export const setTenantIdMiddleware:()

in src/router/middlewares/setTenantId.ts [55:81]


export const setTenantIdMiddleware: (
    fhirConfig: FhirConfig,
) => (req: express.Request, res: express.Response, next: express.NextFunction) => void = (fhirConfig: FhirConfig) => {
    return RouteHelper.wrapAsync(async (req: express.Request, res: express.Response, next: express.NextFunction) => {
        // Find tenantId from custom claim and aud claim
        const tenantIdFromCustomClaim = get(res.locals.userIdentity, fhirConfig.multiTenancyConfig?.tenantIdClaimPath!);
        const tenantIdFromAudClaim = getTenantIdFromAudClaim(res.locals.userIdentity.aud, fhirConfig.server.url);

        // TenantId should exist in at least one claim, if exist in both claims, they should be equal
        if (
            (tenantIdFromCustomClaim === undefined && tenantIdFromAudClaim === undefined) ||
            (tenantIdFromCustomClaim && tenantIdFromAudClaim && tenantIdFromCustomClaim !== tenantIdFromAudClaim)
        ) {
            throw new UnauthorizedError('Unauthorized');
        }
        const tenantId = tenantIdFromCustomClaim || tenantIdFromAudClaim;

        if (
            !tenantIdRegex.test(tenantId) ||
            (req.params.tenantIdFromPath !== undefined && req.params.tenantIdFromPath !== tenantId)
        ) {
            throw new UnauthorizedError('Unauthorized');
        }
        res.locals.tenantId = tenantId;
        next();
    });
};