2022-05-24 10:54:36 +02:00
|
|
|
const { doInTenant, isMultiTenant, DEFAULT_TENANT_ID } = require("../tenancy")
|
2021-08-05 10:59:08 +02:00
|
|
|
const { buildMatcherRegex, matches } = require("./matchers")
|
2022-06-09 13:33:10 +02:00
|
|
|
const { Headers } = require("../constants")
|
2022-05-24 10:54:36 +02:00
|
|
|
|
|
|
|
const getTenantID = (ctx, opts = { allowQs: false, allowNoTenant: false }) => {
|
|
|
|
// exit early if not multi-tenant
|
|
|
|
if (!isMultiTenant()) {
|
|
|
|
return DEFAULT_TENANT_ID
|
|
|
|
}
|
|
|
|
|
|
|
|
let tenantId
|
|
|
|
const allowQs = opts && opts.allowQs
|
|
|
|
const allowNoTenant = opts && opts.allowNoTenant
|
|
|
|
const header = ctx.request.headers[Headers.TENANT_ID]
|
|
|
|
const user = ctx.user || {}
|
|
|
|
if (allowQs) {
|
|
|
|
const query = ctx.request.query || {}
|
|
|
|
tenantId = query.tenantId
|
|
|
|
}
|
|
|
|
// override query string (if allowed) by user, or header
|
|
|
|
// URL params cannot be used in a middleware, as they are
|
|
|
|
// processed later in the chain
|
|
|
|
tenantId = user.tenantId || header || tenantId
|
|
|
|
|
|
|
|
// Set the tenantId from the subdomain
|
|
|
|
if (!tenantId) {
|
|
|
|
tenantId = ctx.subdomains && ctx.subdomains[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!tenantId && !allowNoTenant) {
|
|
|
|
ctx.throw(403, "Tenant id not set")
|
|
|
|
}
|
|
|
|
|
|
|
|
return tenantId
|
|
|
|
}
|
2021-08-05 10:59:08 +02:00
|
|
|
|
2021-09-09 14:27:18 +02:00
|
|
|
module.exports = (
|
|
|
|
allowQueryStringPatterns,
|
|
|
|
noTenancyPatterns,
|
|
|
|
opts = { noTenancyRequired: false }
|
|
|
|
) => {
|
2021-08-05 10:59:08 +02:00
|
|
|
const allowQsOptions = buildMatcherRegex(allowQueryStringPatterns)
|
|
|
|
const noTenancyOptions = buildMatcherRegex(noTenancyPatterns)
|
|
|
|
|
2022-05-10 17:37:24 +02:00
|
|
|
return async function (ctx, next) {
|
2022-05-24 10:54:36 +02:00
|
|
|
const allowNoTenant =
|
|
|
|
opts.noTenancyRequired || !!matches(ctx, noTenancyOptions)
|
|
|
|
const allowQs = !!matches(ctx, allowQsOptions)
|
|
|
|
const tenantId = getTenantID(ctx, { allowQs, allowNoTenant })
|
|
|
|
return doInTenant(tenantId, next)
|
2022-04-19 20:42:52 +02:00
|
|
|
}
|
2021-08-05 10:59:08 +02:00
|
|
|
}
|