import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; const JWT_SECRET = process.env.JWT_SECRET || 'fallback_secret_key_change_in_prod'; export const authMiddleware = (req: Request, res: Response, next: NextFunction) => { try { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { // Se não houver token autêntico JWT, prossegue limpo return next(); } const token = authHeader.split(' ')[1]; const decoded = jwt.verify(token, JWT_SECRET) as any; // Injeta o clerkId no header para que o extractUser (roleMiddleware) // continue seu trabalho de carregar o usuário do banco instanciado e popular req.appUser req.headers['x-clerk-user-id'] = decoded.clerkId; next(); } catch (error) { console.error('Auth Middleware Error:', error); res.status(401).json({ error: 'Token inválido ou expirado' }); } };