/** * @module flitter-auth/deploy/routing/middleware/RequireAuth */ /** * This middleware is provided by Flitter-auth. It will redirect the user * back to their previous location if the does not have the specified role. * * @class */ class Role { /** * Run the middleware's check. If an authenticated session exists and the user has the specified role, * let the request continue. If an authenticated session doesn't exist, write the destination to the * session and redirect the user to the login page. If the role doesn't exist, show a 401. * @param {Express/Request} req - the incoming Express request * @param {Express/Response} res - the corresponding Express response * @param {Function} next - Express handler stack callback. This should be called if the middleware check passed to allow the request to continue. * @param {string} role - Name of the role to require */ test(req, res, next, role){ if ( req.session && req.session.auth && (req.session.auth.authenticated === true || req.session.auth.user) ){ if ( req.session.auth.user.role && req.session.auth.user.role === role ){ next() } else { return _flitter.error(res, 401, {reason: 'Insufficient user permissions.'}) } } else { req.session.destination = req.originalUrl return res.redirect('/auth/login') } } } module.exports = Role