M4trix Dev
M4trix Dev

Reputation: 2274

Firestore security rule - how to secure subcollection?

I would like to ask what is the best way to secure Firestore subcollections.

Here is my problem: I have a user collection where there is a document named as the user id. I also have a collection inside that document with some information including the user id (again). Is there an easy way to give access to every document nested in subcollection of the the user document?

So far I wrote the following. I can access the first document (the one called i6mg... but not the second called DxDt...)

  match /users/{user} {
  allow read: if resource.data.userId == request.auth.uid;
  allow write: if false;

    match /wordScores/{doc} {
    allow read : if resource.data.userId == request.auth.uid;
    allow write;
    }

    match /groupScores/{doc} {
    allow read: if resource.data.userId == request.auth.uid;
    allow write;
    }

  }

Extra question: is there a way to secure all document without having the user id included in every document?

Thanks

EDIT Thanks Doug for the suggestion. I have added the following code and probably got in some other problems...

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

It looks like I am giving my users access to the subcollection but not to the main collection. The following code for example does not produce results and it catches an exception

await Firestore.instance.collection('users').where('userId', isEqualTo: userId).limit(1).getDocuments();

Any suggestion?

enter image description here

Upvotes: 2

Views: 935

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

If you're using the UID of the user as the ID of their top-level document, and you want all of the documents in all of the subcollections to have the same access as that document, use a recursive wildcard:

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

You have to be using security rules version 2 to get the recursive wildcard syntax. Note that regular wildcards just becomes variables you can use directly in rules. You don't have to reach into a document field as you are now.

Upvotes: 4

Related Questions