Firebase简单博客(与安全规则混淆)

时间:2015-12-27 10:34:42

标签: authentication reactjs firebase

我试图创建一个基于React + ReactFire的简单todo或博客系统。

经过一个小时的阅读后,firebase教程对配置firebase安全规则感到困惑。

保存元素代码:

this.props.itemsStore.push({
    text : this.state.text,
    done : false,
    user : this.props.user.uid
})

一切都好,但我怎么能得到所有记录只拥有但授权用户?

此规则不起作用:

  "rules": {
    "items" : {
         ".write" : "auth !== null",
         "$item" : {
            ".read": "data.child('user').val() == auth.uid"
         }
    }
  }

似乎没有办法只为一个用户获取所有记录,使用安全规则,而不是这个,我应该使用像filter这样的东西。但同样,我不知道如何在ReactFire中过滤元素,在手册中也没有任何信息。

作为示例,它如何在Parse export srt files

中起作用

2 个答案:

答案 0 :(得分:0)

Firebase安全模型有两个常见的陷阱:

  1. permissions cascade:一旦您在特定级别授予了读取或写入权限,就无法在较低级别取消此权限

  2. rules are not filters :(这实际上是上一次陷阱的结果)您不能使用安全规则为特定用户返回子级的不同子集。用户可以访问节点,或者他们无权访问该节点。

  3. 你似乎陷入了第二次陷阱。虽然用户可以访问他们是user的每个特定消息,但他们无法查询更高级别的items节点,因为他们没有读取权限。

    如果要保护特定用户的消息/待办事项列表,则需要为该特定用户存储该数据。

    items_per_user
        $uid
            $itemid: true
    

    这在NoSQL数据库中很常见,通常称为非规范化。请参阅Firebase网站上的this article called "denormalization is normal"。就Firebase API而言,它有点过时,但非规范化的架构原则仍然适用。

    然后要显示用户的项目,您需要:

    ref.child('items_per_user')
       .child(ref.getAuth().uid)
       .on('child_added', function(snapshot) {
           ref.child('items')
              .child(itemId.key())
              .once('value', function(itemSnapshot) {
                   console.log(itemSnapshot.val());
              });
       })
    

    许多Firebase新手认为内部循环加载数据的速度太慢。但是Firebase在处理多个请求时非常有效,因为它只为每个客户端打开一次连接并管道内部循环中的所有请求。

答案 1 :(得分:0)

请注意,规则不是过滤器。它们允许根据标准访问节点。

这是一个简单的结构示例,其中用户0和1在其节点中存储了文本数据。

数据结构

ToDo
  a_user_id_0
    text: "some text"
    done: yes
  a_user_id_1
    text: "another text"
    done: no

规则

在此示例规则中,用户只能从ToDo节点中属于它们的节点读取/写入,因此路径$ user_id将等于其auth.id.它假设用户也已经过身份验证。

"ToDo": {
   "$user_id": {
      ".read": "auth != null && $user_id == auth.uid",
      ".write": "auth != null && $user_id == auth.uid"
   }
 }

如果user_0已被授权并尝试从a_user_id_1节点读取/写入数据,则会失败。