In order to solve this problem, you need to keep in mind that you cannot transfer relational database patterns to a non-relational database. When working with Firestore, you should start by asking "What queries should be possible?" and then structure your data based on that. Building up Security Rules will follow naturally.
I wrote a blogpost about exactly your use case: "How to build a team-based user management system with Firebase", so if anything from the following answer is unclear, go there first to see if it helps.
In your case, you'd probably want the following queries:
- Get all users of a group (given the current user is a member of this group and has the correct permission).
- Get all groups of a user (given you are only querying groups of the currently authenticated user).
As you noticed, many-to-many relationships are hard to work with through Firestore and Security Rules, because you would need to make additional requests to join the datasets. To avoid that, I recommend renaming the userGroups
collection to memberships
and turning it into a subcollection of each doc in the groups
collection. So your new structure would look like
- collection "groups", a doc contains:
- field "name"
- collection "memberships", a doc contains:
- field "name"
- field "role"
- field "user" → references doc from "users"
- collection "users", a doc contains:
- field "name"
This way you can easily solve the first query "Get all users of a group" by querying the subcollection "memberships" like collection("groups").doc("your-group-id").collection("memberships").get()
.
Now, to secure that, you can write a helper functions in Security Rules:
function hasAccessToGroup(groupId, role) {
return get(/databases/$(database)/documents/groups/$(groupId)/memberships/$(request.auth.uid)).data.role == role
}
Given a groupId and a role, you can use it allow only users who are a member and have a specific role access to data and subcollections within the group. In order to protect the memberships collection on a group this might look like this:
rules_version = '2'
service cloud.firestore {
match /databases/{database}/documents {
function hasAccessToGroup(groupId, role) {
return get(/databases/$(database)/documents/groups/$(groupId)/memberships/$(request.auth.uid)).data.role == role
}
match /groups/{groupId} {
// Allow users with the role "user" access to read the group doc.
allow get: if
request.auth != null &&
hasAccessToGroup(groupId, "user")
// Allow users with the role "admin" access to read all subcollections, including "memberships".
match /{subcollection}/{document=**} {
allow read: if
request.auth != null &&
hasAccessToGroup(teamId, "admin")
}
}
}
}
Now there is only the second query "Get all groups of a user" left. This can be achieved through a Collection Group Index, which allows to query all subcollections with the same name. You want to create one for the memberships collection. Given a specific user, you can then easily query all of his groups with collectionGroup("memberships").where("user", "==", currentUserRef).get()
.
In order to secure that, you need to setup a Rule that allows such requests only if the queried user reference equals the currently authenticated user:
function isReferenceTo(field, path) {
return path('/databases/(default)/documents' + path) == field
}
match /{document=**}/memberships/{userId} {
allow read: if
request.auth != null &&
isReferenceTo(resource.data.user, "/users/" + request.auth.uid)
}
One last thing to talk about is how you keep the data in the memberships collection up-to-date with the data in the users doc that it references. The answer are Cloud Functions. Every time a users doc changes, you query all of its memberships and update the data.
As you can see, answering your original question how you can construct a Firestore Rule so that a user with the correct permission can read another user's document if they both are found in the same group, takes a different approach. But after restructuring your data, your Security Rules will be easier to read.
I hope this helped. Cheers!