【问题标题】:Problem with Firebase Realtime Database Rules "data.child('uid').val() === auth.uid" not workingFirebase 实时数据库规则“data.child('uid').val() === auth.uid”不工作的问题
【发布时间】:2021-06-15 16:19:07
【问题描述】:

我正在使用 firebase 实时数据库,我希望用户仅在使用其用户 ID 登录时输入数据。

{
  "rules": {
    "Posts2":{
      ".read":true,
      ".write": "data.child('uid').val() === auth.uid"
    }
  }
}

添加了此规则,但它不起作用我正在使用 Rules Playground,但它显示错误。

*模拟结果

  • 类型:设置
  • 位置:/Posts2
  • 数据:{ "key": "value", "uid":"1234few" }
  • 认证:{ "provider": "google", "uid": "1234few" }
  • 管理员:false
  • 写入被拒绝
Line 5 (/Posts2)

write: "data.child('uid').val() === auth.uid"

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    您当前的规则规定,只有当该位置的数据具有带有当前用户的用户 ID 的子属性 'uid' 时,您才能写入该位置。

    但是,如果该位置没有数据怎么办? data.child('uid').val() 将是 null,与当前用户 ID 不匹配。所以我们需要先检查数据是否存在,然后检查现有数据或新数据以确保用户ID匹配。

    {
      "rules": {
        "Posts2":{
          ".read": true,
    
          // if the post already exists, the editing user must have a matching user ID
          // if the post doesn't exist, the stored user ID must match the current user
          // allows creation
          ".write": "(data.exists() && data.child('uid').val() == auth.uid) || (!data.exists() && newData.child('uid').val() == auth.uid)"
        }
      }
    }
    

    虽然上述规则有效,但它们还允许用户将帖子的所有权转让给可能导致审核问题的任何其他用户。因此,无论帖子当前是否存在,我们都应确保任何新数据都具有匹配的用户 ID。

    {
      "rules": {
        "Posts2":{
          ".read": true,
    
          // if the post already exists, the editing user must have a matching user ID
          // after the write completes, the stored user ID must match the current user
          // allows creation
          ".write": "newData.child('uid').val() == auth.uid && (!data.exists() || data.child('uid').val() == auth.uid)"
        }
      }
    }
    

    上述规则允许创建帖子,但不能删除。如果这也需要,您现在可以使用:

    {
      "rules": {
        "Posts2":{
          ".read": true,
    
          // if the post already exists, the editing user must have a matching user ID
          // if the post will exist, the editing user must have a matching user ID
          // allows creation and deletion
          ".write": "(!data.exists() || data.child('uid').val() == auth.uid) && (!newData.exists() || newData.child('uid').val() == auth.uid)"
        }
      }
    }
    

    注意:与 JavaScript 不同,== and === are the same operator 在实时数据库安全规则中

    【讨论】:

    • 不! @samethecodingman 再次给出同样的写入被拒绝错误也无法正常工作。
    • @Areeb 请将要添加到数据库中的数据和代码添加到导致问题写入错误的数据库中。此处发布的规则已经过测试。
    • 我正在使用 firebase 规则操场,并在问题中给出了它作为模拟结果
    • @Areeb 这些规则已针对您所描述的规则游乐场进行了测试。规则游乐场将与您的实时数据库进行交互 - 这表明您的数据库中有一个 /Posts2/uid 并且未设置为 "1234few"
    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2017-04-16
    • 2018-01-19
    • 2017-06-08
    • 2016-11-16
    相关资源
    最近更新 更多