Files
gameno-api/middlewares/authMiddleware.js
T
kavehhn f04c797be6 Initial commit: teaching institution management API.
Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
2026-08-09 04:18:08 +02:00

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;