Firebase Firestore 规则,仅在文档包含特定值时读取

Firebase firestore rules, read only when document contain specific value

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

在我的 collections 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 Error: Missing or insufficient permissions.

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

这是我的 Firestore 外观

请帮忙。

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

而不是使用 get(),因为您是在您正在阅读的位置获取文档,只需使用 resource 解决它(这是该位置的预取文档):

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

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