forked from tsai/budibase
18 changed files with 194 additions and 152 deletions
@ -1,20 +1,14 @@ |
|||
const { createTenancyContext, setTenantId } = require("../tenancy") |
|||
const { setTenantId } = require("../tenancy") |
|||
const ContextFactory = require("../tenancy/FunctionContext") |
|||
const { buildMatcherRegex, matches } = require("./matchers") |
|||
|
|||
module.exports = (allowQueryStringPatterns, noTenancyPatterns) => { |
|||
const allowQsOptions = buildMatcherRegex(allowQueryStringPatterns) |
|||
const noTenancyOptions = buildMatcherRegex(noTenancyPatterns) |
|||
|
|||
return (ctx, next) => { |
|||
// always run in context
|
|||
return createTenancyContext().runAndReturn(() => { |
|||
if (matches(ctx, noTenancyOptions)) { |
|||
return next() |
|||
} |
|||
|
|||
const allowQs = !!matches(ctx, allowQsOptions) |
|||
setTenantId(ctx, { allowQs }) |
|||
return next() |
|||
}) |
|||
} |
|||
return ContextFactory.getMiddleware(ctx => { |
|||
const allowNoTenant = !!matches(ctx, noTenancyOptions) |
|||
const allowQs = !!matches(ctx, allowQsOptions) |
|||
setTenantId(ctx, { allowQs, allowNoTenant }) |
|||
}) |
|||
} |
|||
|
|||
@ -0,0 +1,69 @@ |
|||
const cls = require("cls-hooked") |
|||
const { newid } = require("../hashing") |
|||
|
|||
const REQUEST_ID_KEY = "requestId" |
|||
|
|||
class FunctionContext { |
|||
static getMiddleware(updateCtxFn = null) { |
|||
const namespace = this.createNamespace() |
|||
|
|||
return async function(ctx, next) { |
|||
await new Promise(namespace.bind(function(resolve, reject) { |
|||
// store a contextual request ID that can be used anywhere (audit logs)
|
|||
namespace.set(REQUEST_ID_KEY, newid()) |
|||
namespace.bindEmitter(ctx.req) |
|||
namespace.bindEmitter(ctx.res) |
|||
|
|||
if (updateCtxFn) { |
|||
updateCtxFn(ctx) |
|||
} |
|||
next().then(resolve).catch(reject) |
|||
})) |
|||
} |
|||
} |
|||
|
|||
static run(callback) { |
|||
const namespace = this.createNamespace() |
|||
|
|||
return namespace.runAndReturn(callback) |
|||
} |
|||
|
|||
static setOnContext(key, value) { |
|||
const namespace = this.createNamespace() |
|||
namespace.set(key, value) |
|||
} |
|||
|
|||
static getContextStorage() { |
|||
if (this._namespace && this._namespace.active) { |
|||
const { id, _ns_name, ...contextData } = this._namespace.active |
|||
return contextData |
|||
} |
|||
|
|||
return {} |
|||
} |
|||
|
|||
static getFromContext(key) { |
|||
const context = this.getContextStorage() |
|||
if (context) { |
|||
return context[key] |
|||
} else { |
|||
return null |
|||
} |
|||
} |
|||
|
|||
static destroyNamespace() { |
|||
if (this._namespace) { |
|||
cls.destroyNamespace("session") |
|||
this._namespace = null |
|||
} |
|||
} |
|||
|
|||
static createNamespace() { |
|||
if (!this._namespace) { |
|||
this._namespace = cls.createNamespace("session") |
|||
} |
|||
return this._namespace |
|||
} |
|||
} |
|||
|
|||
module.exports = FunctionContext |
|||
Loading…
Reference in new issue