首页 > 解决方案 > 在 Firebase 实时数据库中为 ChildByAutoID 编写规则?

问题描述

JSON:

  "people" : {
    “user uid” : {
      “**Domain** : "aol.com",
      "peopleWhoLike: {
        "-M-vZavBdcpX3SzkvgKN" : "**IrrBgFY9C1ekMmHUkQRzc5LhbDu1**", ////this is autokey: uid of the likeR///
    }
  }

假设您要评估 IrrBgFY9C1ekMmHUkQRzc5LhbDu1。如果他没有通过 childByAutoID 进行,我会使用这个:

,"peopleWhoLike" : {
"$peopleWhoLike_id": {
    ".read": "auth.uid != null",
    ".write": "$peopleWhoLike_id == auth.uid && data.parent().parent().child('domain').val() == data.parent().parent().parent().child(newData.val()).child('domain').val()"
} /////checks domain of like with domain of person he likes, and makes sure only he can write for himself.

如果 IrrBgFY9C1ekMmHUkQRzc5LhbDu1 没有 ChildByAutoID,这会很好,但事实并非如此。所以现在我想我需要使用类似 $ChildByAutoID 的东西,但我不确定如何调用它,因为它没有在 JSON 中明确定义。

我为 $ 变量阅读的安全规则来源:https ://firebase.google.com/docs/database/security/rules-conditions

标签: jsonfirebase-realtime-databasefirebase-authenticationfirebase-security

解决方案


我正在添加另一个答案,专门解决问题的规则部分

目标是仅当该节点中的域与当前用户域节点匹配时才允许对该节点进行写入。我不会编写所有规则,但这将是第一步:

结构将是

people
   uid_0
      domain: "aol.com"
   uid_1
      domain: "gmail.com"
users
   uid_2
      domain: "aol.com"
   uid_3
      domain: "aol.com"

规则将类似于

{
  "rules": {
    ".read": false,
      ".write": false,
        "people": {
          "$uid": {
            ".read": "auth != null",
            ".write": "root.child('people').child($uid).child('domain').val() === 
                       root.child('users').child(auth.uid).child('domain').val()" 
          }
        }
  }
}

如果 /people/uid_x/domain = /users/this_uid/domain 的值,则允许写入

使用上述结构,用户 uid_2 和 uid_3 可以写到 people/uid_0 但不能写到 people/uid_1


推荐阅读