2019-06-21 22:01:34 +00:00
|
|
|
/**
|
|
|
|
* @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
|
|
|
|
*/
|
2019-08-16 14:58:21 +00:00
|
|
|
const Middleware = require('libflitter/middleware/Middleware')
|
|
|
|
class Role extends Middleware {
|
2019-06-21 22:01:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
*/
|
2019-08-16 14:58:21 +00:00
|
|
|
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) {
|
2019-06-21 22:01:34 +00:00
|
|
|
next()
|
2019-08-16 14:58:21 +00:00
|
|
|
} else {
|
|
|
|
return _flitter.error(res, 401, {
|
|
|
|
reason: 'Insufficient user permissions.'
|
|
|
|
})
|
2019-06-21 22:01:34 +00:00
|
|
|
}
|
2019-08-16 14:58:21 +00:00
|
|
|
} else {
|
2019-06-21 22:01:34 +00:00
|
|
|
req.session.destination = req.originalUrl
|
|
|
|
return res.redirect('/auth/login')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-16 14:58:21 +00:00
|
|
|
module.exports = Role
|