Firebase安全规则以读取部分对象

时间:2019-01-09 01:30:05

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

我不知道如何使用Firebase数据库过滤数据。我读过规则不能用于过滤器。但是那又如何呢?

我想要一个类似于下面的数据结构。即不同用户在指定时间内创建的帖子列表(由于无法确定放置位置,因此下面的布局中未包含用户ID)

posts: {
  "-LKwbZsfy55d24kwX4t1" : {
      when: {
        from: "2019-01-01 10:00",
        to: "2019-01-01 11:00"
      content: {
        text: "Hello"
      }
  },
  "-LKwbZsfy55d24kwX4t2" : {
      when: {
        from: "2019-01-02 10:00",
        to: "2019-01-02 11:00"
      content: {
        text: "Another hello"
      }
  }
}

我希望每个人都能阅读所有帖子,因此我的同步路径为'/ posts'

只有创建帖子的用户才能看到“内容”。因此,我不知何故要说帖子具有“ .read”:true,内容具有“ .read”:$ uid == auth.uid(这是不可能的,因为无法通过子路径撤消访问)

2 个答案:

答案 0 :(得分:2)

如果您当前的数据结构使得无法根据需要保护数据,请考虑对其进行重组,以使安全规则成为可能。换句话说,不要将受保护的数据嵌套在公共数据下。将受保护的数据放在其自己的顶级子级中。

"posts-public": {
    "-LKwbZsfy55d24kwX4t1": {
        // public data here
    }
},
"posts-private": {
    "-LKwbZsfy55d24kwX4t1": {
        // private data here
    }
}

现在,您可以编写安全规则以彼此独立地保护它们。

答案 1 :(得分:0)

".read": "true",让每个人都可以读取数据

它应该看起来像这样(仅作为示例)

"posts": {
      ".read": "true",
      "$postId": {
        ".read": "true",
        ".validate": "root.child('posts/'+$postId).exists()",
        "$contentId": {
            ".read": "auth !=null",
            ".write": "auth != null",
            ".validate": "(newData.hasChildren(['content']))",
             "content": {
                ".validate": "newData.val().length > 0"
            },
           "user": {
             ".validate": "newData.hasChildren(['id', 'name', 'avatar'])"
           }
         }
      }
    },
    "privatePost": {
      "$uid1": {
        "$uid2": {
          ".read": "auth != null && ($uid1 === auth.uid || $uid2 === auth.uid)",
          "$postId": {
            ".write": "auth != null",
            ".validate": "(newData.hasChildren(['content']))",
            "content": {
              ".validate": "newData.val().length > 0"
        },
            "user": {
              ".validate": "newData.hasChildren(['id', 'name', 'avatar'])"
            }
          }
        }
      }