【问题标题】:Firestore security rules when accessing new doc in transaction?在事务中访问新文档时的 Firestore 安全规则?
【发布时间】:2018-07-21 08:50:30
【问题描述】:

我正在运行以下 Firestore 事务以在 accounts 集合中创建一个新文档,并将其新创建的 ID 添加到用户的 accounts。 (相反,发送到帐户的members 对象包含用户ID。)

db.runTransaction(transaction => {
    return transaction.get(db.collection('accounts').doc())
        .then(res => {
            const accountId = res.id;
            transaction.set(db.collection('accounts').doc(accountId), {name, numberOfEmployees, businessTypes, industry, members})
            transaction.set(db.collection('users').doc(uid), {accounts: {[accountId]: true}}, {merge: true})
            return accountId;
        }, error => error)
})

我使用的事实是 .collection('accounts').doc() 没有路径 returns a new document,但我遇到了 Missing or insufficient permissions. 错误。我的规则如下:

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

    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }

    match /accounts/{accountId} {
        // allow read if user is a member or if the document does not exist
        allow read : if resource.data.members[request.auth.uid] == true || !exists(/databases/{database}/documents/accounts/$(accountId));

      // allow update, delete if user is a member
      allow update, delete: if resource.data.members[request.auth.uid] == true;

      // allow creation of any authenticated user
      allow create: if request.auth != null;
    }
  }
}

我已经将其缩小到/accounts/{accountId} 上的read 规则(如果我将其设置为if true;,它可以工作)。我应该将其设置为什么以允许访问尚不“存在”的文档?

【问题讨论】:

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


    【解决方案1】:

    通过将规则更改为找到答案:

    allow read, update, delete: if request.auth != null && (resource.data.members[request.auth.uid] == true || resource == null);
    

    【讨论】:

    • 这让我发疯了!谢谢!即使做 ! ( 'createdBy' in resource.data ) 也没有用,我猜是因为 resource 是 null .. 但当然没有办法调试并解决这个问题。
    【解决方案2】:

    您可以在安全规则中使用getAfter() 来获取文档状态,因为它将在事务结束时(但在提交之前)。

    因此,您可以使用 resource == null,而不是 resource == null,这对于阅读规则的人来说可能很奇怪,您可以使用:

    allow read, update, delete: if request.auth != null && getAfter(/databases/$(database)/documents/accounts/$(accountId)).data.members[request.auth.uid] == true;
    

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2023-04-08
      • 2023-03-28
      • 2019-02-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多