【问题标题】:How can Firestore check a collection to allow write (rules)Firestore 如何检查集合以允许写入(规则)
【发布时间】:2018-07-02 15:34:32
【问题描述】:

我在 Firestore 中使用一个名为“admin”的集合来定义哪些用户可以编写新文档(下图)。

目前,它仅由软件控制。我想向 Firestore 添加规则。我尝试了以下规则,但没有奏效。在这种情况下,正确的规则是什么?

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth != null;
      allow write: if get(/admin/{anyDocument}).data.userId == request.auth.uid;
    }
  }
}

【问题讨论】:

    标签: firebase firebase-realtime-database firebase-authentication google-cloud-firestore


    【解决方案1】:

    我建议改为使用带有admin 字段的users 集合,该字段可以设置为true/false。然后您可以执行以下操作:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read: if request.auth != null;
          allow write: if get(/users/${request.auth.uid}).data.admin == true;
        }
      }
    }
    

    【讨论】:

    • request.auth.uid 来自哪里?
    • 如果客户端通过 Firebase Auth 进行身份验证,使用 Firestore SDK 时将自动填充 request.auth
    • 如果我想在特定集合中设置规则怎么办?我该怎么做
    【解决方案2】:

    据我所知,这在您当前的数据库结构中是不可能的。因为除非在 admin 节点中,否则在 Firestore 规则中无法访问推送键。

    一种方法是将admin 与他们的uid 保存为admin/userID/data... 之类的密钥

    现在你可以访问它了

    allow write: if get(/databases/$(database)/documents/admin/$(request.auth.uid)).data.userId == request.auth.uid;;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2018-12-26
      • 1970-01-01
      相关资源
      最近更新 更多