我有一个名为(people)的数据库节点,如下所示:

    people
    |
    |
    -------UserID1 //which is a random id
    |       |
    |       |
    |        ----UserId2 //which is a random id
    |            |
    |            |
    |            name:"some_name"
    |            id:"UserId2"
    |            image:"image_url"
    |
    |
    |
    -------UserId2
            |
            |
             ----UserId3
                 |
                 |
                 name:"some_name"
                 id:"UserId3"
                 image:"image_url"


如果我们查看(people / UserID1 / UserId2)节点:

由于UserId1和UserId2是2个随机ID,因此如果我们要向UserId2写入规则,我们将注意到它的深度为2个随机ID。

我要在此指定的路径上写一条规则,内容如下:

1)people / UserId1:可以由(UserID1)和(UserId2)编写。

2)people / UserId1:可由(UserID1)和(UserId2)读取。

3)people / UserId1 / UserId2:必须以具有(名称,ID,图像)的newData结尾。

我该怎么做呢?

谢谢。

最佳答案

由于Firebase Realtime Database将cascade规则化为更深的密钥的方式,因此不建议允许people/UserId1UserId2写入,因为这将允许UserId2对存储在people/UserId1下的其他用户的数据进行写访问。就像people/UserId1/UserId3

但是,利用这一特征,我们可以在数据结构中“添加”具有读写权限的用户。

因此,新条件是:


people/UserId1-UserId1具有读写访问权限
people/UserId1/UserId2-UserId2具有读写访问权限
people/UserId1/UserId2-必须始终包含“名称”,“ id”和“图像”键
people/UserId1/UserId3-UserId2无法读取/写入


{
"rules": {
  "people": {
    "$userId1": {
      "$userId2": {
        ".read": "auth.uid == $userId2", // add $userId2 to those granted read permission, cascades into deeper keys
        ".write": "auth.uid == $userId2", // add $userId2 to those granted write permission, cascades into deeper keys
        ".validate": "newData.hasChildren(['name', 'id', 'image'])" // any new data must have 'name', 'id' and 'image' fields.
      },
      ".read": "auth.uid == $userId1", // add $userId1 to those granted read permission, cascades into deeper keys
      ".write": "auth.uid == $userId1" // add $userId1 to those granted write permission, cascades into deeper keys
    }
  }
}


最后,如果还要求people/UserId1/UserId2/id等于UserId2,则可以更改".validate"规则以强制执行此操作:

".validate": "newData.hasChildren(['name', 'id', 'image']) && newData.child('id').val() == $userId2" // any new data must have 'name', 'id' and 'image' fields and 'id' must have a value of $userId2

08-16 15:04