Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass extra auth parameters for firestore rules authentication (React-Native)?

I want to implement role based restrictions in my application. I have the user role information in one collection documents. Now I want to write rules to restrict different Write, Update operation on other collections of the database.

Since I am using Firestore database with React-Native I only pass the respective collection's document info while inserting/updating. So how can I pass the user's role information along with this so that my rule gets authenticated and that data doesn't go into other collection.

One example depicting above scenario:

/collection1/document1
{
   prop1: value1,
   prop2: value2,
   role: "WRITE"
}

/collection1/document2
{
   prop1: value1,
   prop2: value2,
   role: "READ"
}

Now consider that current logged in user is document2.

I have another collection:

/collection2/doc1
{
   userRef: document1, //this is id of document1 from collection1
   ...
}

I want to configure firestore rule for collection2 that if request has come from user with role="WRITE" then only allow it to isert/update documents.

Have read many articles and ways but any of them does not satisfy this use-case.

Any help would be appreciated.

like image 423
Hriday Modi Avatar asked Oct 21 '18 21:10

Hriday Modi


1 Answers

To make the rules easier to read, you can create a function that gets the user role, then use in the conditions. This is how the firestore.rules file would look like :

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection2/{doc} {
     allow read: if getUserRole() === 'READ' || getUserRole() === 'WRITE';
     allow create: if getUserRole() === 'WRITE';
     allow update: if getUserRole() === 'WRITE';
    }
    function getUserRole() {
        return get(/databases/$(database)/documents/collection1/$(request.auth.uid)).data.role;
    }
  }
}
like image 115
ibenjelloun Avatar answered Nov 12 '22 16:11

ibenjelloun