2022-11-09 17:35:16 +01:00
|
|
|
import { doInTenant, getTenantIDFromCtx } from "../tenancy"
|
|
|
|
import { buildMatcherRegex, matches } from "./matchers"
|
2022-11-16 19:28:45 +01:00
|
|
|
import { Header } from "../constants"
|
2022-11-09 17:35:16 +01:00
|
|
|
import {
|
|
|
|
BBContext,
|
|
|
|
EndpointMatcher,
|
|
|
|
GetTenantIdOptions,
|
|
|
|
TenantResolutionStrategy,
|
|
|
|
} from "@budibase/types"
|
|
|
|
|
2022-11-26 15:46:01 +01:00
|
|
|
export = function (
|
2022-11-09 17:35:16 +01:00
|
|
|
allowQueryStringPatterns: EndpointMatcher[],
|
2022-11-11 12:10:07 +01:00
|
|
|
noTenancyPatterns: EndpointMatcher[],
|
2022-11-26 15:46:01 +01:00
|
|
|
opts: { noTenancyRequired?: boolean } = { noTenancyRequired: false }
|
|
|
|
) {
|
2022-11-09 17:35:16 +01:00
|
|
|
const allowQsOptions = buildMatcherRegex(allowQueryStringPatterns)
|
|
|
|
const noTenancyOptions = buildMatcherRegex(noTenancyPatterns)
|
|
|
|
|
2022-11-26 15:46:01 +01:00
|
|
|
return async function (ctx: BBContext | any, next: any) {
|
2022-11-09 17:35:16 +01:00
|
|
|
const allowNoTenant =
|
|
|
|
opts.noTenancyRequired || !!matches(ctx, noTenancyOptions)
|
|
|
|
const tenantOpts: GetTenantIdOptions = {
|
|
|
|
allowNoTenant,
|
|
|
|
}
|
|
|
|
|
|
|
|
const allowQs = !!matches(ctx, allowQsOptions)
|
|
|
|
if (!allowQs) {
|
|
|
|
tenantOpts.excludeStrategies = [TenantResolutionStrategy.QUERY]
|
|
|
|
}
|
|
|
|
|
|
|
|
const tenantId = getTenantIDFromCtx(ctx, tenantOpts)
|
2022-11-16 19:28:45 +01:00
|
|
|
ctx.set(Header.TENANT_ID, tenantId as string)
|
2022-11-09 17:35:16 +01:00
|
|
|
return doInTenant(tenantId, next)
|
|
|
|
}
|
|
|
|
}
|