You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
devbug/app/routing/middleware/auth/Role.middleware.js

39 lines
1.6 KiB

/**
* @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
*/
const Middleware = require('libflitter/middleware/Middleware')
class Role extends Middleware {
/**
* 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