Reflex/backend/middleware/authMiddleware.js
2025-05-21 22:13:09 +07:00

70 lines
3.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
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');