61 lines
1.4 KiB
JavaScript
61 lines
1.4 KiB
JavaScript
const jwt = require('jsonwebtoken');
|
|
const User = require('../models/User');
|
|
|
|
// Middleware to verify JWT token
|
|
exports.protect = async (req, res, next) => {
|
|
try {
|
|
let token;
|
|
|
|
// Check if token exists in headers
|
|
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
|
token = req.headers.authorization.split(' ')[1];
|
|
}
|
|
|
|
// Check if token exists
|
|
if (!token) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
message: 'Not authorized to access this route'
|
|
});
|
|
}
|
|
|
|
try {
|
|
// Verify token
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
|
|
// Attach user to request
|
|
req.user = await User.findById(decoded.id);
|
|
|
|
if (!req.user) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
message: 'User not found'
|
|
});
|
|
}
|
|
|
|
next();
|
|
} catch (error) {
|
|
return res.status(401).json({
|
|
success: false,
|
|
message: 'Not authorized to access this route',
|
|
error: error.message
|
|
});
|
|
}
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
// Role-based authorization middleware
|
|
exports.authorize = (...roles) => {
|
|
return (req, res, next) => {
|
|
if (!roles.includes(req.user.role)) {
|
|
return res.status(403).json({
|
|
success: false,
|
|
message: `User role ${req.user.role} is not authorized to access this route`
|
|
});
|
|
}
|
|
next();
|
|
};
|
|
};
|