106 lines
2.4 KiB
TypeScript
106 lines
2.4 KiB
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { PrismaClient } from '@prisma/client';
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
// Adicionar interface para tipo de usuário no Request
|
|
declare global {
|
|
namespace Express {
|
|
interface Request {
|
|
user?: {
|
|
id: string;
|
|
nome: string;
|
|
email: string;
|
|
perfil: string;
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
export const authenticateToken = async (
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction
|
|
): Promise<void> => {
|
|
try {
|
|
// Verificar se há token
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader) {
|
|
res.status(401).json({ error: 'Token não fornecido' });
|
|
return;
|
|
}
|
|
|
|
// Extrair o token do header (remover o Bearer)
|
|
const token = authHeader.replace('Bearer ', '');
|
|
|
|
// Verificar o token
|
|
const secret = process.env.JWT_SECRET || 'default-secret';
|
|
const decoded = jwt.verify(token, secret) as any;
|
|
|
|
// Buscar o usuário no banco
|
|
const user = await prisma.usuario.findUnique({
|
|
where: { id: decoded.id },
|
|
select: {
|
|
id: true,
|
|
nome: true,
|
|
email: true,
|
|
perfil: true,
|
|
ativo: true,
|
|
},
|
|
});
|
|
|
|
if (!user || !user.ativo) {
|
|
res.status(401).json({ error: 'Usuário inválido ou inativo' });
|
|
return;
|
|
}
|
|
|
|
// Adicionar o usuário no request
|
|
req.user = {
|
|
id: user.id,
|
|
nome: user.nome,
|
|
email: user.email,
|
|
perfil: user.perfil,
|
|
};
|
|
|
|
next();
|
|
} catch (error) {
|
|
console.error('Erro na autenticação:', error);
|
|
|
|
if (error instanceof jwt.TokenExpiredError) {
|
|
res.status(401).json({ error: 'Token expirado' });
|
|
return;
|
|
}
|
|
|
|
if (error instanceof jwt.JsonWebTokenError) {
|
|
res.status(401).json({ error: 'Token inválido' });
|
|
return;
|
|
}
|
|
|
|
res.status(500).json({ error: 'Erro ao autenticar' });
|
|
}
|
|
};
|
|
|
|
export const requireAdmin = async (
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction
|
|
): Promise<void> => {
|
|
try {
|
|
if (!req.user) {
|
|
res.status(401).json({ error: 'Usuário não autenticado' });
|
|
return;
|
|
}
|
|
|
|
if (req.user.perfil !== 'ADVOGADO_ADMIN') {
|
|
res.status(403).json({ error: 'Acesso negado. Apenas administradores.' });
|
|
return;
|
|
}
|
|
|
|
next();
|
|
} catch (error) {
|
|
console.error('Erro na verificação de permissão:', error);
|
|
res.status(500).json({ error: 'Erro ao verificar permissões' });
|
|
}
|
|
};
|