【问题标题】:Complex Firebase Security Rule复杂的 Firebase 安全规则
【发布时间】:2017-08-07 05:17:01
【问题描述】:

我的 Firebase 数据结构看起来像

-isAdmin 
    -user1
        isAdmin: true

-users
    -user1 
        -firsName: Jane
        -lastLoggedIn: 12 March 2017
    -user2
        -firstName: John
        -lastLoggedIn: 11 March 2017

我希望我的管理员(用户 1)能够执行以下操作

将更多用户添加到 -users 分支。所以我需要以下权限(创建 user3、user4...等)

"users": {
    .write: "(auth != null) && (root.child('isAdmin').child(auth.id).val == true)
}

但是我也希望非管理员用户能够更新 lastLoggedIn 条目。所以我需要以下权限

"users": {
    $userId: {
        "lastLoggedIn": {
            .write: "(auth != null) && ($userId == auth.id)   
        }
    }
}

但问题是,firebase 不允许嵌套规则,因为我在 users 下有一个 .write 规则,我相信 users/$userId/lastLoggedIn 下的 .write 规则将被忽略

有没有办法解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    Firebase 安全规则不允许嵌套规则是不正确的 - 他们确实如此。规则级联和您需要注意的情况是,一旦授予权限,它就不能被“嵌套”规则撤销。

    因此,只有在更高级别的规则已经授予写入权限时,才会忽略“嵌套”规则。如果尚未授予写入权限并且“嵌套”规则授予写入权限,则不会忽略它。

    使用这些规则:

    "users": {
      ".write": "(auth != null) && (root.child('isAdmin').child(auth.uid).val == true),
      "$userId": {
        "lastLoggedIn": {
          ".write": "(auth != null) && ($userId == auth.uid)
        }
      }
    }
    

    管理员和用户自己都可以写信给lastLoggedIn

    【讨论】:

    • 感谢您的及时答复。我已经在 firebase 模拟器中验证了结果,并确认这是正确的。
    猜你喜欢
    • 2017-08-05
    • 2016-06-27
    • 1970-01-01
    • 2016-08-19
    • 2018-11-09
    • 2020-09-06
    • 2016-07-16
    相关资源
    最近更新 更多