Reputation: 11
In my project I have firestore collection of users and classes. Each user can be part of one or more classes. Classes document has property members which is an array including all users uids in that class.
For instance:
users documents:
doc.id: USER1UID
{ name: 'user1', email: '[email protected]', phone: '+123 456 789 001' }
doc.id: USER2UID
{ name: 'user2', email: '[email protected]', phone: '+123 456 789 002' }
doc.id: USER3UID
{ name: 'user3', email: '[email protected]', phone: '+123 654 789 003' }
classes documents:
doc.id: ABCDEF
{ name="class1", members: ['USER1UID', 'USER2UID'] }
doc.id: GHIJKL
{ name="class2", members: ['USER1UID', 'USER3UID'] }
doc.id: MNOPQR
{ name="class3", members: ['USER3UID'] }
I need to write a rule that will allow user to read details about another user ONLY if they are in the same class. Every user can also read own profile.
In this case user1 can read details of user2 and user3. (they are together in class1 and class2). User2 can read details only of user1 (they are together in class1). User3 can read details only of user1 (they are together in class2).
I need something like:
match /users/{userId} {
allow read:
//user is logged in
if request.auth != null
&& (
//user can read own profile
request.auth.id == $(userId)
//there is a class where are both (requesting and requested) users
|| exists( (/databases/$(database)/documents/classes/).where(request.auth.id in members).where($(userId) in members)
)
}
Upvotes: 0
Views: 121
Reputation: 317467
What you're trying to do is not possible with your database schema, because security rules don't allow you to perform queries. You may only request one document at a time using its known path, maximum of 10 documents per rule execution.
What you can do instead is manage each users document to contain a list of all other users who have a class in common with that user. But you will have to write some code to keep that up to date as the roster of the classes might change over time. This might be a good use for Cloud Functions.
Upvotes: 1