【问题标题】:Firebase user read all, write new, but only modify his own dataFirebase 用户读取所有数据,写入新数据,但只修改自己的数据
【发布时间】:2015-10-22 13:08:13
【问题描述】:

我在 Firebase 上有下一个场景:

有两件事,用户事件

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

意思是UserOne创建了EventOne,可以看到EventOne和EventTwo,但是只能修改EventOne。

我的结构如下:

-events
 -eventOne
    endTime: 
    id: 
    name: 
    providerId: 
    startTime: 
    userId: 
 -eventTwo
    endTime: 
    id: 
    name: 
    providerId:  
    startTime: 
    userId: 
-users
    -userOne
    -userTwo

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

{
  "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"
    }
  }
}

提前致谢。

【问题讨论】:

    标签: authentication firebase rules


    【解决方案1】:

    为确保所有用户都能看到所有事件,您可以将事件的读取规则设置为 trueauth != 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"
            }
          }
        }
      }
    }
    

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

    【讨论】:

    • 感谢您的快速回答!我只需在“规则”下方添加".read":"auth != null" 以确保它们可以阅读
    • 如果我在.validate中设置newData.hasChild('author')是一样的吗?
    • @vzhen 只要您还验证 'author' 的值是否与您想要的匹配(即身份验证令牌中的某些内容)。
    • @vzhen 不太一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多