Firebase安全性 - 如何允许推送到节点并更新该节点上的子树?

时间:2017-07-04 14:55:27

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

我觉得这是一个非常常见的问题,但是由于我一直在学习Firebase的安全性,我似乎仍然无法解决这个小问题,因为我有一个树节点,我希望能够推送新数据,同时能够更新现有节点。根据Firebase文档,如果您将这些规则放在顶级树中,您应该能够创建/删除,但不能更新:

".write": "!data.exists() || !newData.exists()"

因此,当我使用带有身份验证和所有内容的Firebase数据库模拟器时,我会去模拟一个"写"在路径/social/bands上,但我得到Simulated write denied。我应该注意到,在这条路径中,数据确实存在。

此示例的完整规则如下:

"social": {
   "bands": {
     ".read": "auth != null",
     ".write": "!data.exists() || !newData.exists() && auth != null",
     "$bandId": {
        ".write": "auth != null && data.child('admins').child(auth.uid).val() === true"
     }
   }
}

是否有办法在我的/social/bands树上创建/删除节点,同时能够存在/social/bands/$bandId之类的节点,无论路径中是否存在数据?我觉得这是常见的事情。

我应该注意到,我试图在Ionic 3应用程序的上下文中使用AngularFire来实现这些规则,如果它应该有任何区别(我不相信它会,因为模拟器给我许可错误。)

更新:以下是模拟器失败的屏幕截图:

enter image description here

以下是我试图在模拟器中编写的数据

{
  "admins" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "creator_id" : "ruNdZP2Gx6bqsovL8gMlLJP9g0a2",
  "followers" : 2,
  "genres" : [ "Classical" ],
  "looking_for_musicians" : true,
  "members" : {
    "ruNdZP2Gx6bqsovL8gMlLJP9g0a2" : true
  },
  "name" : "Radiant and the beach",
  "social_profiles" : {
    "soundcloud" : ""
  }
}

我写的路径是/social/bands

以下是模拟器中的身份验证状态:

enter image description here

以下是树中的现有数据,其中一个节点已展开:

enter image description here

错误信息只是我之前提到的模拟器写入拒绝问题。

有什么想法我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

您正试图写信给/social/bands。在该级别,您有一个规则!data.exists()/social/bands下已有数据,例如名为My Awesome Band的频段。由于数据已存在,!data.exists()计算结果为false,写入被拒绝。

如果您希望用户能够添加新频段,则应将该规则下移到JSON中特定频段的级别:

"social": {
   "bands": {
     ".read": "auth != null",
     "$bandId": {
        ".write": "auth != null && (
          !data.exists() || !newData.exists() ||
          data.child('admins').child(auth.uid).val() === true
        )"
     }
   }
}

单词:任何经过身份验证的用户都可以添加或删除某个频段,只有管理员可以修改一个频段。