Files
Iris_back/src/auth/auth.service.ts
T

122 lines
3.3 KiB
TypeScript
Raw Normal View History

2025-10-10 10:06:00 -06:00
import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
2025-05-20 15:53:57 -06:00
import { JwtService } from '@nestjs/jwt';
2025-10-10 10:06:00 -06:00
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios';
2025-05-26 15:29:47 -06:00
2025-10-10 10:06:00 -06:00
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';
2025-10-16 14:04:30 -06:00
import * as argon2 from 'argon2';
import * as bcrypt from 'bcrypt';
2025-05-20 15:53:57 -06:00
@Injectable()
export class AuthService {
2025-10-10 10:06:00 -06:00
constructor(
private readonly jwtService: JwtService,
@InjectRepository(Usuario)
private readonly userRepo: Repository<Usuario>,
2026-01-21 10:53:53 -06:00
) { }
2025-10-10 10:06:00 -06:00
async jwtVerificar(token: string) {
try {
const payload = this.jwtService.verify(token);
2025-05-26 15:29:47 -06:00
return payload;
2025-10-10 10:06:00 -06:00
} 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');
2025-05-26 15:29:47 -06:00
}
2025-10-10 10:06:00 -06:00
}
2025-05-26 15:29:47 -06:00
}
2025-10-10 10:06:00 -06:00
async jwtCreate(idUsuario: number, idTipoUsuario: number) {
const payload = { Usuario: idUsuario, tipoUsuario: idTipoUsuario };
return {
2025-05-26 15:29:47 -06:00
access_token: this.jwtService.sign(payload),
2025-10-10 10:06:00 -06:00
};
2025-05-26 15:29:47 -06:00
}
2025-10-10 10:06:00 -06:00
async comparar(password, dbPassword) {
if (await bcrypt.compare(password, dbPassword)) {
2025-05-26 15:29:47 -06:00
return true;
2025-10-16 14:04:30 -06:00
} else {
return false;
2025-05-20 15:53:57 -06:00
}
2025-05-26 15:29:47 -06:00
}
2025-05-20 15:53:57 -06:00
2025-10-10 10:06:00 -06:00
async encriptar(password) {
2025-11-27 17:32:14 -06:00
const saltRounds = 10;
2026-01-21 10:53:53 -06:00
return await bcrypt.hash(password, saltRounds);
2025-05-26 15:29:47 -06:00
}
2025-10-10 10:06:00 -06:00
async generarPassword() {
2025-05-26 15:29:47 -06:00
const length = 8;
const charset =
2025-10-10 10:06:00 -06:00
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2025-05-26 15:29:47 -06:00
let password = '';
2025-10-10 10:06:00 -06:00
for (let i = 0, n = charset.length; i < length; ++i) {
password += charset.charAt(Math.floor(Math.random() * n));
2025-05-20 15:53:57 -06:00
}
2025-05-26 15:29:47 -06:00
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;
}
2025-10-10 10:06:00 -06:00
async login(usuario: string, password: string) {
const user = await this.userRepo.findOne({
where: { usuario },
relations: ['tipoUsuario'],
});
2025-10-10 10:06:00 -06:00
if (!user) throw new UnauthorizedException('No existe este usuario.');
2025-10-16 14:04:30 -06:00
const match = await this.comparar(password, user.password);
2025-10-10 10:06:00 -06:00
if (!match) throw new UnauthorizedException('Credenciales inválidas');
2026-01-21 10:53:53 -06:00
if (!user.activo) throw new BadRequestException('Este usuario no esta activo.');
const token = await this.jwtCreate(
2025-10-10 10:06:00 -06:00
user.idUsuario,
user.tipoUsuario.idTipoUsuario,
2025-10-10 10:06:00 -06:00
);
return {
token: token.access_token,
Usuario: {
idUsuario: user.idUsuario,
usuario: user.usuario,
nombre: user.nombre || '',
TipoUsuario: {
idTipoUsuario: user.tipoUsuario.idTipoUsuario,
tipoUsuario: user.tipoUsuario.tipoUsuario || '',
},
},
};
2025-10-10 10:06:00 -06:00
}
2025-05-20 15:53:57 -06:00
}