Home > Software design >  Firestore Rules | Insufficient permission when using resource.data on getting collection
Firestore Rules | Insufficient permission when using resource.data on getting collection

Time:03-14

My firestore rules

match /fruits/{fruit} {
  allow read: if request.auth.uid == resource.data.user;
}

Now on reading a single document, there is no problem

db.collection("fruits").doc('apple').get()

but when I try to get the collection, it gives me permission-denied

db.collection("fruits").get()

CodePudding user response:

When you try to query all documents in 'fruits' collection, the security rules check if user field in those documents is equal to UID of user requesting data. If any one document doesn't match the condition, it'll throw a permission error. Instead you should add a where() clause in your query as shown below:

db.collection("fruits").where("user", ==, currentUserUID).get()

This query will find documents where user field matches user's UID and all matched docs will pass the security rule if request.auth.uid == resource.data.user;. Security rules are not filters and that means they won't filter out documents from collection based on the rule. You must write a query that way.

  • Related