Search code examples
firebasegoogle-cloud-firestorefirebase-security

firebase firestore rules authenticated access to all collections except one


I have the following firestore structure, basically 3 collections

publicdata protecteddata1 protecteddata2

I want to have protecteddata1 and protecteddata 2, and really the entire firestore database as authenticated users only. But i want the public to have readonly access to 'publicdata' collection..

The following is my attempt but it doesn't work

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if (request.auth.uid != null);
    }
    match /publicdata {
       allow read;
    }
  }
}

Solution

  • You can use the following functions I created to do this

    function isUserAuthenticated() {
        return request.auth.uid != null; 
    }
    

    You can then use it like this:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if isUserAuthenticated();
        }
        
        match /publicdata/{itemId} {
          allow read : if true;
          allow create : if isUserAuthenticated();
          allow update: if isUserAuthenticated();
          allow delete: if isUserAuthenticated();
        }
    
        /* Functions */
        function isUserAuthenticated() {
          return request.auth.uid != null; 
        }
      }
    }