2025-10-24 14:37:59 -06:00
|
|
|
import {
|
|
|
|
|
BadRequestException,
|
|
|
|
|
Injectable,
|
|
|
|
|
UnauthorizedException,
|
|
|
|
|
InternalServerErrorException,
|
|
|
|
|
} from '@nestjs/common';
|
2025-10-21 14:01:53 -06:00
|
|
|
import { UsuariosService } from 'src/usuarios/usuarios.service';
|
|
|
|
|
import * as argon2 from 'argon2';
|
|
|
|
|
import { LoginDto } from './dto/login.dto';
|
|
|
|
|
import { CreateUsuarioDto } from 'src/usuarios/dto/create-usuario.dto';
|
|
|
|
|
import { JwtService } from '@nestjs/jwt';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class AuthService {
|
2025-10-24 14:37:59 -06:00
|
|
|
constructor(
|
|
|
|
|
private readonly usuarioService: UsuariosService,
|
|
|
|
|
private readonly jwtService: JwtService,
|
|
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
async registro({ nombre, contraseña, tipoUsuario }: CreateUsuarioDto) {
|
|
|
|
|
const usuario = await this.usuarioService.findOneByName(nombre);
|
|
|
|
|
if (usuario) {
|
|
|
|
|
throw new BadRequestException('Nombre de usuario ya existente');
|
2025-10-21 14:01:53 -06:00
|
|
|
}
|
2025-10-23 14:00:26 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
try {
|
|
|
|
|
const hashedContraseña = await argon2.hash(contraseña);
|
2025-10-21 14:01:53 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
await this.usuarioService.create({
|
|
|
|
|
nombre,
|
|
|
|
|
contraseña: hashedContraseña,
|
|
|
|
|
tipoUsuario,
|
|
|
|
|
});
|
2025-10-23 14:00:26 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
return {
|
|
|
|
|
message: 'Usuario registrado exitosamente',
|
|
|
|
|
};
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw new InternalServerErrorException('Error al crear el usuario');
|
2025-10-21 14:01:53 -06:00
|
|
|
}
|
2025-10-24 14:37:59 -06:00
|
|
|
}
|
2025-10-21 14:01:53 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
async login({ nombre, contraseña }: LoginDto) {
|
|
|
|
|
const usuario = await this.usuarioService.findOneByName(nombre);
|
|
|
|
|
if (!usuario) {
|
|
|
|
|
throw new UnauthorizedException('Usuario no encontrado');
|
|
|
|
|
}
|
2025-10-21 14:01:53 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
const contraseñaValida = await argon2.verify(
|
|
|
|
|
usuario.contraseña,
|
|
|
|
|
contraseña,
|
|
|
|
|
);
|
2025-10-21 14:01:53 -06:00
|
|
|
|
2025-10-24 14:37:59 -06:00
|
|
|
if (!contraseñaValida) {
|
|
|
|
|
throw new UnauthorizedException('Contraseña invalida');
|
|
|
|
|
}
|
|
|
|
|
const dataUser = {
|
|
|
|
|
id: usuario.id_usuario,
|
|
|
|
|
nombre: usuario.nombre,
|
|
|
|
|
tipoUsuario: usuario.tipoUsuario.id_tipo_usuario,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const token = await this.jwtService.sign(dataUser);
|
|
|
|
|
return {
|
|
|
|
|
token: token,
|
|
|
|
|
};
|
|
|
|
|
}
|
2025-10-21 14:01:53 -06:00
|
|
|
}
|