Search code examples
google-cloud-firestorefirebase-security

Complex firestore rules


I have a top level collection: "organizations", in that collections doc's there is an employees map like this:

employees: {
  uid1: {
    displayName: John Do
    [...]
  }
  uid2 {
   [...]
  }
}

I have an other top collection: "customers" with an organization map like this:

organizations: {
  organizationId1: some string,
  organizationId2: some other string,
  [...]
}

where:

  • uid is the user id from firebase auth
  • organizationId is the document id of an organization doc.

user can be in multiple organizations, and customers can be share between multiple organizations as well.

I want to restain acces to customer doc, at user who are employee of at least one organization listed in the customer doc.

Has there is no way to loop in firestore.rules

I think the answer may be mapDiff, and custom claims.

user custom claims:

organizations:[organizationId1, organizationId2, ...]

But i have some difficulty to understand the documentation: https://firebase.google.com/docs/reference/rules/rules.MapDiff

Is there a way to achive that ?


Solution

  • I finaly find the ways to set rules for that:

     match /customer/{cId} {
          allow create: if request.auth != null;
          allow read, update: if (request.auth.token.organisations.keys().hasAny(resource.data.organizationIds.keys()));
          allow delete: if false;
        }
    

    My custom claims are like: (there is only 1 to 5 organisations so it's not heavy to transmit)

    organizations:{
      organizationId1: "role",
      organizationId2: "admin",
      ...
    }
    

    My file customer docs as a map like this:

    organizationIds{
      organization1Id: "some AES key used for security purpose",
      organization358Id: "some AES key used for security purpose"
    }
    

    It work nice and using custom claims save countless read per day.