How to make cloud firestore security rules such that logged in users can access only their data?

Viewed 815

I am new to Cloud Firestore and I am unable to complete a task. I want that each logged in user should be able to see their own data, i.e., each logged in user can only see the data he/she has created and not other's data. Currently when I log in with different users, every user is able to see everything stored in Firestore database. I tried many tutorials and documentations, but my case seems to be different and I am unable to apply their method in my app.

Please have a look at my Firestore Database's screenshots given below:

This is the 'users' collection in which the document id is same as the Firebase uid provided when the user is logged in using email password login method: This is the 'users' collection

And this is the 'venues' collection in which the document id is auto-generated and field values are entered by the user in the app. enter image description here

This is the code in my Firestore Security Rules:

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

Please help me out!

1 Answers

State the security rule for one path only once - you used for users/{uid} first time correct settings, and next to them allow to read to all who is logged in

rules_version = '2';
   service cloud.firestore {
     match /databases/{database}/documents {
       match /users/{uid} {
          allow read, write: if request.auth != null && request.auth.uid == uid;
     }}}

request.auth.uid == uid rule usually used for letting user access only docs, that named with their id. U had them right in first statement.

resource.data.nameOfTheField == 'fieldContent' user gets access to file if its nameOfTheField in firestore already contains fieldContent value.

request.resource.data.nameOfTheField == fieldValue rules validates operation if requested data to nameOfTheField will be changed to fieldValue

You may allow operation based on other collections data: get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true will allow data operation if user is admin in admin field of users document.

Remember that you can validate with any operator that resolves to boolean, so you can use > < for example when validating integer fields values.

Related