Firebase实时数据库添加基于 child 的规则

标签 firebase firebase-realtime-database

我已经制定了规则

(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 的预期值是多少。所以我假设它只是规则中未使用的一些随机字符串。

对于每个安全规则,可以使用 predefined variable 访问节点的当前数据数据".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 作为 key ,因为安全规则无法执行诸如“用户 ID 是否具有”之类的查询管理员角色?”无需构建您的数据以允许它。如果 $key 是用户名,请改用用户名到用户 ID 映射,因为它可以防止将来出现问题。一个这样的例子是,如果用户想要更改他们的用户名,您可以删除新用户名并将其链接到该用户,而无需移动他们的所有数据。

关于Firebase实时数据库添加基于 child 的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585200/

相关文章:

java - 火力地堡 : How to search all objects with same value in whole database or nested database

javascript - puppeteer 师 typescript : Fails with errors when transpilling

Firebase:允许读取管理员的集合和用户的特定记录

logging - 关闭 Firebase logcat 日志记录

javascript - 新的 Firebase () 函数已弃用?

ios - Firebase authWithOPopup ("facebook") 不会重定向,留在白屏上

angular - 使用 firebase cloud pub/sub 在聊天应用程序中实现 "Someone is typing..."功能

android - getContactsFromFirebase() 方法返回一个空列表

android - Firebase 安卓订购

swift firebase 查询不起作用