53 lines
1.9 KiB
JavaScript
53 lines
1.9 KiB
JavaScript
const passport = require('passport');
|
|
|
|
function Admited(acceptedRoles){
|
|
return (req, res, next) => {
|
|
|
|
// if Unconnected accepted
|
|
if (acceptedRoles.includes('Unconnected') || acceptedRoles.length == 0){
|
|
next();
|
|
}
|
|
|
|
passport.authenticate('jwt', { session: false }, (err, user, info) => {
|
|
|
|
if (err) {
|
|
// An error occurred, return a JSON error response
|
|
return res.status(500).json({ error: "An error occurred" });
|
|
}
|
|
if (!user) {
|
|
// User not authenticated, return a JSON error response
|
|
console.log('User not authenticated');
|
|
return res.status(401).json({ error: "User not authenticated" });
|
|
}
|
|
// User authenticated, attach user to request and proceed
|
|
req.user = user;
|
|
|
|
// Determine the user's role
|
|
let userRoles = [];
|
|
if (user.isAdmin) {
|
|
userRoles.push('Admin');
|
|
}
|
|
if (user.isAgent) {
|
|
userRoles.push('Agent')
|
|
}
|
|
if (user._id.toString() === req.params.id) {
|
|
userRoles.push('ConcernedUser')
|
|
}
|
|
if (user) {
|
|
userRoles.push('NormalUser')
|
|
}
|
|
|
|
// Check if any of the user's roles are in the list of accepted roles
|
|
const isAuthorized = userRoles.some(role => acceptedRoles.includes(role));
|
|
|
|
// Check if the user's role is in the list of accepted roles
|
|
if (isAuthorized) {
|
|
next(); // User's role is accepted, proceed to the next middleware/controller
|
|
} else {
|
|
res.status(403).json({ error: 'Forbidden' }); // User's role is not accepted, return 403 Forbidden
|
|
}
|
|
})(req, res, next);
|
|
|
|
}
|
|
}
|
|
module.exports = { Admited }; |