const jwt = require('jsonwebtoken'); const User = require('../models/User'); /** * Strict authentication middleware. Rejects requests without a valid JWT. */ 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('-password'); if (!req.user) { return res.status(401).json({ message: 'User not found' }); } return next(); } catch (error) { return res.status(401).json({ message: 'Not authorized, token failed' }); } } return res.status(401).json({ message: 'Not authorized, no token provided' }); }; /** * Optional authentication middleware. Populates req.user if a valid token is present, * but allows the request to proceed as a guest if no token is found. */ const optionalAuth = async (req, res, next) => { if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { try { const token = req.headers.authorization.split(' ')[1]; const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded.id).select('-password'); } catch (error) { // Ignore error and continue as guest } } next(); }; module.exports = { protect, optionalAuth };