【问题标题】:Firebase realtime database add rule based on childFirebase 实时数据库添加基于子节点的规则
【发布时间】:2019-08-30 07:08:48
【问题描述】:

我把规则设置为

(root.child('users').child(auth.uid).child('role/cafe').val() === true)

在我的实时数据库规则中。

我的用户是

key {
 uid: xxxx 
 name: xxxx
 role:{
  cafe: true
  user: false
  }
}

如果 auth.uid 等于 key,则该规则有效,但是如何修改上述规则以在数据中查找 uid

【问题讨论】:

  • $key 的期望值是多少?当您要查找用户的数据时(例如在另一个规则中),如何获取$key 的值?由于这些原因,我强烈建议不要将其设置为用户 ID 以外的任何内容并使用查找索引(例如用户名:uid)。

标签: firebase firebase-realtime-database


【解决方案1】:

您可以使用通配符。在你的规则中

"users":{
  "$key":{
    ".read" : (root.child('users'+$key).child('role/cafe').val() === true) && (root.child('users'+$key).child('uid').val() === auth.uid  ),
    ".write" : (root.child('users'+$key).child('role/cafe').val() === true  ) &&(root.child('users'+$key).child('uid').val() === auth.uid  )
  }
},

第一个条件检查用户的cafe值是否为真,第二个条件检查uid是否相同

【讨论】:

    【解决方案2】:

    目前还不清楚$key 的预期值是多少。所以我假设它只是一些没有在规则中使用的随机字符串。

    对于每个安全规则,可以使用predefined variable data 访问节点的当前数据。 ".write"".validate" 规则也可以作为newData 访问要写入的数据。这些都是RuleDataSnapshot 对象。

    假设进行更改的用户必须是uid属性给定的用户,可以使用以下规则。

    "rules": {
      "users": {
        "$key": {
          ".read": "auth != null && data.child('uid').val() == auth.uid",
          ".write": "auth != null && ((data.exists() && data.child('uid').val() == auth.uid) || (!data.exists() && newData.child('uid').val() == auth.uid)"
        }
      }
    }
    

    上述规则使用fail-fast 方法。如果用户未登录,则检查中止。否则,用户的 ID 将与给定节点上的现有数据进行匹配。如果数据尚不存在,则新更新的数据也必须与当前用户的 ID 匹配。

    如果“cafe”角色很重要,以下规则还要求将“cafe”设置为true 以允许读/写操作。

    "rules": {
      "users": {
        "$key": {
          ".read": "auth != null && data.child('uid').val() == auth.uid && data.child('role/cafe').val() == true",
          ".write": "auth != null && ((data.exists() && data.child('uid').val() == auth.uid && data.child('role/cafe').val() == true) || (!data.exists() && newData.child('uid').val() == auth.uid && newData.child('role/cafe') == true))"
        }
      }
    }
    

    注意:如果$key 存储用户信息/数据,我强烈建议使用用户ID 作为密钥,因为安全规则无法执行诸如“用户ID 是否具有管理员角色?”之类的查询。无需结构化您的数据以允许它。如果$key 是用户名,请改用用户名到用户ID 映射,因为这样可以防止将来出现问题。一个这样的例子是,如果用户想要更改他们的用户名,您可以删除新用户名并将其链接到该用户,而无需移动他们的所有数据。

    【讨论】:

    • key是firebase自动生成的id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2021-08-16
    • 2019-12-17
    相关资源
    最近更新 更多