Reflex/backend/middleware/authMiddleware.js

89 lines
4.1 KiB
JavaScript
Raw Permalink Normal View History

2025-05-21 22:13:09 +07:00
console.log('[DEBUG] authMiddleware.js - Start of file');
const jwt = require('jsonwebtoken');
console.log('[DEBUG] authMiddleware.js - jwt loaded');
let User;
try {
User = require('../models/User');
console.log('[DEBUG] authMiddleware.js - User model loaded successfully. Type:', typeof User);
} catch (error) {
console.error('[DEBUG] authMiddleware.js - FAILED to load User model:', error);
// Если модель пользователя не загрузится, protect не сможет работать, но модуль все равно должен попытаться экспортировать
}
console.log('[DEBUG] authMiddleware.js - Defining protect function...');
const protect = async (req, res, next) => {
console.log('[DEBUG] protect middleware - Entered');
let token;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
token = req.headers.authorization.split(' ')[1];
console.log('[DEBUG] protect middleware - Token found:', token ? 'Yes' : 'No');
if (!process.env.JWT_SECRET) {
console.error('[DEBUG] protect middleware - JWT_SECRET is not defined in environment variables!');
const err = new Error('Ошибка конфигурации сервера: секрет JWT не установлен.');
err.statusCode = 500;
return next(err);
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log('[DEBUG] protect middleware - Token decoded');
if (!User) {
console.error('[DEBUG] protect middleware - User model is not loaded!');
const err = new Error('Ошибка сервера: модель пользователя не загружена.');
err.statusCode = 500;
return next(err);
}
req.user = await User.findById(decoded.id).select('-password');
if (!req.user) {
console.log('[DEBUG] protect middleware - User not found for token');
const err = new Error('Пользователь не найден (возможно, удален после выдачи токена)');
err.statusCode = 401;
return next(err);
}
2025-05-26 20:01:25 +07:00
// Проверяем, не заблокирован ли пользователь
if (req.user.blocked && !req.user.isAdmin) {
console.log('[DEBUG] protect middleware - User is blocked');
const err = new Error('Ваш аккаунт заблокирован администратором.');
err.statusCode = 403;
err.blocked = true;
err.blockReason = req.user.blockReason;
return next(err);
}
2025-05-25 23:36:51 +07:00
// Добавляем отладочное логирование для проверки прав администратора
console.log('[DEBUG] protect middleware - User loaded:', {
id: req.user._id,
name: req.user.name,
email: req.user.email,
2025-05-26 20:01:25 +07:00
isAdmin: req.user.isAdmin,
blocked: req.user.blocked
2025-05-25 23:36:51 +07:00
});
2025-05-21 22:13:09 +07:00
console.log('[DEBUG] protect middleware - User authenticated, calling next()');
next();
} catch (error) {
console.error('[DEBUG] protect middleware - Authentication error:', error.message);
const err = new Error('Не авторизован, токен недействителен или ошибка верификации.');
err.statusCode = 401;
return next(err);
}
} else {
console.log('[DEBUG] protect middleware - No Bearer token in authorization header');
const err = new Error('Не авторизован, нет токена или неверная схема авторизации.');
err.statusCode = 401;
return next(err);
}
};
console.log('[DEBUG] authMiddleware.js - typeof protect after definition:', typeof protect);
console.log('[DEBUG] authMiddleware.js - Current module.exports before assignment:', typeof module.exports, JSON.stringify(module.exports));
module.exports = { protect };
console.log('[DEBUG] authMiddleware.js - module.exports after assignment:', typeof module.exports, JSON.stringify(module.exports));
console.log('[DEBUG] authMiddleware.js - End of file');