import { BadRequestException, Injectable, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectRepository } from '@nestjs/typeorm'; import axios from 'axios'; import { Carrera } from 'src/carrera/entities/carrera.entity'; import { gmail } from 'src/helpers.services/gmail.service'; import { Servicio } from 'src/servicio/entities/servicio.entity'; import { Usuario } from 'src/usuario/entities/usuario.entity'; import { Like, Not, Repository } from 'typeorm'; import * as argon2 from 'argon2'; import * as bcrypt from 'bcrypt'; @Injectable() export class AuthService { constructor( private readonly jwtService: JwtService, @InjectRepository(Usuario) private readonly userRepo: Repository, ) { } async jwtVerificar(token: string) { try { const payload = this.jwtService.verify(token); return payload; } catch (err) { if (err.name === 'TokenExpiredError') { throw new UnauthorizedException('El token ha expirado'); } else if (err.name === 'JsonWebTokenError') { throw new UnauthorizedException('Token inválido'); } else { throw new UnauthorizedException('Error al verificar el token'); } } } async jwtCreate(idUsuario: number, idTipoUsuario: number) { const payload = { Usuario: idUsuario, tipoUsuario: idTipoUsuario }; return { access_token: this.jwtService.sign(payload), }; } async comparar(password, dbPassword) { if (await bcrypt.compare(password, dbPassword)) { return true; } else { return false; } } async encriptar(password) { const saltRounds = 10; return await bcrypt.hash(password, saltRounds); } async generarPassword() { const length = 8; const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let password = ''; for (let i = 0, n = charset.length; i < length; ++i) { password += charset.charAt(Math.floor(Math.random() * n)); } return password; } async update_password() { let user = await this.userRepo.findOne({ where: { tipoUsuario: { idTipoUsuario: 1 } } }) if (!user) throw new NotFoundException('No se encontró el usuario administrador.'); const newPassword = await this.generarPassword(); const hashedPassword = await this.encriptar(newPassword); user.password = hashedPassword; await this.userRepo.save(user); return newPassword; } async login(usuario: string, password: string) { const user = await this.userRepo.findOne({ where: { usuario }, relations: ['tipoUsuario'], }); if (!user) throw new UnauthorizedException('No existe este usuario.'); const match = await this.comparar(password, user.password); if (!match) throw new UnauthorizedException('Credenciales inválidas'); if (!user.activo) throw new BadRequestException('Este usuario no esta activo.'); const token = await this.jwtCreate( user.idUsuario, user.tipoUsuario.idTipoUsuario, ); return { token: token.access_token, Usuario: { idUsuario: user.idUsuario, usuario: user.usuario, nombre: user.nombre || '', TipoUsuario: { idTipoUsuario: user.tipoUsuario.idTipoUsuario, tipoUsuario: user.tipoUsuario.tipoUsuario || '', }, }, }; } }