UNPKG

@thisisagile/easy-express

Version:

Straightforward library for building domain-driven microservice architectures

1 lines 4.71 kB
{"version":3,"sources":["../src/express/SecurityHandler.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n"],"mappings":";;;;;AACA,OAAO,cAAc;AACrB,SAAS,YAAY,YAAY,mBAAmB;AAIpD,SAAS,KAAK,aAAa,YAAY,eAAe;AA2B/C,IAAM,eAAe,MAAsB,CAAC,KAAK,KAAK,SAAS,KAAK,QAAQ,YAAY,IAAI,OAAO,IAAI,IAAI,IAAI,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAElJ,IAAM,aAAa,MAAsB,SAAS,aAAa,OAAO,EAAE,SAAS,OAAO,eAAe,KAAK,CAAC;AAE7G,IAAM,aACX,CAAC,UACD,CAAC,KAAK,KAAK,SACT,KAAK,QAAS,IAAI,MAAc,QAAQ,SAAS,MAAM,EAAE,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAEzF,IAAM,eACX,CAAC,OACD,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