first commit
This commit is contained in:
commit
c9fb67e751
423 files changed
+53287
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { prisma } from '../server/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 authMiddleware = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
try {
|
||||
// Verificar se há token
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader) {
|
||||
return res.status(401).json({ error: 'Token não fornecido' });
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return res.status(401).json({ error: 'Usuário não autorizado' });
|
||||
}
|
||||
|
||||
// Adicionar usuário ao request
|
||||
req.user = {
|
||||
id: user.id,
|
||||
nome: user.nome,
|
||||
email: user.email,
|
||||
perfil: user.perfil,
|
||||
};
|
||||
|
||||
// Continuar
|
||||
return next();
|
||||
} catch (error) {
|
||||
console.error('Erro de autenticação:', error);
|
||||
return res.status(401).json({ error: 'Token inválido' });
|
||||
}
|
||||
};
|
||||
|
||||
export default authMiddleware;
|
||||
Reference in new issue
Block a user