【问题标题】:Setting firebase database rules for auto-id node为 auto-id 节点设置 firebase 数据库规则
【发布时间】:2021-07-14 10:39:43
【问题描述】:

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

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

我的数据库看起来像这样。如您所见,帖子是在自动 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"]
         }
   }
 }

【问题讨论】:

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


    【解决方案1】:
    1.确保您已通过身份验证。

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

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

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

    【讨论】:

    • 嗨 Bulat,我还是有点困惑。你的意思是我应该重新格式化我写规则的方式吗?你能给我举个例子来说明你的意思吗?
    • { "rules": { "posts": { // 一般规则 ".read": "auth != null", ".indexOn": "timestamp", // 每个的键post 存储在 $post_id 变量中以供参考 "$post_id": { //other rules } } } } }
    • 嘿,是的,这对我来说是正确的。有帮助吗?它还取决于您访问数据的方式。您还可以分享您从数据库中读取的代码行吗?
    • 酷!我很高兴它有帮助
    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2017-11-30
    • 2020-02-28
    相关资源
    最近更新 更多