50 lines
2.0 KiB
JavaScript
50 lines
2.0 KiB
JavaScript
/**
|
|
* @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 permission.
|
|
*
|
|
* @class
|
|
*/
|
|
class Permission {
|
|
|
|
/**
|
|
* Run the middleware's check. If an authenticated session exists and the user has the specified permission,
|
|
* 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 permission 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} permission - Name of the permission to require
|
|
*/
|
|
async test(req, res, next, permission){
|
|
if ( req.session && req.session.auth && (req.session.auth.authenticated === true || req.session.auth.user) ){
|
|
if ( req.session.auth.user.permissions && req.session.auth.user.permissions.includes(permission) ){
|
|
next()
|
|
}
|
|
else if ( req.session.auth.user.role ){
|
|
const Role = _flitter.model('auth:Role')
|
|
const role = await Role.findOne({name: req.session.auth.user.role})
|
|
|
|
if ( role.permissions.includes(permission) ){
|
|
next()
|
|
}
|
|
else {
|
|
return _flitter.error(res, 401, {reason: 'Insufficient user permissions.'})
|
|
}
|
|
}
|
|
else {
|
|
return _flitter.error(res, 401, {reason: 'Insufficient user permissions.'})
|
|
}
|
|
}
|
|
else {
|
|
req.session.destination = req.originalUrl
|
|
return res.redirect('/auth/login')
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = Permission
|