@totalsoft/multitenancy-core
v2.1.0
Published
Tenant configuration provider
Readme
multitenancy-core
This package allows loading tenant configuration from environment variables.
Installation
npm i @totalsoft/multitenancy-coreor
yarn add @totalsoft/multitenancy-coreActivation
The following environment variable should be set to 'true'
IS_MULTITENANT: 'true'Environment variables format
Tenant speciffic environment variables should follow the format MultiTenancy__Tenants__Tenant1__TenantProp where:
MultiTenancy__Tenants__is a fixed prefixTenant1is the tenant codeTenantPropis a tenant speciffic setting__is the separator for the nested structure
An environment variable with the tenant id is mandatory for each tenant (eg: MultiTenancy__Tenants__Tenant1__TenantId)
Nested properties can be used (eg: MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__Password)
For settings that are shared by multiple tenants, the folowing format should be used MultiTenancy__Defaults__DefaultProp where:
MultiTenancy__Defaults__is a fixed prefixDefaultPropis a shared setting for all tenants__is the separator for the nested structure
The default settings are merged with the tenant speciffic settings, and in case of conflicts the tenant speciffic ones have precedence.
Usage
tenantConfiguration
The getValue function reads values or complex objects from environment variables:
const { tenantConfiguration } = require("@totalsoft/multitenancy-core")
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Tenants__Tenant1__TenantId: '3c841325-eccc-4670-a577-09546df7b1fc',
// MultiTenancy__Tenants__Tenant1__TenantProp: 'tenantPropValue'
//}
const tenantSpecifficValue = tenantConfiguration.getValue('3c841325-eccc-4670-a577-09546df7b1fc', "tenantProp")The getAll function retrieves all tenant configurations from environment variables:
const { tenantConfiguration } = require("@totalsoft/multitenancy-core")
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Tenants__Tenant1__TenantId: '3c841325-eccc-4670-a577-09546df7b1fc',
// MultiTenancy__Tenants__Tenant1__Name: 'tenant 1 name',
// MultiTenancy__Tenants__Tenant1__Enabled: 'true',
// MultiTenancy__Tenants__Tenant2__TenantId: '9c841325-eccc-4670-a577-09546df7b1fc',
// MultiTenancy__Tenants__Tenant2__Name: 'tenant 2 name',
// MultiTenancy__Tenants__Tenant2__Enabled: 'false',
//}
const tenants = tenantConfiguration.getAll();The getConnectionInfo extension reads the configuration to return a connection information object:
const { tenantConfiguration } = require("@totalsoft/multitenancy-core")
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Tenants__Tenant1__TenantId: tenantId,
// MultiTenancy__Defaults__ConnectionStrings__MyDatabase__Server: server,
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__Database: db,
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__UserName: user,
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__Password: pass,
// MultiTenancy__Defaults__ConnectionStrings__MyDatabase__OtherParams: otherParams,
}
const connectionInfo = tenantConfiguration.getConnectionInfo(tenantId, "myDatabase")The returned ConnectionInfo object has the following structure:
export interface ConnectionInfo {
server: string, // Can include instance name and port
database: string,
userName?: string, // SQL authentication
password?: string, // SQL authentication
otherParams?: string,
authentication?: string, // Optional authentication mode, see below
identityClientId?: string // Client id of the managed identity, for identity-based authentication
}Identity-based SQL authentication
By default the connection uses SQL authentication with userName / password. A tenant can instead authenticate with an Azure identity (eg: AKS Workload Identity) by setting the Authentication and IdentityClientId keys of the connection string:
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Defaults__ConnectionStrings__MyDatabase__Server: 'my-server.database.windows.net',
// MultiTenancy__Defaults__ConnectionStrings__MyDatabase__UserName: 'sharedUser', // ignored for Tenant1
// MultiTenancy__Defaults__ConnectionStrings__MyDatabase__Password: 'sharedPassword', // ignored for Tenant1
// MultiTenancy__Tenants__Tenant1__TenantId: tenantId,
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__Database: db,
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__Authentication: 'Active Directory Workload Identity',
// MultiTenancy__Tenants__Tenant1__ConnectionStrings__MyDatabase__IdentityClientId: 'managed-identity-client-id',
//}The getTediousAuthentication helper builds the authentication block of a tedious / mssql config from a ConnectionInfo:
authenticationempty or missing →{ type: 'default', options: { userName, password } }(SQL authentication)Active Directory Workload Identity,Active Directory Managed Identity,Active Directory MSIorActive Directory Default(case-insensitive, spaces ignored) →{ type: 'azure-active-directory-default', options: { clientId: identityClientId } }.userName/passwordare ignored and an error is thrown ifidentityClientIdis missing.- any other value → an "unsupported authentication" error is thrown
const { tenantConfiguration, getTediousAuthentication } = require("@totalsoft/multitenancy-core")
const connectionInfo = tenantConfiguration.getConnectionInfo(tenantId, "myDatabase")
const [server, port] = connectionInfo.server.split(',')
// tedious: new Connection(config) / mssql: new sql.ConnectionPool(config)
const config = {
server,
port: port ? parseInt(port) : undefined,
database: connectionInfo.database,
authentication: getTediousAuthentication(connectionInfo),
options: { encrypt: true }
}The azure-active-directory-default authentication requires tedious ≥ 19, which uses DefaultAzureCredential from @azure/identity with managedIdentityClientId set to the identity client id. When AZURE_FEDERATED_TOKEN_FILE is set (eg: by the AKS Workload Identity webhook), the same client id is used for workload identity.
tenantService
The tenant service relies on the tenant configuration mechanism described above to read obtain tenant attributes.
The getTenantFromId function returns tenant information based on a tenant id.
const { tenantService } = require("@totalsoft/multitenancy-core")
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Tenants__Tenant1__TenantId: tenantId,
// MultiTenancy__Tenants__Tenant1__Name: 'Tenant 1 name'
//}
const res = await tenantService.getTenantFromId(tenantId)tenantService.getAll
The getAll function retrieves all enabled tenants:
const { tenantService } = require("@totalsoft/multitenancy-core")
// process.env = {
// IS_MULTITENANT: 'true',
// MultiTenancy__Tenants__Tenant1__TenantId: '3c841325-eccc-4670-a577-09546df7b1fc',
// MultiTenancy__Tenants__Tenant1__Name: 'tenant 1 name',
// MultiTenancy__Tenants__Tenant1__Enabled: 'true',
// MultiTenancy__Tenants__Tenant2__TenantId: '9c841325-eccc-4670-a577-09546df7b1fc',
// MultiTenancy__Tenants__Tenant2__Name: 'tenant 2 name',
// MultiTenancy__Tenants__Tenant2__Enabled: 'false',
//}
const tenants = await tenantService.getAll();The returned Tenant object has the following structure:
export interface Tenant {
id: string,
code: string,
name?: string
enabled: boolean
}This function is useful when you need to retrieve all enabled tenants at once, for example, when initializing your application or when performing bulk operations on all tenants.
tenantContextAccessor
Allows propagating a tenant context across async/await calls.
async function inner() {
// Access tenant context
const tenantContext = tenantContextAccessor.getTenantContext()
}
const tenant = { id: 'tenant1', code: 'tenant1-code', enabled: true }
//Create context for the current tenant and
tenantContextAccessor.useTenantContext({ tenant }, async () => {
await inner()
})