import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { AppError, AuthenticatedRequest } from '../types/index'; export function authMiddleware(req: Request, res: Response, next: NextFunction): void { const token = (req.cookies as Record)?.token; if (!token) { next(new AppError('Unauthorized', 401, 'NO_TOKEN')); return; } const secret = process.env.JWT_SECRET; if (!secret) { next(new AppError('Server misconfiguration: JWT_SECRET not set', 500, 'CONFIG_ERROR')); return; } try { const payload = jwt.verify(token, secret) as { sub: string }; (req as AuthenticatedRequest).user = { sub: payload.sub }; next(); } catch { next(new AppError('Invalid or expired session', 401, 'INVALID_TOKEN')); } }