Firestore 安全规则:如何使用子集合字段值验证传入读取请求

问题描述 投票:0回答:1

我有一个名为“users”的 Firestore 集合,用于存储用户信息。在此集合中,有一个名为“商店”的子集合,其中包含列出每个用户有权访问的商店的文档。 “shops”子集合包含一个名为“shopId”的字段,它充当每个商店的唯一标识符。

每个传入的读取请求都包含一个“shopId”。我希望创建一个 Firestore 安全规则来验证每个传入请求。具体来说,该规则应验证传入请求中的“shopId”是否与与请求关联的用户文档的“shops”子集合中的“shopId”匹配,然后向具有与客户端请求匹配的 shopId 的任何集合中的文档授予读取权限.

这是我的代码,但不起作用。

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow read access to user documents if conditions are met
    match /users/{userId} {
      allow read: if request.auth != null &&
        // Check if the user document exists and if the 'shopId' in the request matches the 'shopId' in the user document
        exists(/databases/$(database)/documents/users/$(request.auth.uid)/shops/$(request.data.shopId)) &&
        request.data.shopId == resource.data.shopId;
      
      // Allow reading all documents under any collection for the specified shopId
      match /{collectionId}/{document=**} {
        // Check if the user document exists and if the 'shopId' in the request matches the 'shopId' in the user document
        allow read: if request.auth != null &&
          exists(/databases/$(database)/documents/users/$(request.auth.uid)/shops/$(request.data.shopId)) &&
          request.data.shopId == resource.data.shopId;
      }
    }
  }
}
firebase google-cloud-firestore firebase-security
1个回答
0
投票

您的 Firestore 安全规则似乎存在逻辑错误。为了实现所需的行为,您需要确保请求中的“shopId”至少与与该请求关联的用户文档的“shops”子集合中的一个“shopId”匹配。 这是您的规则的更新版本:

/ Allow read access to user documents if conditions are met
match /users/{userId} {
  allow read: if request.auth != null &&
    // Check if the user document exists and if the 'shopId' in the request matches any 'shopId' in the user document's 'shops' subcollection
    exists(/databases/$(database)/documents/users/$(request.auth.uid)/shops/$(request.data.shopId));
  
  // Allow reading all documents under any collection for the specified shopId
  match /{collectionId}/{document=**} {
    // Check if the user document exists and if the 'shopId' in the request matches any 'shopId' in the user document's 'shops' subcollection
    allow read: if request.auth != null &&
      exists(/databases/$(database)/documents/users/$(request.auth.uid)/shops/$(request.data.shopId));
  }
}

} }

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.