// /middlewares/authMiddleware.js const jwt = require('jsonwebtoken'); const config = require('../config/config'); const AppError = require('../utils/AppError'); const User = require('../components/users/userModel'); const { isBootstrapSuperAdminDisabled } = require('../utils/superAdmin'); const authMiddleware = async (req, res, next) => { try { let token = null; const authHeader = req.headers.authorization; if (authHeader && authHeader.startsWith('Bearer ')) { token = authHeader.split(' ')[1]; } if (!token) { return next(new AppError('UNAUTHORIZED')); } let decoded; try { decoded = jwt.verify(token, config.JWT_ACCESS_SECRET); } catch (err) { if (err.name === 'TokenExpiredError') { return next(new AppError('TOKEN_EXPIRED')); } return next(new AppError('UNAUTHORIZED')); } const user = await User.findById(decoded.id).populate('role'); if (!user || !user.isActive || isBootstrapSuperAdminDisabled(user)) { return next(new AppError('UNAUTHORIZED')); } req.user = user; next(); } catch (error) { next(error); } }; module.exports = authMiddleware;