integration of authentication

This commit is contained in:
2024-08-06 17:44:28 +02:00
parent 0c7fc6fdf7
commit ee932a2339
13 changed files with 153 additions and 84 deletions
+48 -28
View File
@@ -1,33 +1,53 @@
const passport = require('passport');
function Admited(acceptedRoles){
return (req, res, next) => {
// if Unconnected accepted
if (acceptedRoles.includes('Unconnected') || acceptedRoles.length == 0){
next();
}
function checkIsConcernedUserOrAdmin(req, res, next) {
const user = req.user; // User is set by Passport
const userIdParam = req.params.id;
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;
if (user.isAdmin === true || user._id === userIdParam) {
next();
} else {
res.status(403).json({ error: 'Forbidden' });
// 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);
}
}
function checkIsAdmin(req, res, next) {
const user = req.user; // User is set by Passport
if (user.isAdmin === true) {
next();
} else {
res.status(403).json({ error: 'Forbidden' });
}
}
function checkIsAgent(req, res, next) {
const user = req.user; // User is set by Passport
if (user.isAgent === true) {
next();
} else {
res.status(403).json({ error: 'Forbidden' });
}
}
module.exports = { checkIsConcernedUserOrAdmin, checkIsAgent, checkIsAdmin };
module.exports = { Admited };