ismail
ismail

Reputation: 648

cloud_firestore/permission-denied with flutter

I have this document in the firestore cloud :enter image description here

and I want to get download it in the app by this request :

QuerySnapshot<Map<String, dynamic>> value = await FirebaseFirestore
          .instance
          .collection('Notification')
          .where("ChatID", isEqualTo: 'UyqfawuqBG0km69E2aY8')
          .get()

and I have this rules :

  allow delete,read:if request.auth != null
        && (resource.data.SenderID == request.auth.uid || request.auth.uid in resource.data.Receivers);
  

and I get the error : [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.

I don't know why ?!!

Upvotes: 1

Views: 734

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598648

Firebase security rules in don't filter data requests, as that wouldn't scale. Instead, all they do is ensure that the operations don't access more data than they are allowed to access.

This means that you'll need to replicate the access conditions from your security rules in the query that your code runs. So in your case that means you need to have a query that only requests documents where the current user's UID matches either the sender or the receiver ID field values.

But you can't actually create such an OR query across multiple fields in Firestore, so that leaves you with a catch-22.

The common workaround is to add an addition array field where you keep the UIDs of all participants in that document:

participants: ["uid1", "uid2"]

Now you can perform a query with an array-contains clause to only request documents that the user is a participant in. Of course you'll also have to modify the security rules to check this new field, rather than the separate sender and receiver fields.

Upvotes: 2

Related Questions