Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorefirebase-security

Set Cloud Firestore rules to access same admin account from staff account


I created an ERP Flutter app, with multiple "shops", where Admins account can add staff members and this staff can manage some Firebase collections on their behalf. So, the idea is that staff should login the same account of the Admin, or at least, read and write the same collections.

The problem I am facing is that "users" collection has multiple "Admin". Each Admin assigned to a shop. I need help in setting up the Firestore rules to allow only "staff ID" included in "staff" array from that particular Shop/Admin document to read and write permission.

As the screenshot below:

  • each Admin has a "staff" array with staff ID;
  • staff are also saved inside the users collection;
  • staff needs to access the "Category" and "InventoryCat" collections.

enter image description here

Maybe I am doing this wrong, and I need to set "Category" and "InventoryCat" as independent collections not released to the Admin, and share same "reference" across Admin and staff of the same shop?

Stream to call collection "categories:

 StreamBuilder(
        stream: _services.userRef.doc(_services.getUserID()).collection(_collectionName).orderBy('name').snapshots(),
        builder: (context, snapshot) {

Solution

  • The following rules should do the trick: We check if the Id of the user is within the staff array OR if the user's ID is the parent collection ID (i.e. the user is the Admin himself):

    service cloud.firestore {
      match /databases/{database}/documents {
    
        match /users/{userId}/Categories/{catId} {
          allow read: if request.auth != null && (request.auth.uid in get(/databases/$(database)/documents/users/$(userId)).data.staff || request.auth.uid == userId);
          allow write: ...
        }
      }
    }
    

    Note that the above rule is only for the Categories subcollections, you need to declare the same one for InventoryCat and daily_production subcollections.