Reputation: 30
I'm making a structure that looks something like this:
users
user1
user2
user3
group
group1
group2
group3
subcollections1
subdoc11
subdoc12
subcollections2
subdoc21
subdoc22
So explaining it, I have a users collection and group collection. All users must be part of one and only one group. A group has a 'members' field which I check if the user is a member or not.
So my rules are something like this for now.
match /groups/{document=**} {
allow read, write: if resource.data.users[request.auth.uid] != null;
}
My question is, would it accurately check if user is in group1->doc-'members' even when writing to a subcollection or would it check in group1->doc->subcollection->doc-'members' in that case?
Because the members list is only in the groups collection but not in the subcollection so the second situation is not wanted.
Upvotes: 0
Views: 58
Reputation: 2002
Although I haven't actually tried, the resource.data
variable is a refernce to the document being accessed. So if the path accesses the document /groups/group3/subcollections1/subdoc11
that would be the document referenced by resource.data
. Therefore I think you're rule won't work as expected.
Regarding how to implement the desired behavior, note that it's best to define Firestore rules at the most granular level. This would prevent to accidentally grant access when a stricter rule ought to be applied but instead a wider rule is applied. I would suggest something alike this:
match /groups/{groupId} {
allow read, write: if resource.data.users[request.auth.uid] != null;
}
match /groups/{groupId}/{subcollection}/{documentId} {
allow read, write: if get(/databases/$(database)/documents/$(groupId)).data.users[request.auth.uid] != null
}
For further reference check this pages about how rules work and sample rules.
Upvotes: 1