koas-security
Version:
Koas security checks if a request matches the security requirement of an operation. For example, given the following partial OpenAPI document:
39 lines (38 loc) • 1.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpSecurityCheck = void 0;
const utils_1 = require("./utils");
/**
* Get a user based on an http security scheme.
*
* @param scheme - The OpenAPI security scheme.
* @param userGetter - A function for getting a user.
* @returns A tuple containing just the user.
*/
function httpSecurityCheck(scheme, userGetter) {
return async (ctx) => {
const [type, credentials] = (0, utils_1.parseAuthorizationHeader)(ctx);
let user;
if (type.toLowerCase() !== scheme.scheme) {
return null;
}
switch (type) {
case 'Basic': {
const basicAuthMatch = String(Buffer.from(credentials, 'base64')).match(/([^:]*):(.*)/);
if (!basicAuthMatch) {
return null;
}
user = await userGetter(basicAuthMatch[1], basicAuthMatch[2], ctx);
break;
}
case 'Bearer':
user = await userGetter(credentials, ctx);
break;
default:
// Unsupported authentication scheme.
return null;
}
return Array.isArray(user) ? user : [user];
};
}
exports.httpSecurityCheck = httpSecurityCheck;