Indiana
Indiana

Reputation: 723

Why am I getting permission denied from my Firebase Firestore Query?

I know there is a lot of similar posts, but I have been unable to find the right answer for my issue. Albeit, I'm sure its probably something simple.

I am getting a Permission Denied exception when I try to make the following query:

firestore.collection(COLLECTION_RESTAURANT)
.whereArrayContains(KEY_ADMIN_ID, "myUserId")
.get()
.await()

The 'Restaurant' entity contains an array of UserIds, which I have confirmed is the correct Id that im sending in my query. The object also has an isVisible property which is set to true on the object I am trying to retrieve.

The rules are currently written as follows:

  match /databases/{database}/documents {

    match /restaurants/{restaurantId} {

        function restaurantIsOnline() {
          return resource.data.isVisible == true;
        }

        allow read: if restaurantIsOnline();

        allow create: if false;
        allow update: if false;
        allow delete: if false;
    }
  }

When I change the rules to read allow read: if true; then I get a successful result, but I'm not sure I understand why this function is failing.

Upvotes: 0

Views: 302

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

Firebase security rules don't filter data on their own. Instead they merely ensure that all operations on the data follow the rules that you set for it.

So if you want to only allow reading of documents that have isVisible set to true, you need two things:

  1. A query that only requests documents that are visible.
  2. Security rules that ensure only this query is allowed.

Right now you have a security rule, but not the query yet. So you'll need to also filter for isVisible being equal to true in your code:

firestore.collection(COLLECTION_RESTAURANT)
  .whereArrayContains(KEY_ADMIN_ID, "myUserId")
  .whereEqualTo("isVisible", true)
  .get()
  .await()

Also see the Firebase documentation on securely querying data.

Upvotes: 1

Related Questions