Search code examples
google-cloud-firestorefirebase-security

How to allow an action only if a document exists on firestore?


To allow people writing on a collection, I want to check if a document exists(which indicate the current user is admin.

I've tried the following:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function isAdmin() {
      return request.auth &&  exists(/databases/$(database)/documents/profiles/$(request.auth.uid)/roles/admin) 
    }

    match /profiles/{userId} {
      allow read, create: if request.auth !=null;
      allow update: if request.auth != null && request.auth.uid == userId;      
    }
    match /profiles/{userId}/roles/{role} {
      allow read: if request.auth !=null;
      allow write: if isAdmin()   //---> If I just set the if true;, it works
    }
    match /{document=**} {
      allow read, write: if false;
    }    

  }
}

And I know my current user has this document(i've only 2 users and I display this information on the page).

Any idea what I've done wrong?

Thanks


Solution

  • I found the issue, the isAdmin function was missing the != null for the auth check:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
    
        function isAdmin() {
          return request.auth != null &&  exists(/databases/$(database)/documents/profiles/$(request.auth.uid)/roles/admin) 
        }
    
        match /profiles/{userId} {
          allow read, create: if request.auth !=null;
          allow update: if request.auth != null && request.auth.uid == userId;      
        }
        match /profiles/{userId}/roles/{role} {
          allow read: if request.auth !=null;
          allow write: if isAdmin()   //---> If I just set the if true;, it works
        }
        match /{document=**} {
          allow read, write: if false;
        }    
    
      }
    }