Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firebase Security Rules -- using attribute from User document


I'm struggling to make my Firebase security rules work. I only want to allow write access to documents in the collection Nouns to users with the attribute 'admin' == true (boolean) in their user document (stored in collection Users).

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  
    
    match /Users/{userId}/{documents=**} {
      allow read, write: if request.auth != null 
                && request.auth.uid == userId
    }
    
    match /Nouns/{documents=**} {
      allow read: if request.auth != null 
    }
    
    match /Nouns/{documents=**} {
      allow read, write: if request.auth != null 
                && resource.data.admin == true
    }
    
    
  }
}

The rules playground gives the following error when I try a write on a document in the Nouns collection:

Error: simulator.rules line [17], column [13]. Property admin is undefined on object.

Can anyone please let me know what I'm doing wrong?


Solution

  • resource.data will contain data of the document being accessed in Nouns collection. If you want to read data from user's document, use get() instead:

    match /Nouns/{documents=**} {
      allow read, write: if request.auth != null 
                    && get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.admin == true
    }
    

    Collection names are case-sensitive so make sure you enter it correctly.