【问题标题】:Firebase rules: Unknown variable '$uid'Firebase 规则:未知变量“$uid”
【发布时间】:2021-04-09 11:42:46
【问题描述】:

我希望用户只能访问他们自己的内容,除了一个子节点:common
common 子节点中,我希望所有登录用户都可以访问。 我制定了以下规则:

{
  "rules": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      },
        "common" : {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }    

Firebase 给了我错误:

错误保存规则 - 第 8 行:未知变量 '$uid'。

错误出现在这一行:".read": "auth != null && auth.uid == $uid",

【问题讨论】:

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


    【解决方案1】:

    根据您的问题,这是您想要的数据库结构:

    {
      "userIdA": { // anything here can be written by only userIdA
        "name": "Tom", // this is just example data
        "location": "London",
        /* ... */
      },
      "userIdB": { // anything here can be written by only userIdB
        "name": "Sarah",
        "location": "New York",
        /* ... */
      },
      /* ... other user data ... */
      "common": { // anything here can be written by signed in users
        "data1": "some value",
        "data2": "some other value",
      }
    }
    

    这种结构的规则是:

    {
      "rules": {
        "common" : {
          ".read": "auth != null", // logged in users can read
          ".write": "auth != null" // logged in users can write
        },
        "$uid": { // $uid will be the value of any key, that isn't listed above it (in this case, anything other than "common")
          ".read": "$uid === auth.uid", // only the matching user can read
          ".write": "$uid === auth.uid" // only the matching user can write
        }
      }
    }
    

    注意:这种数据结构不是很安全。仅允许对数据库中需要的内容进行读/写访问。使用这种结构,任何用户都可以打开他们的控制台并删除"/common" 下的所有内容。您可以考虑添加".validate" 规则以确保某些键(例如"/common/data1")只是字符串。

    【讨论】:

      【解决方案2】:

      $uid 必须在 users 文档中,如下例所示:

       {
        "rules": {
          "users": {
            "$uid": {
              ".read": "$uid === auth.uid",
              ".write": "$uid === auth.uid"
            }
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 1970-01-01
        • 2020-12-23
        • 2021-12-10
        • 2020-06-10
        • 2018-09-03
        • 1970-01-01
        • 2019-11-14
        • 2017-06-08
        相关资源
        最近更新 更多