github-actions[bot]
Deploy to Hugging Face
b921752
Raw
History Blame Contribute Delete
1.07 kB
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const protect = async (req, res, next) => {
let token;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-passwordHash');
if (!req.user) {
return res.status(401).json({ success: false, message: 'User no longer exists' });
}
next();
} catch (error) {
console.error(error);
return res.status(401).json({ success: false, message: 'Not authorized, token failed' });
}
} else {
return res.status(401).json({ success: false, message: 'Not authorized, no token' });
}
};
const isAdmin = (req, res, next) => {
if (req.user && req.user.role === 'admin') {
next();
} else {
return res.status(403).json({ success: false, message: 'Not authorized as an admin' });
}
};
module.exports = { protect, isAdmin };