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

creating a multi-level role based access in firestore security rules


I am trying to implement a multi-level based role in firestore with security rules.

I have a two role based which is admin and superadmin and an admin can only read however a superadmin can do the CRUD operations. This is the structure of my rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    function isSuperAdmin() {
      return request.auth != null && resource.data.admin == 'SuperAdmin'
    }
    function isAdmin(){
        return request.auth != null && resource.data.admin == 'Admin'
    }

    match /admins/{admin} {
      allow read, write, delete, update, create: if isSuperAdmin()
      allow read: if isAdmin()

    }
    match /{document=**} {
      allow create, read, update, delete: if isSuperAdmin()
      allow read: if isAdmin()
    }

  }
}

and these are my fields from firestore and the error simulation for firestore security rules.

admin: enter image description here

superadmin: enter image description here

security rules: enter image description here


Solution

  • I understand that you want, in your security rules, to check the user’s role which is stored in the document in the admins collection that has its ID corresponding to the user’s uid.

    If this understanding is correct you should use the get() method as shown here in the doc:

    function isAdmin(){
        return request.auth != null && get(/databases/$(database)/documents/admins/$(request.auth.uid)).data.admin == 'Admin'
    }