Files
gameno-api/middlewares/authMiddleware.js
T
kavehhn 35704409ec feat: bootstrap SuperAdmin from env and lock one-time seeding
Production creates the SuperAdmin from env credentials, and dashboard seeding is authenticated, SuperAdmin-only, and locked after the first run.
2026-08-14 23:23:06 +03:30

45 lines
1.2 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 { 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;