koas-security
Version:
Koas security checks if a request matches the security requirement of an operation. For example, given the following partial OpenAPI document:
38 lines (37 loc) • 1.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiKeySecurityCheck = void 0;
/**
* Get a user based on an apiKey security scheme.
*
* @param scheme - The OpenAPI security scheme.
* @param userGetter - A function for getting a user.
* @returns A tuple containing just the user.
*/
function apiKeySecurityCheck(scheme, userGetter) {
return async (ctx) => {
let apiKey;
switch (scheme.in) {
case 'cookie':
apiKey = ctx.cookies.get(scheme.name);
break;
case 'header':
apiKey = ctx.headers[scheme.name.toLowerCase()];
break;
case 'query':
apiKey = ctx.query[scheme.name];
break;
default:
return;
}
if (!apiKey) {
return;
}
if (typeof apiKey !== 'string') {
return;
}
const user = await userGetter(apiKey, ctx);
return Array.isArray(user) ? user : [user];
};
}
exports.apiKeySecurityCheck = apiKeySecurityCheck;