Firestore返回的权限不足,甚至不应该

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

我为Firestore数据库设置了以下规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /collections/{document=**} {
        allow read;
        allow write: if isAdmin();
        }

    match /general/{document=**} {
        allow read;
        allow write: if isAdmin();
        }

    match /inquiries/{document=**} {
        allow write;
        allow read: if isAdmin();
        }

    match /orders/{document=**} {
        allow write;
        allow read: if isAdmin() || resource.data.userID == request.auth.uid;
        }

    match /products/{document=**} {
        allow read;
        allow write: if isAdmin();
        }

    match /users/{userId} {
        allow write, read: if belongsTo(userId);
        }

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

    function isAdmin() {
        return resource.data.admin == true;
    }
  }
}

如您所见,每个人都可以阅读/ products及其文档以及子集合。哪个对产品有效,但是无法读取产品的子集合(每个产品都有一个称为collection-colors的子集。

FirebaseError:缺少权限或不足。

导致错误的代码:

retrieveCollectionColors(name) {
    this.db.collectionGroup('collection-colors', ref => ref.where('product', '==', name))
      .valueChanges().subscribe( (val: []) => {
      this.collectionColors.next(val);
    }, error => {
      console.log(error);
    });
}
javascript google-cloud-firestore firebase-security-rules
1个回答
1
投票

您现在拥有的规则根本不适用于收藏组查询。您需要为此编写一条特殊规则。从documentation

基于收集组的安全和查询文档

在您的安全规则中,您必须明确允许收集组通过为收集组编写规则进行查询:

  • 确保rules_version ='2';是规则集的第一行。集合组查询需要新的递归通配符{name=**}安全规则版本2的行为。
  • 使用match /{path=**}/[COLLECTION_ID]/{doc}为您的收藏组编写规则。

因此,如果要允许对“收藏颜色”进行收藏组查询,它将看起来像这样:

match /{path=**}/collection-colors/{doc} {
  allow read: ...
}

这将应用于具有给定名称的all子集合。您不能根据父集合的名称有选择地允许或禁止子集合。

© www.soinside.com 2019 - 2024. All rights reserved.