Reputation: 3
I want to give access to particular Document for a Specific user group. as shown in picture below. I want to give Access to Doc1 & Doc3 for usergrp1 which is in users collection. How to do it with Firestore Rules.
Documents collection
Users collection with groups docs
Upvotes: 0
Views: 584
Reputation: 83068
In order to access other Firestore documents in the security rules for a given document, you should use the get()
and exists()
functions, as explained in the doc.
However, if you save each user of a group in a specific field of the "group" document (as we can see on the screenshots), you will encounter some difficulties because you need to know which field to be checked.
I would advise, to do as follows: for each user that is part of a group, use the user uid
as the field name and assign a dummy value (e.g. true
for example). Then you can easily check the field is present in the doc, as follows, for example, by using the in
operator and the get()
function:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /docs/{docId} {
allow read: if request.auth != null && request.auth.uid in get(/databases/$(database)/documents/users/usergrp1).data
}
}
}
However, you can see in the above rule that there is a problem: the group name is hardcoded...
In order do have a group value for each specific document in the docs
collection (e.g. doc1
can allow be read by users of usergrp1
), you need to save, in the document, the name of the group that can access it.
If you save the group name in a field named authorizedGroup
you can adapt the rules as follows, by using a second time the get()
function:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /docs/{docs} {
allow read: if request.auth != null && request.auth.uid in get(/databases/$(database)/documents/users/$(get(/databases/$(database)/documents/docs/$(docs)).data.authorizedGroup)).data
}
}
}
Upvotes: 3