iamfredrik
iamfredrik

Reputation: 340

Firestore Security Rule for users with their own collection

What would be the best Firestore rules when users should only be able to read and write their own collections, i.e. the collection name is the same as the userId? Currently I have the following which works, but is it secure enough?

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

I also tried the following which didn't work.

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

Upvotes: 0

Views: 133

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

The first rule is indeed not sufficient, since there is no check on the collection name: any authenticated user can read all the collections named with any users' uid.

The second one should work for your requirements ("Users should only be able to read and write their own collections, i.e. the collection name is the same as the userId"). You are probably having an error somewhere else, e.g. with the code for writing or reading or for authenticating the user. You should share this code in order we double check it

Upvotes: 1

Related Questions