7 Commits

Author SHA1 Message Date
IO bfd9d7da0d auth 2024-06-26 22:21:24 -06:00
IO 8e5d2c000d services 2024-06-26 21:27:54 -06:00
IO d86565c2af fixed auth 2024-06-26 21:09:43 -06:00
IO 56f3eec287 fixed profe 2024-06-26 20:31:50 -06:00
IO cc7473ebd2 k 2024-06-26 20:25:12 -06:00
IO 8eace2204b k 2024-06-26 20:20:40 -06:00
IO 9ab9d05122 guard 2024-06-26 18:39:37 -06:00
6 changed files with 103 additions and 17 deletions
+7
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProfesorService } from './profesor.service';
import { ProfesorController } from './profesor.controller';
@@ -11,6 +12,7 @@ import { DatosAcademicos, LineasInvestigacion } from './dto/profesorDto.dto';
import { ProyectosAcademicosService } from 'src/proyectos_academicos/proyectos_academicos.service';
import { DatosAcademicosService } from 'src/datos_academicos/datos_academicos.service';
import { LineasInvestigacionService } from 'src/lineas_investigacion/lineas_investigacion.service';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [TypeOrmModule.forFeature([Profesor,
@@ -20,6 +22,11 @@ import { LineasInvestigacionService } from 'src/lineas_investigacion/lineas_inve
DatosAcademicosModule,
LineasInvestigacionModule,
ProyectosAcademicosModule,
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '60m' },
}),
ConfigModule,
],
providers: [ProfesorService,
ProyectosAcademicosService,
+1 -1
View File
@@ -163,7 +163,7 @@ export class ProfesorService {
async profile(id_profesor: number) {
const profesor = await this.profesorRepository.findOne({
where: { id_profesor },
relations: ['proyectosAcademicos', 'datosAcademicos', 'lineasInvestigacion'],
//relations: ['proyectosAcademicos', 'datosAcademicos', 'lineasInvestigacion'],
});
if (!profesor) {
+27 -1
View File
@@ -9,7 +9,9 @@ import {
Put,
Request,
UseGuards,
Delete
Delete,
ParseIntPipe,
Query
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
@@ -64,4 +66,28 @@ export class AuthController {
return this.authService.validateToken(token);
}
@Get()
findAll() {
return this.authService.findAll();
}
@Get(':id_user')
async profile(@Param('id_user', ParseIntPipe) id_user: number) {
return this.authService.profile(id_user);
}
@Get('page')
findAllPaginated(
@Query('page') page: number = 1,
@Query('limit') limit: number = 10,
@Query('nombreUsuario') nombreUsuario?: string,
@Query('tipoUsuario') tipoUsuario?: string
) {
page = page < 1 ? 1 : page;
limit = limit > 10 || limit < 1 ? 10 : limit;
return this.authService.findAllPaginated(page, limit, nombreUsuario, tipoUsuario);
}
}
+44
View File
@@ -108,4 +108,48 @@ export class AuthService {
throw new UnauthorizedException('validation token failed');
}
}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async profile(id_usuario: number) {
const user = await this.userRepository.findOne({
where: { id_usuario },
});
if (!user) {
throw new HttpException('user not found', 404);
}
return user;
}
async findAllPaginated(
page: number,
limit: number,
nombreUsuario?: string,
tipoUsuario?: string
): Promise<{ usuarios: User[], total: number, totalPages: number }> {
const query = this.userRepository.createQueryBuilder('usuario');
if (nombreUsuario) {
query.andWhere('usuario.nombre LIKE :nombreUsuario', { nombreUsuario: `%${nombreUsuario}%` });
}
if (tipoUsuario) {
query.andWhere('usuario.id_tipo_usuario = :tipoUsuario', { tipoUsuario });
}
const [usuarios, total] = await query
.skip((page - 1) * limit)
.take(limit)
.orderBy('usuario.nombre', 'ASC')
.getManyAndCount();
const totalPages = Math.ceil(total / limit);
return { usuarios, total, totalPages };
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
export enum Role {
Admin = '1',
Responsable = '2',
Admin = 1,
Responsable = 2,
}
+22 -13
View File
@@ -3,19 +3,24 @@ import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Role } from './role.enum';
import { ROLES_KEY } from './roles.decorator';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector, private jwtService: JwtService) {}
constructor(
private reflector: Reflector,
private jwtService: JwtService,
private configService: ConfigService
) {}
canActivate(context: ExecutionContext): boolean {
async canActivate(context: ExecutionContext): Promise<boolean> {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true; // Si no hay roles requeridos, se permite el acceso
return true; // Permitir acceso si no se especifican roles requeridos
}
const request = context.switchToHttp().getRequest();
@@ -30,18 +35,22 @@ export class RolesGuard implements CanActivate {
throw new UnauthorizedException('No token provided');
}
let userPayload;
try {
userPayload = this.jwtService.verify(token);
const userPayload = await this.jwtService.verifyAsync(
token,
{
secret: this.configService.get<string>('JWT_SECRET'),
}
);
const userRole: Role = userPayload.id_tipo_usuario;
if (userRole === undefined) {
return false; // Si el token no contiene roles, se niega el acceso
}
return requiredRoles.includes(userRole);
} catch (error) {
throw new UnauthorizedException('Invalid token');
}
const userRoles: Role[] = userPayload.id_tipo_usuario;
if (!userRoles) {
return false; // Si el token no contiene roles, se niega el acceso
}
return requiredRoles.some(role => userRoles.includes(role));
}
}
}