Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firebase Security Rules: Allow if user uid exists in a collection as a document


I am collecting my admin users uid's as documents in "admins" collection. I want to allow users to read if they have their uid's in that collection as a document.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /admins/{document=**} {
      allow write; // Everyone should be able to write
      allow read: if request.auth.uid == ; // Only read if /admins/{youruid}
    }
  }
}

Solution

  • You can use exists() to check if a document exists. Try refactoring your rules as shown below:

    match /admins/{document=**} {
      allow read: if exists(/databases/$(database)/documents/admins/$(request.auth.uid)); 
      // Only read if /admins/{youruid}
    }
    

    You can read more about exists() in the documentation.