52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { UsuarioRepository } from "../repositories/UsuarioRepository";
|
|
import bcrypt from "bcryptjs";
|
|
import jwt from "jsonwebtoken";
|
|
|
|
const JWT_SECRET = "seu-segredo-super-secreto"; // Em produção, use variável de ambiente
|
|
|
|
export class AuthService {
|
|
constructor(private usuarioRepository: UsuarioRepository) {}
|
|
|
|
async login(email: string, senha: string) {
|
|
console.log("AuthService - Login tentativa:", { email }); // Debug
|
|
|
|
const usuario = await this.usuarioRepository.findByEmail(email);
|
|
console.log("AuthService - Usuário encontrado:", usuario); // Debug
|
|
|
|
if (!usuario) {
|
|
throw new Error("Usuário não encontrado");
|
|
}
|
|
|
|
if (!usuario.ativo) {
|
|
throw new Error("Usuário inativo");
|
|
}
|
|
|
|
const senhaValida = await bcrypt.compare(senha, usuario.senha);
|
|
console.log("AuthService - Senha válida:", senhaValida); // Debug
|
|
|
|
if (!senhaValida) {
|
|
throw new Error("Senha inválida");
|
|
}
|
|
|
|
const token = jwt.sign(
|
|
{
|
|
id: usuario.id,
|
|
perfil: usuario.perfil,
|
|
email: usuario.email,
|
|
},
|
|
process.env.JWT_SECRET || "default-secret",
|
|
{ expiresIn: "7d" }, // 7 dias para melhor UX
|
|
);
|
|
|
|
return {
|
|
user: {
|
|
id: usuario.id,
|
|
nome: usuario.nome,
|
|
email: usuario.email,
|
|
perfil: usuario.perfil,
|
|
},
|
|
token,
|
|
};
|
|
}
|
|
}
|