【问题标题】:Setting Firestore security rules with Collections generated at runtime使用运行时生成的集合设置 Firestore 安全规则
【发布时间】:2018-07-17 15:38:02
【问题描述】:

每当新用户注册我的应用时,我的 Firestore 数据库都会创建一个新集合。集合的名称是新用户的用户名。我想让这个集合中的文档具有受限的写访问权限。

service cloud.firestore {
  match /databases/{database}/documents {

    match /User1/{info} {
      allow read: if signedIn();
      allow write: if isOwner(User1);
    }

    function signedIn() {
        return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId;
    }    
  }
} 

如果当前用户是User1,则此方法有效,但不适用于任何注册的新用户。如何将此 Firestore 安全规则添加到每个新用户?

【问题讨论】:

  • 每个用户都有一个集合可能不是一个好主意。考虑改为使用每个用户使用他们的 uid 的文档,然后根据需要在其下使用子集合。
  • 唯一的问题是我正在为我的应用程序使用 Flutter,我无法弄清楚如何访问 Flutter 中的子集合。
  • 您应该能够使用 DocumentReference 上的某些方法访问子集合,可能称为 collection()。

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


【解决方案1】:

我注意到第一条规则匹配/User1/{info},这意味着它将匹配集合User1 中的任何路径。相反,如果您使用方括号,此值将成为通配符,这意味着匹配将适用于任何值。查看guide 中的示例以获取更多信息。

service cloud.firestore {
  match /databases/{database}/documents {

    match /{username}/{info} {
      allow read: if signedIn();
      allow write: if isOwner(username);
    }

    function signedIn() {
        return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId;
    }    
  }
} 

【讨论】:

  • 问题是我在运行时创建了其他集合,这些集合不存储用户信息而是其他内容。我想对这些集合应用不同的规则,但这样做不允许我这样做。
  • 那么你应该为这些集合添加单独的规则。
猜你喜欢
  • 2019-09-15
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多