为 auto-id 节点设置 firebase 数据库规则

Setting firebase database rules for auto-id node

我正在尝试为我的应用程序设置 firebase 数据库规则。本质上,该应用程序有一个 posts 页面,允许用户与不同的 posts 进行交互。

我遇到的问题是,当我尝试在“$post_id”分支下设置规则时,我的应用程序中没有数据加载,我有一个连续加载屏幕。但如果我从规则中删除这个“$post_id”分支,那么我的应用程序会正确加载。

我的数据库是这样的。如您所见,post 被加载到自动 ID 节点下,这就是为什么我尝试添加 $post_id 来反映这一点。

{
 "rules": {
 "posts": {
  // the key for each post is stored inside $post_id variable for reference
   "$post_id": {
     // general rules
     ".indexOn": ["timestamp", "likes"],
     ".read": "auth != null",
       // enter the author branch 
       "author": {
         ".read": "auth != null",
         "$user_id": {
           ".write": "$user_id === auth.uid"
         }
       },
         //enter the comments branch
         "comments": {
           ".indexOn": ["timestamp"]
         }
   }
 }

1。确保您已通过身份验证。

检查firebase.auth().currentUser != null(对于网络)。
它应该允许您读取 /posts/XXX_some_post_id 路径,因为您在 rules/posts/$post_id.

下有 ".read": "auth != null"

P.S。您甚至不需要 author 下的第二个 ".read": "auth != null",因为来自 /posts/XXX_some_post_id 的相同规则会自动应用于其所有 branches/descendants.

2。检查您正在阅读的路径。

很有可能(我过去犯过同样的错误)您正在尝试从上层 posts 路径而不是 posts/XXX_some_post_id.
读取 这将失败,因为没有为 posts 指定规则。当前仅针对更深一层的 posts/$post_id 提供规则。所以你需要

  • 每次直接从/posts/XXX_some_post_id读取,或者
  • 在帖子下方添加规则:
{
  "rules": {
    "posts": {
      ".read": "auth != null",

      "$post_id": {
        // other rules here
      }
    }
  }
}