Home > Net >  Firestore schema that supports group write access
Firestore schema that supports group write access

Time:11-04

I'm trying to design a firestore schema that allows many groups of people to edit only their own group's documents, but anyone service-wide can read them. It doesn't appear possible with firestore's security rules setup.

Role-based access

Firebase supports role-based access control, but it applies service-wide to documents, and I wouldn't be able to support many groups.

Custom roles are created and assigned via the gcloud console, so I could not create new, dynamic custom roles for each group, in order for them to have their own groups.

Firestore triggers to copy documents

I considered using firestore triggers (onCreate, onUpdate, onDelete) to copy documents to other user's subcollections who are in the same group. The issue with doing that is it could create an endless loop of triggers since each member can update a document. You could in theory use a property set on a copied doc that could prevent that, but it feels a little kludgy and brittle.

Is there a best practice, or is this not possible with Firestore?

CodePudding user response:

Firebase Authentication with Custom Claims might be a good fit for this use case. You can add a claim groupId and set it's value to the ID of group that user belongs to. If user can be a part of multiple groups then store an array of groupIds. Your can check if this groupId is included in user's claims in security rules.

You would have to store the groupId in every document so we know which group that doc belongs to. You can try the following rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{docId} {
      allow read, write: if resource.data.groupId == request.auth.token.groupId;
    }
  }
}

The above rules will allow users to read, write a document only if groupId in document matched groupId in their custom claim.

The custom claims can be changed using Firebase Admin SDK in a secure environment only so you might have to use a Cloud function/server to add users to their respective group.

  • Related