【问题标题】:Firebase firestore rules, read only when document contain specific valueFirebase firestore 规则,仅当文档包含特定值时才读取
【发布时间】:2018-03-29 03:15:11
【问题描述】:

我正在通过官方doc 学习安全规则,但我无法使其发挥作用。

在我的集合users 下的文档user 中有一些映射值,其中之一是role: "guest"。角色值可以是"guest" or "superAdmin"

我只想在role == "superAdmin" 时访问/users

这是我尝试过的

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read: if get(/databases/$(database)/documents/users/$(userId)).data.role == "superAdmin";
    }
  }
}

当我以superAdmin 登录时出现错误

ERROR 错误:权限缺失或不足。

我相信我正确地遵循了文档。并在SO 中发现了一个类似的问题,其中说一些特定于评估查询中的嵌套字段的错误。但我没有嵌套查询。我在这里做错了吗?

这是我的 Firestore 外观

请帮忙。

【问题讨论】:

  • 看起来像 Firestore 中的一个错误,它仍处于测试阶段。找到了替代解决方案here。等待正确答案。

标签: firebase firebase-security google-cloud-firestore


【解决方案1】:

不要使用get(),因为您是在正在读取的位置获取文档,所以只需使用resource(这是该位置的预取文档)对其进行寻址:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read: if resource.data.role == "superAdmin";
    }
  }
}

如果您要到不同的集合获取数据,请仅使用 get()

【讨论】:

    【解决方案2】:

    我认为打破它的部分是allow read: if get(/databases/$(database)/documents/users/$(userId))。在这里,您正在比较文档的所有者,而不是请求它的人。尝试将userID 替换为request.auth.uid

    【讨论】:

    • 你说得对。我试过了,等了 10 分钟,但不幸的是同样的错误。 if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "superAdmin" 对吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2019-03-03
    • 2023-02-13
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多