Firebase rules/secure in collectionGroup use if state


i have a problem with firebase rules.
At this moment i try to set new rules for more security in my db.

My problem is that in my flutter code im using a collectionGroup
and i dont know i can specifiy the rules.

In firebase rules i have create this code:

doc -> product_id (contains random number and user_id)

path -> path to product_details

//check product details
        match /{path=**}/product_details/{doc}{
      //check the user own the product -> is it -> he has all rules
      allow read : if(doc.split('_')[2] == request.auth.uid);
      //check the user own the product -> is not -> only can only read
      allow write : if(doc.split('_')[2] != request.auth.uid);
      //comming soon -> admin rules -> write/delete/read/update

Too check the user is in his own product i split the product_id.
The product_id contains also the user_id.
My plan is the user can only read, write, update and delete his own product.
Products from other user can only read.

Its just a example.
If i set the in the code above the state ‘allow read’ my app works fine.
But im change the the state (for example with a if state) i got an error in my app.
In firebase debug my code works fine.

In flutter the collectionGroup looks like this code:

//collection group all collection with 'product_images'
    Query<Map<String, dynamic>>  collectionGroupImage = FirebaseFirestore.instance.collectionGroup('product_images');

//get data from collection group
var query_product_images = await collectionGroupImage.get();

The error i got in my app looks like this code:
enter image description here

My Database:
Path: /user/user_id/data/product_data/product_details/product_id/paramter(price,discription…)

enter image description here

I add all product from one user into the user (see path above)

My problem is, if i want show all products in my app
i need all products id’s.
To solve this problem i make a collectionGroup on my ‘product_details’.
Now i can get all values in my products.
Until now its work.

If any questions feel free to ask me.

Anyone have a idea how i can set a if state in code.
Many thx


Since you want a user to be able to see all product_details data: Use this rule for your collection group

match /{path=**}/product_details/{docId}{
  allow read: if true;
  // allow read: if (request.auth != null); use this line if you want to 
  // allow only logged in users.

Then, to prevent a user from modifying another users data, use something like this

function isLoggedIn() {
  return request.auth != null;
function isOwner(detailsId) {
  return isLoggedIn() && detailsId.split('_')[2] == request.auth.uid;
match /product_details/{detailsId} {
  allow update, delete, create: if isOwner(detailsId);

Answered By – Peter O.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published