Kuruva Laxmi
Hardcode JWT fallback to fix registration crashes
6b49d6e
Raw
History Blame Contribute Delete
1.2 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 || 'fallback_demo_secret_key_123');
req.user = await User.findById(decoded.id).select('-password');
if (!req.user) {
return res.status(401).json({ message: 'Not authorized, user not found' });
}
next();
} catch (error) {
console.error(error);
res.status(401).json({ message: 'Not authorized, token failed' });
}
}
if (!token) {
res.status(401).json({ message: 'Not authorized, no token' });
}
};
const authorize = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ message: `User role ${req.user.role} is not authorized to access this route` });
}
next();
};
};
module.exports = { protect, authorize };