Search code examples
google-cloud-firestorefirebase-security

prevent writings to document depending on user type in firebase?


I have a collection called shared in this collection I will have a doc that will serve as a connection between admin and clients (so clients can push theirs online status so does the the admin) , what I want to make is a security rule that allows the admin to modify his filed only (onlineAdmin : true)

and clients to modify theirs doc only (onlineClients : {clientID : true}). can this be done using rules ? if so how to limit the writing to each of the user types and depending on what in this case ?

Doc Model


Solution

  • Yup, that is totally possible and covered quite well in the Firebase documentation on role based access control. From there come these example rules for when you define the roles in Firestore documents:

    service cloud.firestore {
      match /databases/{database}/documents {
        // For attribute-based access control, Check a boolean `admin` attribute
        allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
        allow read: true;
    
        // Alterntatively, for role-based access, assign specific roles to users
        match /some_collection/{document} {
         allow read: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Reader"
         allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Writer"
       }
      }
    }
    

    And these rules for when you define the roles in custom attributes:

    service cloud.firestore {
      match /databases/{database}/documents {
        // For attribute-based access control, check for an admin claim
        allow write: if request.auth.token.admin == true;
        allow read: true;
    
        // Alterntatively, for role-based access, assign specific roles to users
        match /some_collection/{document} {
         allow read: if request.auth.token.reader == "true";
         allow write: if request.auth.token.writer == "true";
       }
      }
    }
    

    I also recommend checking out this video from a Firebase expert on the topic: Implementing Authorization Models