【问题标题】:Firestore Security Rules "get()" not working?Firestore 安全规则“get()”不起作用?
【发布时间】:2021-05-12 10:48:44
【问题描述】:

我有一个结构如下的 Firestore 集合: /database/{database}/documents/group/{group}/...

每个组都有一个名为“members”的字段,它是一个用户 ID 数组:

group: {
    members: [
        "user01",
        "user02",
    ]
}

我在这个集合上有一个 iOS (Swift) 快照监听器:

Firestore.firestore().collection("group").whereField("members", arrayContains: Auth.auth().currentUser.uid)
            .addSnapshotListener {...

如果我将 Firestore 规则大部分打开时,这会起作用:

match /group/{group}/{document=**} {
    allow read: if request.auth.uid != null;
}

但是,当我尝试保护集合以仅允许上述快照(而不是对集合中其他文档的请求)时,我的权限不正确。这是我尝试过的:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /group/{group}/{document=**} {
      allow read: if request.auth.uid in get(/database/$(database)/documents/group/$(group)).data.members || request.auth.uid in get(/database/$(database)/documents/group/$(group)).members;
    }
  }
}

我也试过了:

match /group/{group} {
    allow read: if request.auth.uid in resource.data.members;
}

这似乎有效,但不允许我访问文档的子集合。我需要 get() 规则方法才能工作。

类似的解决方案似乎对其他人也适用于 SO。是否有另一种方法允许对文档和子集合进行这种类型的权限,或者我可能忽略了这个解决方案明显的一些东西?


编辑

通读more docs后,看来此解决方案有效:

match /group/{group} {
    allow read: if request.auth.uid in resource.data.members;
    match /child_collection/{document=**} {
        allow read: if request.auth != null;
    }
}

我会花一些时间将其列为答案,以防更有经验的人有更好的解决方案。

【问题讨论】:

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


    【解决方案1】:

    通读more docs后,看来此解决方案有效:

    match /group/{group} {
        allow read: if request.auth.uid in resource.data.members;
        match /child_collection/{document=**} {
            allow read: if request.auth != null;
        }
    }
    

    如果有人对使用 get() 的解决方案提出意见,那也将非常有帮助!

    【讨论】:

    • 感谢您添加答案,请考虑将其标记为正确!
    • @Juancki 我希望收到一些关于我在使用get() 方法时做错了什么的反馈,因为我也应该能够使用它。但是,如果我没有很快收到基于get() 的答案,我会将此标记为已回答。谢谢!
    猜你喜欢
    • 2018-03-19
    • 2019-01-31
    • 2021-11-22
    • 2019-09-06
    • 2018-05-28
    • 2020-08-24
    • 1970-01-01
    • 2019-12-14
    相关资源
    最近更新 更多