如何在firebase数据库中实现基于用户的安全性?

时间:2016-11-18 17:57:47

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

这是数据库,例如:

"Messages" : {
      "Message1" : {
               "Uid" : "sampleid1"
                "Text" : "hi"
                },
       "Message2" : {
                "Uid" : "sampleid2"
                "Text" : " hello"
                }
  }

我只希望那些用户阅读其uid等于Uid的{​​{1}}字段的邮件。

firebase文档中给出的数据库结构(即在数据库中使用基于用户标识的消息,其中每条消息的节点代表发送消息的用户的uid)不能实现我的项目的目标,因为我需要每次任何用户发送消息时,都要知道发送消息的用户的uid。

因此,请提出有助于我完成本课题所述任务的规则

此外,当我在上述数据库结构上应用某些规则时,我无法读取任何数据,因为“firebase规则不是过滤器”。

请忽略上面例子中写的json的语法和格式,因为它仅供参考

请帮忙!

1 个答案:

答案 0 :(得分:0)

构建您的数据:

"messages" : {
  "<receiver_uid>" : {
      "msg_1" : {
         "text" : "Hello world...",
         "uid" : "<sender_uid>"
      }
      // more msgs for this receiver ...
   }
}

规则应该类似

{ 
  "rules" : {
    "messages" : {
      "$receiver" : {
        ".read" : "auth.uid == $receiver", // only receiver shall read
        ".write" : "auth != false" // any authenticated user can write
      }
    }
  }
}