使用Firebase的安全规则

时间:2016-04-26 04:11:29

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

我一直在开发项目中使用Firebase一段时间,但到目前为止还没有过多担心安全问题。从现在开始,我想实现一些安全规则。我在Firebase网站上阅读了有关该主题的快速入门教程,但我还不确定它们是如何组合在一起的。

这是我数据的结构:

myApp
- DataList
    - Contents
        - randomKey_One
            value: "grgrsgs;jj…data…data.."
        - randomKey_Two
            value: "43efdsd7gs;jj…data…data.."
        - randomKey_Three
            value: "8dfsvshj…data…data.."
        …….
    - Names
        - randomKey_One
            - authorID: "PeterLogID"
            - name: "RecordOne_Peter"
        - randomKey_Two
            - authorID: "JohnLogID"
            - name: "RecordStar_byJohn"
        - randomKey_Three
            - authorID: "PeterLogID"
            - name: "RecordTwo_Peter"
        …….

内容和名称之间存在一对一的对应关系,它通过randomKey_One,randomKey_Two,... .etc的值建立。 创建新记录时会自动生成这些键。我将用户的登录ID存储在“名称”部分的authorID字段中。

我想要的是:

1) To have read access for the whole world to all the data (possibly with the exception of authorIDs).
2) To give write(and delete) access to a record, only if the authorID field matches auth.uid (i.e. the logged in user).

我已经弄清楚第1部分),忘记了“authorIDs的例外”。 我如何使用第2部分)? 我在这一点上尝试过的东西不起作用。 我遇到的一个问题是我不知道如何访问安全规则脚本中的authorID字段,因为我没有其父级的名称。

1 个答案:

答案 0 :(得分:1)

对于那些可能有一天会遇到同样问题并阅读此内容的人。 几个小时后,我在这里提出了我想出的解决方案。由于这是我第一次处理Firebase安全规则,欢迎任何有关此主题的专家发表评论。

{
    "rules": {
      ".read": true,
      "DataList": {
        "Names": {
          "$Name": {
             ".write": "newData.child('authorID').val() === auth.uid || data.child('authorID').val() === auth.uid"
          }
        },
        "Contents": {
          "$Content": {
            ".write": "root.child('DataList/Names/'+$Content).exists() && root.child('DataList/Names/'+$Content).child('authorID').val() === auth.uid"
          }
        }
      }
    }
}
相关问题