UNPKG

@pan-os/cerberus

Version:

security wrapper to protect routes dynamically with heimdall structure

86 lines (71 loc) 2.02 kB
/** * Module Dependencies */ const Errors = require('restify-errors'); const { verify } = require('jsonwebtoken'); const { localStrategy, facebookStrategy } = require('./strategies'); const attachPassport = (app, passport) => { app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { done(null, user); }); passport.deserializeUser((user, done) => { done(null, user); }); }; const registerLocalStrategy = (passport, kind) => (User) => passport.use(kind, localStrategy(User)); const registerFacebookStrategy = (passport) => passport.use('facebook', facebookStrategy); const validateJwt = (jwt) => { try { verify(jwt, process.env.SECRET_MASTER); } catch (error) { switch (error.name) { case 'TokenExpiredError': throw new Errors.UnauthorizedError(error.name); default: throw new Errors.ForbiddenError(error.name); } } }; /** * Parses a JWT token from the x-Authenticate header if it * exists. * * @param {*} req The request to check the header from. */ const validate = (req) => { const jwt = req.headers.authorization; if (!jwt) { throw new Errors.UnauthorizedError('Authorization header not found, you smart thief'); } validateJwt(jwt); }; /** * Wraps a microsservice adding a validation to the request * and returning forbidden if the validation fails. * * @param {Object} services The microsservice to wrap. * @returns {Array} protected microService routes */ const protect = (services) => { const microServices = Array.isArray(services) ? services : [services]; return microServices.map(microService => ({ ...microService, action: async (req, res, next) => { try { await validate(req); } catch (error) { return next(error); } return microService.action(req, res, next); }, })); }; const Cerberus = { attachPassport, registerLocalStrategy, registerFacebookStrategy, protect, }; module.exports = Cerberus;