Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
44 lines
1.0 KiB
JavaScript
44 lines
1.0 KiB
JavaScript
// /middlewares/authMiddleware.js
|
|
|
|
const jwt = require('jsonwebtoken');
|
|
const config = require('../config/config');
|
|
const AppError = require('../utils/AppError');
|
|
const User = require('../components/users/userModel');
|
|
|
|
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) {
|
|
return next(new AppError('UNAUTHORIZED'));
|
|
}
|
|
|
|
req.user = user;
|
|
next();
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
};
|
|
|
|
module.exports = authMiddleware;
|