UNPKG

@bitblit/ratchet-epsilon-common

Version:

Tiny adapter to simplify building API gateway Lambda APIS

60 lines 2.79 kB
import { UnauthorizedError } from '../../http/error/unauthorized-error.js'; import { MisconfiguredError } from '../../http/error/misconfigured-error.js'; import { ForbiddenError } from '../../http/error/forbidden-error.js'; import { EventUtil } from '../../http/event-util.js'; import { StringRatchet } from '@bitblit/ratchet-common/lang/string-ratchet'; export class BuiltInAuthFilters { static async parseAuthorizationHeader(fCtx, webTokenManipulators) { if (!fCtx?.event || !webTokenManipulators || (Array.isArray(webTokenManipulators) && !webTokenManipulators.length)) { throw new MisconfiguredError('Cannot continue - missing event or encryption'); } else { const tokenString = EventUtil.extractBearerTokenFromEvent(fCtx?.event); if (!Array.isArray(webTokenManipulators)) { webTokenManipulators = [webTokenManipulators]; } for (let i = 0; i < webTokenManipulators.length && !fCtx?.event?.authorization?.auth; i++) { const manipulator = webTokenManipulators[i]; try { const token = await manipulator.extractTokenFromAuthorizationHeader(tokenString); fCtx.event.authorization = { raw: tokenString, auth: token, error: null, }; } catch (err) { fCtx.event.authorization = { raw: tokenString, auth: null, error: err['message'], }; } } } return true; } static async applyOpenApiAuthorization(fCtx) { if (StringRatchet.trimToNull(fCtx?.routeAndParse?.mapping?.authorizerName)) { const authorizer = fCtx?.authenticators?.get(fCtx.routeAndParse.mapping.authorizerName); if (authorizer) { if (fCtx?.event?.authorization?.auth) { const allowed = await authorizer(fCtx.event.authorization, fCtx.event, fCtx.routeAndParse.mapping); if (!allowed) { throw new ForbiddenError('You lack privileges to see this endpoint'); } } else { throw new UnauthorizedError('You need to supply credentials for this endpoint'); } } else { throw new MisconfiguredError().withFormattedErrorMessage('Authorizer %s requested but not found', fCtx.routeAndParse.mapping.authorizerName); } } else { } return true; } } //# sourceMappingURL=built-in-auth-filters.js.map