Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Many to Many Relationships

Would like suggestions related to a many to many structure with roles/permissions.

We need a structure that permits users to belong to many organizations and users have a role/permissions for each organization. For example, User1 belongs to ABC CO as Admin, and User1 belongs to XYZ CO as Guest

like image 944
Puches Avatar asked Nov 08 '22 12:11

Puches


1 Answers

We have solved this issue as follows:

organizations (collection) {
    ABC (doc) {
        permissions (object): {
            User1DocID (object): {
                admin: true
            }
        }
    }
    XYZ (doc) {
        permissions (object): {
            User2DocID (object): {
                guest: true
            }
        }
    }
}

This way you can configure the rules like this:

match /origanizations/{origanization} {
    allow update, read: if resource.data.permissions[request.auth.uid].admin == true;
    allow read: if resource.data.permissions[request.auth.uid].guest == true;
}

For the resources of the organization you would have to store the Organization ID in the specific docs (obviously). Then you can setup the rules for them as follows:

match /origanizationRessources/{origanizationRessource} {
    allow update: if get(/databases/$(database)/documents/organizations/$(resource.data.organizationId)).data.permissions[request.auth.uid].admin == true;
}

You can also easily query for data that the user has specific permissions on with this design.

Please note: This design fits our purposes as we have a finite, straightforward number of users assigned to the organizations. If you are unsure, have a look at the limits in terms of document sizes (see https://firebase.google.com/docs/firestore/quotas) to find out whether you have to rely on another design. If you happen to be in the position of potentially hitting those limits, consider a seperate mapping collection.

like image 175
John Doee Avatar answered Nov 15 '22 07:11

John Doee