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 I'm using a collectionGroup and I don't know how I can specify the rules.
In firebase rules I have created this code:
//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);
//coming soon -> admin rules -> write/delete/read/update
}
To 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 I'm changing 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:
My Database: Path: /user/user_id/data/product_data/product_details/product_id/paramter(price,discription...)
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);
}