Firebase用户全部读取,写入新内容,但只修改自己的数据

Vaz*_*azh 7 authentication rules firebase

我在Firebase上有下一个场景:

有两件事,用户事件.

我希望用户能够创建新事件,查看所有现有事件,但只能修改由他们创建的事件.

这意味着UserOne创建了EventOne,可以看到EventOne和EventTwo,但只能修改EventOne.

我的结构如下:

-events
 -eventOne
    endTime: 
    id: 
    name: 
    providerId: 
    startTime: 
    userId: 
 -eventTwo
    endTime: 
    id: 
    name: 
    providerId:  
    startTime: 
    userId: 
-users
    -userOne
    -userTwo
Run Code Online (Sandbox Code Playgroud)

我目前的规则几乎是默认规则:

{
  "rules": {
    "users": {
      "$uid": {
        // grants write access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",
        // grants read access to any user who is logged in with an email and password
        ".read": "auth != null && auth.uid == $uid"
      }
    },
     "events": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Rob*_*rco 9

要确保所有用户都能看到所有事件,您可以将事件的读取规则设置为true或者auth != null,如果要求读者至少进行身份验证,则可以使用后者.

要确保事件只能由其创建者修改,请将原始作者与事件一起记录并使用它进行验证auth.uid.

{
  "rules": {
    "events": {
      "$eventid": {
        ".read": "auth != null",
        ".write": "auth != null && (!data.exists() || data.child('author').val() === auth.uid) && newData.hasChild('author')",
        "author": {
          ".write": "newData.val() === auth.uid"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

上面,我们!data.exists()用来检查这个位置是否存在现有事件.如果不存在任何事件,则任何人都可以在此位置添加一个.接下来,data.child('author').val() === auth.uid确保如果事件存在,则只有作者可以修改它.