import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { prisma } from '../config/database'; export interface SessionRequest extends Request { user?: { id: string; email: string; perfil: string; }; } export const sessionAuthMiddleware = async ( req: SessionRequest, res: Response, next: NextFunction ) => { try { const token = req.headers.authorization?.replace('Bearer ', ''); if (!token) { // Para sessões, permitir acesso sem autenticação em certas rotas if (req.path.includes('/public/') || req.method === 'GET') { return next(); } return res.status(401).json({ error: 'Token não fornecido' }); } const decoded = jwt.verify(token, process.env.JWT_SECRET || 'default-secret') as any; const user = await prisma.usuario.findUnique({ where: { id: decoded.id }, select: { id: true, email: true, perfil: true, ativo: true } }); if (!user || !user.ativo) { return res.status(401).json({ error: 'Usuário inválido ou inativo' }); } req.user = user; next(); } catch (error) { console.error('Erro na autenticação de sessão:', error); res.status(401).json({ error: 'Token inválido' }); } };