Search code examples
google-cloud-firestorefirebase-authenticationfirebase-security

FireStore Security Rules for Content Owner only and Public


I have Security rules like below in my Firestore database just to be sure I want to ask here for best practice of security rules firestore

So I have collection of userData and communityPost

user data only can be access by content owner that create it (content owner can create and update it)

for community post I want everyone auth and non-auth user can read the data (public)

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /userdata/{document} {
      allow read, write: if request.auth != null && request.auth.uid == userId
    }
    
    match /communityPost/{document} {
     allow read: if true;
   }
  }
}

is this correct rules ?? this is my first time dealing with collection based rules, thanks for your time


Solution

  • You can check the properties within the document

        match /userdata/{document} {
          allow read, write: if request.auth != null && request.auth.uid == resource.data.owner
        }
    

    or you can match the document id to the user You can check the properties within the document, notice the match path

        match /userdata/{userID} {
          allow read, write: if request.auth != null && request.auth.uid == userID
        }
    

    As for making it public, Firestore discourages purely open database so you need a few conditional statements You can check the properties within the document

        match /communityPost/{document} {
         allow read: if resource.data.public == true;
       }