zhlajiex
Fix: Stabilize authentication system with default secrets and better error handling
bdb0988
| const jwt = require('jsonwebtoken'); | |
| const asyncHandler = require('../utils/asyncHandler'); | |
| const ErrorResponse = require('../utils/errorResponse'); | |
| const User = require('../models/User'); | |
| exports.protect = asyncHandler(async (req, res, next) => { | |
| let token; | |
| // 1. Check Authorization Header | |
| if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { | |
| token = req.headers.authorization.split(' ')[1]; | |
| } | |
| // 2. Check Cookies | |
| else if (req.cookies && req.cookies.token) { | |
| token = req.cookies.token; | |
| } | |
| if (!token) { | |
| console.log(`AUTH_FAILURE: No token found in request to ${req.path}`); | |
| return next(new ErrorResponse('Not authorized: Neural token missing', 401)); | |
| } | |
| console.log(`[DEBUG_AUTH] Verifying token: ${token.substring(0, 10)}... (Length: ${token.length})`); | |
| try { | |
| const decoded = jwt.verify(token, process.env.JWT_SECRET || 'secret'); | |
| req.user = await User.findById(decoded.id); | |
| if (!req.user) { | |
| res.clearCookie('token'); | |
| return next(new ErrorResponse('Not authorized: Subject not found in archive. Please log in again.', 401)); | |
| } | |
| next(); | |
| } catch (err) { | |
| console.log(`AUTH_FAILURE: Token verification failed (${err.message})`); | |
| res.clearCookie('token'); | |
| return next(new ErrorResponse('Not authorized: Link signature invalid', 401)); | |
| } | |
| }); | |
| exports.authorize = (...roles) => { | |
| return (req, res, next) => { | |
| if (!roles.includes(req.user.role)) { | |
| return next(new ErrorResponse(`Rank ${req.user.role} unauthorized for this sector`, 403)); | |
| } | |
| next(); | |
| }; | |
| }; | |