UNPKG

koas-security

Version:

Koas security checks if a request matches the security requirement of an operation. For example, given the following partial OpenAPI document:

29 lines (28 loc) 1.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.oauth2SecurityCheck = void 0; const utils_1 = require("./utils"); /** * Get a user based on an oauth2 security scheme. * * @param scheme - The OpenAPI security scheme. * @param userGetter - A function for getting a user. * @returns A tuple containing the user and the OAuth2 client. */ function oauth2SecurityCheck(scheme, userGetter) { return async (ctx, scopes) => { const [type, accessToken] = (0, utils_1.parseAuthorizationHeader)(ctx); if (type !== 'Bearer') { return null; } const pair = await userGetter(accessToken, ctx); if (!pair || pair.length < 2) { return null; } const [user, client] = pair; const clientScopes = new Set(typeof client.scope === 'string' ? client.scope.split(/\s+/) : client.scope); const isValid = scopes.every((scope) => clientScopes.has(scope)); return isValid ? [user, client] : null; }; } exports.oauth2SecurityCheck = oauth2SecurityCheck;