Initial commit: teaching institution management API.
Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
// /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;
|
||||
Reference in New Issue
Block a user