Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firestore security rules - nested documents


I want to restrict access to group data with the firebase security rules.

Each user has a userId and can be in multiple groups.

All participants in the same group should be able to make changes to the group for all participants.

For example, the user Wrrhks98BUSLLoGfnUswt2FE57s should be allowed to make changes to the group-document -JrwbcP1OdmjUWxTWHJk of the user 2B0ABrxKXzr9UdmCP8TuMgqrtBI3

General structure:

collection (groups) 
--> Document (userId) 
   --> Collection (userId) 
       --> Document(groupId)

Example:

collection (groups) 
    --> Document (2B0ABrxKXzr9UdmCP8TuMgqrtBI3) 
        --> Collection (2B0ABrxKXzr9UdmCP8TuMgqrtBI3) 
            --> Document(-JrwbcP1OdmjUWxTWHJk)
            --> Document(-Mrwtjko3dmjUWxTWHJl)
            --> Document(-LrwbcPtujdqcWxTWHJe)
    --> Document (Wrrhks98BUSLLoGfnUswt2FE57s) 
        --> Collection (Wrrhks98BUSLLoGfnUswt2FE57s) 
            --> Document(-JrwbcP1OdmjUWxTWHJk)

i tried this but it doesn' work:

match /groups/{userId}/{userId2}/{groupId} {
    allow read, write: if exists(/databases/$(database)/documents/groups/$(request.auth.uid)/$(request.auth.uid)/groupId)
}

Solution

  • I have found the solution :-)

    simply that way:

    match /groups/{userId}/{userId2}/{groupId} {
        allow read, write: if exists(/databases/$(database)/documents/groups/$(request.auth.uid)/$(request.auth.uid)/$(resource.data.id))
    }