如何通过规则授予特定用户访问多个 Firestore 文档的权限

时间:2021-01-08 06:56:18

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

我想授予特定用户组访问特定文档的权限。如下图所示。我想为 users 集合中的 usergrp1 授予对 Doc1Doc3 的访问权限。如何使用 Firestore 规则做到这一点。

文档集合

enter image description here

包含群组文档的用户集合

enter image description here

1 个答案:

答案 0 :(得分:1)

为了访问给定文档的安全规则中的其他 Firestore 文档,您应该使用 get()exists() 函数,如 doc 中所述。

但是,如果将某个组的每个用户保存在“组”文档的特定字段中(如我们在屏幕截图中所见),则会遇到一些困难,因为您需要知道要检查哪个字段。< /p>

我建议按如下方式执行:对于属于组的每个用户,使用用户 uid 作为字段名称并分配一个虚拟值(例如 true)。然后您可以轻松地检查该字段是否存在于文档中,例如,通过使用 in 运算符和 get() 函数:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /docs/{docId} {
      allow read: if request.auth != null && request.auth.uid in get(/databases/$(database)/documents/users/usergrp1).data
    }
  }
}

但是,在上面的规则中可以看到有一个问题:组名是硬编码的...

为了让 docs 集合中的每个特定文档都有一个组值(例如 doc1 可以允许 usergrp1 的用户阅读),您需要保存,在文档,可以访问它的组的名称。

如果您将组名保存在名为 authorizedGroup 的字段中,您可以通过再次使用 get() 函数来调整规则如下:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /docs/{docs} {
      allow read: if request.auth != null && request.auth.uid in get(/databases/$(database)/documents/users/$(get(/databases/$(database)/documents/docs/$(docs)).data.authorizedGroup)).data
    }
  }
}