LoginSignup
4
2

More than 3 years have passed since last update.

CollectionGroupのFirebaseError: Missing or insufficient permissionsで躓いたときの対処法

Last updated at Posted at 2020-11-19

FirebaseのFirestoreのCollectionGroupはstores/{storeId}/items/{itemId}のようにStoreCollectionを跨いだItemCollectionを一括で指定できる便利な機能です。

ただ、今回、セキュリティルールを設定している際に下記エラーに直面し、少し詰まったので対処方をまとめます。

FirebaseError: Missing or insufficient permissions

このエラーはセキュリティールールがfalseを返しているときに吐かれるもので、もともと設定していた下記のセキュリティルールに問題があったことになります。

firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    match /stores/{storeId}/items/{itemId} {
      // Itemのオーナーのみがを読み込みを可能
      allow read: if resource.data.ownerId == request.auth.uid;
    }
  }
}

どうやらSubCollectionのフルパスではCollectionGroupで読み取る際のセキュリティルールとして引っかからないようです。そこで、下記のように対処しました。

firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    match /{path=**}/items/{itemId} {
      allow read: if resource.data.ownerId == request.auth.uid;
    }
  }
}

CollectionGroupは使用上、ルートに別のItemsCollectionがあればそれもグループとして扱うため、上記のようにItemsCollectionまでのパスを再帰的に書いてあげる必要があるようです。

参考

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2