This commit is contained in:
IO
2024-07-29 20:21:38 -06:00
parent a8794eee14
commit 1e4e7f2d65
14 changed files with 66 additions and 42 deletions
+1
View File
@@ -33,6 +33,7 @@ export class ProfesorService {
while (exists) {
if (!await this.profesorRepository.findOne({ where: { id_profesor: id } })) {
Logger.debug(`id_profesor = ${id}`);
exists = false;
return id;
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Logger } from '@nestjs/common';
import { AdscripcionService } from './adscripcion.service';
@Controller('adscripcion')
@@ -7,6 +7,7 @@ export class AdscripcionController {
@Get()
findAll() {
Logger.debug('find all adscripcion');
return this.adscripcionService.findAll();
}
}
+23 -14
View File
@@ -11,15 +11,15 @@ import {
UseGuards,
Delete,
ParseIntPipe,
Query
Query,
Logger,
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
import { registerDto } from './dto/registerDto.dto';
import {Roles} from '../permissions/roles.decorator'
import {RolesGuard} from '../permissions/roles.guard'
import {Role} from '../permissions/role.enum'
import { Roles } from '../permissions/roles.decorator';
import { RolesGuard } from '../permissions/roles.guard';
import { Role } from '../permissions/role.enum';
@Controller('auth')
@UseGuards(RolesGuard)
@@ -29,20 +29,22 @@ export class AuthController {
@HttpCode(HttpStatus.OK)
@Post('login')
async signIn(@Body() data: registerDto) {
Logger.debug('signIn');
const { rememberMe } = data;
return this.authService.signIn(data, rememberMe);
}
//@UseGuards()
@Post("register")
@Post('register')
//@Roles(Role.Admin)
async register(@Body() data: registerDto){
return this.authService.register(data)
async register(@Body() data: registerDto) {
Logger.debug('register user');
return this.authService.register(data);
}
//@UseGuards(AuthGuard)
@Get()
findAll() {
Logger.debug('find all users');
return this.authService.findAll();
}
@@ -50,23 +52,29 @@ export class AuthController {
findAllPaginated(
@Query('page') page: number = 1,
@Query('limit') limit: number = 10,
@Query() filters: any
@Query() filters: any,
) {
Logger.debug('find all users max 10');
page = page < 1 ? 1 : page;
limit = limit > 10 || limit < 1 ? 10 : limit;
return this.authService.findAllPaginated(page, limit,filters);
return this.authService.findAllPaginated(page, limit, filters);
}
@Get(':id_usuario')
async profile(@Param('id_usuario', ParseIntPipe) id_usuario: number) {
Logger.debug('find one user');
return this.authService.profile(id_usuario);
}
//@UseGuards(AuthGuard)
@Put(':id_usuario')
@Roles(Role.Admin)
async update(@Param('id_usuario') id_usuario: number, @Body() data: registerDto) {
async update(
@Param('id_usuario') id_usuario: number,
@Body() data: registerDto,
) {
Logger.debug('update user');
return this.authService.update(id_usuario, data);
}
@@ -74,6 +82,7 @@ export class AuthController {
@Delete(':id_usuario')
@Roles(Role.Admin)
async remove(@Param('id_usuario') id_usuario: number) {
Logger.debug('delete user');
await this.authService.remove(id_usuario);
return { message: 'User successfully deleted' };
}
@@ -81,7 +90,7 @@ export class AuthController {
@HttpCode(HttpStatus.OK)
@Post('validate')
async validateToken(@Body('token') token: string) {
Logger.debug('validate user');
return this.authService.validateToken(token);
}
}
}
+4
View File
@@ -2,6 +2,7 @@ import {
HttpException,
Inject,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { UsersService } from '../users/users.service';
@@ -131,10 +132,12 @@ export class AuthService {
const query = this.userRepository.createQueryBuilder('usuario');
if (filters.nombre) {
Logger.debug('fiter by name user');
query.andWhere('usuario.nombre LIKE :nombre', { nombre: `%${filters.nombre}%` });
}
if (filters.id_tipo_usuario) {
Logger.debug('fiter by id user');
query.andWhere('usuario.id_tipo_usuario = :id_tipo_usuario', { id_tipo_usuario: filters.id_tipo_usuario });
}
@@ -155,6 +158,7 @@ export class AuthService {
});
if (!user) {
Logger.debug('user not found');
throw new HttpException('user not found', 404);
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Logger } from '@nestjs/common';
import { CategoriaService } from './categoria.service';
@Controller('categoria')
@@ -7,6 +7,7 @@ export class CategoriaController {
@Get()
findAll() {
Logger.debug('find all categoria');
return this.categoriaService.findAll();
}
}
@@ -1,12 +1,15 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Logger } from '@nestjs/common';
import { DatosAcademicosService } from './datos_academicos.service';
@Controller('datos-academicos')
export class DatosAcademicosController {
constructor(private readonly datosAcademicosService: DatosAcademicosService) {}
constructor(
private readonly datosAcademicosService: DatosAcademicosService,
) {}
@Get()
findAll() {
Logger.debug('find all datos academicos');
return this.datosAcademicosService.findAll();
}
}
@@ -10,7 +10,6 @@ export class DatosAcademicosService {
private readonly datosAcademicosRepository: Repository<DatosAcademicos>,
) {}
// Add methods to manage DatosAcademicos entities as needed
async removeByProfesorId(id_profesor: number): Promise<void> {
await this.datosAcademicosRepository.delete({ profesor: { id_profesor } });
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Logger } from '@nestjs/common';
import { EdificioService } from './edificio.service';
@Controller('edificio')
@@ -7,6 +7,7 @@ export class EdificioController {
@Get()
findAll() {
Logger.debug('find all edificio');
return this.edificioService.findAll();
}
}
+4 -8
View File
@@ -1,9 +1,4 @@
import {
Controller,
Post,
Body,
Put,
} from '@nestjs/common';
import { Controller, Post, Body, Put, Logger } from '@nestjs/common';
import { ImagenService } from './images.service';
@Controller('imagen')
@@ -12,8 +7,9 @@ export class ImagenController {
@Post()
async upload(@Body() body) {
Logger.debug('upload image');
const { fotografia, nombre } = body;
const imageUrl = await this.imagenService.saveImage(fotografia, nombre);
return { message: 'Image uploaded successfully', imageUrl };
@@ -21,11 +17,11 @@ export class ImagenController {
@Put()
async modify(@Body() body) {
Logger.debug('modify image');
const { fotografia, nombre } = body;
const imageUrl = await this.imagenService.modify(fotografia, nombre);
return { message: 'Image uploaded successfully', imageUrl };
}
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import * as sharp from 'sharp';
@@ -37,6 +37,7 @@ export class ImagenService {
}
async deleteImage(nombre: string): Promise<void> {
Logger.debug('delete image');
const sanitizedFileName = nombre.replace(/\s+/g, '_').toLowerCase();
const imageDir = path.join(process.cwd(), 'imagenes');
const imagePath = path.join(imageDir, sanitizedFileName);
@@ -1,4 +1,4 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Logger } from '@nestjs/common';
import { LineasInvestigacionService } from './lineas_investigacion.service';
@Controller('lineas-investigacion')
@@ -7,6 +7,7 @@ export class LineasInvestigacionController {
@Get()
findAll() {
Logger.debug('find all lineas de investigacion');
return this.lineasInvestigacionService.findAll();
}
}
+14 -10
View File
@@ -1,4 +1,10 @@
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Role } from './role.enum';
@@ -10,17 +16,18 @@ export class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
private jwtService: JwtService,
private configService: ConfigService
private configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
Logger.debug('verify roles');
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true; // Permitir acceso si no se especifican roles requeridos
return true;
}
const request = context.switchToHttp().getRequest();
@@ -30,18 +37,15 @@ export class RolesGuard implements CanActivate {
throw new UnauthorizedException('No authorization header provided');
}
const [, token] = authHeader.split(' ');
const [, token] = authHeader.split(' ');
if (!token) {
throw new UnauthorizedException('No token provided');
}
try {
const userPayload = await this.jwtService.verifyAsync(
token,
{
secret: this.configService.get<string>('JWT_SECRET'),
}
);
const userPayload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('JWT_SECRET'),
});
const userRole: Role = userPayload.id_tipo_usuario;
const userId: number = userPayload.id_usuario;
@@ -1,4 +1,4 @@
import { Controller,Get } from '@nestjs/common';
import { Controller,Get, Logger } from '@nestjs/common';
import { ProyectosAcademicosService } from './proyectos_academicos.service';
@Controller('proyectos-academicos')
@@ -7,6 +7,7 @@ export class ProyectosAcademicosController {
@Get()
findAll() {
Logger.debug('find all proyectos academicos');
return this.proyectosAcademicosService.findAll();
}
}
+3 -1
View File
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
@@ -14,12 +14,14 @@ export class UsersService {
async findOne(usuario: string): Promise<User | undefined> {
return this.users.findOne({ where: { usuario } });
}
async updateTokenAndDates(
id: number,
token: string,
lastLogin: Date,
jwtExpiry: Date,
): Promise<void> {
Logger.debug('update token and date user');
await this.users.update(id, {
jwt: token,
lastlog: lastLogin,