在Firebase实时数据库中为ChildByAutoID编写规则?

时间:2020-09-09 15:15:59

标签: json firebase-realtime-database firebase-authentication firebase-security

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

2 个答案:

答案 0 :(得分:1)

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

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

结构应为

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

答案 1 :(得分:0)

在此用例中,没有理由在peoplWhoLikeMe中使用childByAutoId,这会使规则变得更加复杂。

您知道要存储的特定数据,因此只需使用占位符存储该数据即可。

换句话说,我假设您要存储用户的UID,因此您的结构应为

people
   this_users_uid
      domain: "aol.com"
      people_who_like_me
          uid_0: true
          uid_3: true

这极大地简化了规则,因为当另一个用户写入people_who_like_me节点时,只需验证所写入的密钥是他们自己的uid。它还保证了唯一性,因此子节点永远不会重复。