Cloud firestore rules - how do I view a users rights by accessing different collections in the store?

51 views Asked by At

I have a cloud firestore. In this store I have a collections of all admins. All data from the store can be read by anyone, but writes should be limited to the admins. If someone tries to write to a collection, e.g. latest-news, I want to see if the user that tries to write to the collection is an admin. The idea I want is something like this:

 match /latest-news/{news-id} {
    allow read: if true;
    allow write: if <my-admin-collection>.map(auth => auth.uid).includes(request.auth.uid);
 }

How would I actually do this?

2

There are 2 answers

3
Frank van Puffelen On BEST ANSWER

If your collection of admins stores those admins by their UID, you can check for the existence of such a document from your rules with:

if exists(/databases/$(database)/documents/admins/$(request.auth.uid));

The above allows the operation if a document with the current user's UID exists in the /admins collection.

Also see the documentation on attribute-based and role-based access control.

0
Codex On

It all depends on how you define roles. In firebase auth roles can be configured by Custom Claims.

Custom claims can be used in writing security rules like

match /latest-news/{news-id} {
   allow write: if request.auth.token.role == 'Admin';
}

Above security rule will only allow user from having role as 'Admin' to write to the collection.