@thisisagile/easy-express
Version:
Straightforward library for building domain-driven microservice architectures
43 lines (41 loc) • 1.81 kB
JavaScript
import {
authError
} from "./chunk-RL5ICAHT.mjs";
// src/express/SecurityHandler.ts
import passport from "passport";
import { ExtractJwt, Strategy as JwtStrategy } from "passport-jwt";
import { ctx, Environment, HttpStatus, ifFalse } from "@thisisagile/easy";
var checkLabCoat = () => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));
var checkToken = () => passport.authenticate("jwt", { session: false, failWithError: true });
var checkScope = (scope) => (req, res, next) => next(ifFalse(req.user?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));
var checkUseCase = (uc) => (req, res, next) => next(ifFalse(req.user?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));
var wrapSecretOrKeyProvider = (p) => p ? (request, rawJwtToken, done) => p(request, rawJwtToken).then((t) => done(null, t)).catch((e) => done(e)) : void 0;
var security = ({ jwtStrategyOptions } = {}) => {
jwtStrategyOptions ??= {};
if ("secretOrKeyProvider" in jwtStrategyOptions)
jwtStrategyOptions.secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);
else if (!("secretOrKey" in jwtStrategyOptions))
jwtStrategyOptions.secretOrKey = ctx.env.get("tokenPublicKey");
const strategy = new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
passReqToCallback: true,
...jwtStrategyOptions
},
(req, payload, done) => {
ctx.request.token = payload;
ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? "";
done(null, payload);
}
);
passport.use(strategy);
return passport.initialize();
};
export {
checkLabCoat,
checkToken,
checkScope,
checkUseCase,
security
};
//# sourceMappingURL=chunk-G54PL2JB.mjs.map