2016-04-26 118 views
0

我一直在开发项目中使用Firebase一段时间,但到目前为止并没有太多担心安全问题。从现在开始,我想实施一些安全规则。我已阅读关于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字段中的Names部分。

我要的是:

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字段,因为我没有它的父级名称。

+0

只是一个念头。为什么不使用用户ID而不是一些随机生成的ID? –

+0

这在这里不起作用,因为一个用户可能有很多记录。随机生成的id实际上是从childByAutoId()中取出来的,当创建一个新记录时,取出关键部分。这部分没有问题。 – Michel

回答

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" 
      } 
     } 
     } 
    } 
}