How to create a multitenant system with roles/permissions?

Hi all,

I’m currently using the user app_metadata section to implement a multi-tenant feature in my application. Similar to how you can switch tenants on the Auth0 platform, a user in my application can switch organizations.

When an organization is selected, I’m using Auth0’s management API to patch the app_metadata with the selected organization. Then, on my backend, most middleware functions reference the app_metadata data (via req.auth.payload[‘active-org’]) within external API requests to ensure the proper organizations’ data is retrieved. To make this all work, I’m using an Auth0 post-login action that ensures all the app_metadata fields are available on my access token. Here’s what that looks like:

exports.onExecutePostLogin = async (event, api) => {
    if (event.authorization) {
        api.accessToken.setCustomClaim("active-org", event.user.app_metadata.active);
        api.accessToken.setCustomClaim("primary-org", event.user.app_metadata.primary);
        api.accessToken.setCustomClaim("secondary-org", event.user.app_metadata.secondary);
        api.accessToken.setCustomClaim("role", event.user.app_metadata.role);
    }
};

An example of a users app_metadata:

{
  "active": "org1",
  "primary": "org1",
  "secondary": [
    "org5",
    "org4",
    "org3",
    "org2",
    "org1"
  ],
  “role”: “basic”,
}

The above user is from org1 but has access to org2, org3, org4, and org5. They can use the tenant switcher to switch to any of these orgs – the org selected will become the active org (which again is used by the backend middleware functions to query external APIs ultimately populating the data on the frontend for the selected organization). This example user is a “basic” user. I’m using the value of “role” to protect certain features by conditionally rendering components on the basis of the role value (i.e. basic vs analyst).

I’m wondering if there is a better way to implement this type of system using a combination of roles and permissions. Could I assign a role ‘basic-org1’ for the above user? That role should then have permissions that give it access to org1, org2, org3, org4, and org5. How would I go about accessing a roles’ permissions programmatically? Also, how would I handle the multi tenant feature (i.e. where the basic-org1 user should be able to switch their view to the other organizations they have permissions for)? If this is the wrong approach entirely and I shouldn’t be using roles/permissions to implement this, please do let me know what you think the best way to approach this problem is.

I apologize for the long and potentially confusing message. I’d appreciate any and all help. Please let me know if I can provide any additional information that may be helpful.

Thank you for taking the time to read this.

Best,
dhpcc