Misha Moroshko
Misha Moroshko

Reputation: 171321

How to set Firebase rules that allow authenticated users to only read and write their own data?

My database structure is:

users
  [email protected]
    records
      ApK2DFpG87NDGYutgAVO
        pulse: 80
      Bryd87NAS20dfDGYtghg
        pulse: 78
  [email protected]
    records
      A81hxASDKH38dhaj9321
        pulse: 93
      A82ndasklih38ASD2eda
        pulse: 67

and rules are:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{email} {
      allow create, read, update, delete: if request.auth.token.email == email;
    }
  } 
}

I would like every user (e.g. [email protected]) to be able to read and write data only under that user (users/[email protected]/**).

When I read users/[email protected] in the Rules playground (while being authenticated as [email protected]), I get "Simulated read allowed", as expected.

However, when I read users/[email protected]/records from my app (while being authenticated as [email protected]), I get:

FirebaseError: Missing or insufficient permissions.

What am I missing?

By the way, why the Rules playground doesn't allow reading collections (e.g. users/[email protected]/records)? It says:

Path must be document-level

Upvotes: 1

Views: 2155

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

You should take advantage of the recursive wildcards of version 2 of the security rules, as follows:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{email}/{document=**} {
      allow create, read, update, delete: if request.auth.token.email == email;
    }
  } 
}

As explained in the doc, it will match documents in any subcollections of the users collection as well as documents in the users collection.


By the way, why the Rules playground doesn't allow reading collections

If I am not mistaking, this is because rules are not filters, and therefore you need to exactly specify the document you want to target in the "Rules Playground".

Upvotes: 2

Related Questions