Nik
Nik

Reputation: 7192

Firebase rules: allow read only if resource property condition met

I'm having a hard time setting up a rule that allows only for reading of public messages. Not sure If I'm going about this the right way.

I have a collection /messages

{
 isPublic:true,
 message: "Public message"
},
{
 isPublic:false,
 message: "Private message"
}

I have my rules set up as:

match /messages/{message=**} {
 allow read: if resource.data.isPublic == true;
}

The query is this:

angularFirestore.collection('messages').get()

This returns:

FirebaseError: Missing or insufficient permissions

And when I run a test the resource is null.

What I want to do is only allow for the reads of public messages. What do I need to do to achieve that?

Upvotes: 1

Views: 62

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317562

The query is being rejected because security rules are not filters. Read more about that. Be sure to understand how this works as described in the documentation.

Your query is asking for all documents in the collection, but your rules only allows read for those where isPublic is true. Since the rules won't filter the results, the entire query is simply rejected.

The query will work when it matches the rules. This means your query will have to add a filter that matches the rule. You will need a where clause that specifies only documents where isPublic==true, so that the query matches the constraints of the rules.

Upvotes: 2

Related Questions