import { BadRequestException, Injectable, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectRepository } from '@nestjs/typeorm'; import axios from 'axios'; import { bcrypt } from 'bcrypt'; 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'; @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 argon2.verify(password, dbPassword)) { return true; } else { return false; } } async encriptar(password) { return await argon2.hash(password); } 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 login(usuario: string, password: string) { const user = await this.userRepo.findOne({ where: { usuario } }); 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 Error('Este usuario no esta activo.'); const token = this.jwtCreate( user.idUsuario, user.tipoUsuario.idTipoUsuario, ); return token; } }