se cambio el tipo de encriptacion y la manera en que se jala el JWT , ya se puede generar un jwt mediante inicio de sesion

This commit is contained in:
2025-11-19 17:24:39 -06:00
parent 75f55ba918
commit a6ee9decec
5 changed files with 552 additions and 18 deletions
File diff suppressed because one or more lines are too long
+11 -4
View File
@@ -4,17 +4,24 @@ import { AuthService } from './auth.service';
import { Usuario } from 'src/usuario/entities/usuario.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forFeature([Usuario]),
JwtModule.register({
secret: process.env.JWT, // Usa un .env en producción
signOptions: { expiresIn: '1h' },
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT') || 'clave_temporal_desarrollo',
signOptions: { expiresIn: '1h' },
}),
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [AuthService],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
+14 -6
View File
@@ -7,7 +7,6 @@ import {
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';
@@ -15,6 +14,7 @@ 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 {
@@ -48,7 +48,7 @@ export class AuthService {
}
async comparar(password, dbPassword) {
if (await argon2.verify(password, dbPassword)) {
if (await bcrypt.compare(password, dbPassword)) {
return true;
} else {
return false;
@@ -56,7 +56,7 @@ export class AuthService {
}
async encriptar(password) {
return await argon2.hash(password);
return await bcrypt.hash(password);
}
async generarPassword() {
@@ -73,14 +73,22 @@ export class AuthService {
}
async login(usuario: string, password: string) {
const user = await this.userRepo.findOne({ where: { usuario } });
const user = await this.userRepo.findOne({
where: { usuario },
relations: ['tipoUsuario'], // ✅ Cargar la relación
});
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(
// ✅ Ahora user.tipoUsuario debería estar definido
const token = await this.jwtCreate(
user.idUsuario,
user.tipoUsuario.idTipoUsuario,
user.tipoUsuario.idTipoUsuario, // Ya no será undefined
);
return token;
}
+7 -5
View File
@@ -1,19 +1,21 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT,
secretOrKey: configService.get('JWT') || 'clave_temporal_desarrollo',
});
}
async validate(payload: any) {
// payload contiene los datos del usuario que se pusieron al generar el token
// ejemplo: { sub: 123, email: "user@example.com" }
return { userId: payload.sub, email: payload.email };
return {
userId: payload.Usuario,
tipoUsuario: payload.tipoUsuario,
};
}
}
+3 -3
View File
@@ -47,13 +47,13 @@ export class ServicioController {
}
@Get('alumno')
//@UseGuards(AuthGuard('jwt'))
@UseGuards(AuthGuard('jwt'))
async obtenerAlumno(@Query('idUsuario', ParseIntPipe) idUsuario: number) {
return this.servicioService.obtenerServicioAlumno(idUsuario);
}
@Get('gustavo_baz_prada')
//@UseGuards(AuthGuard('jwt'))
@UseGuards(AuthGuard('jwt'))
async gustavoBaz(
@Query('year', ParseIntPipe) year: number,
@Res() res: Response,
@@ -63,7 +63,7 @@ export class ServicioController {
}
@Get('reporte')
//@UseGuards(AuthGuard('jwt'))
@UseGuards(AuthGuard('jwt'))
async generarReporte(@Query() query: any, @Res() res: Response) {
const path = await this.servicioService.generarGustavoBazPrada(query.year);
return res.download(path);