This commit is contained in:
2024-06-26 11:47:56 -06:00
20 changed files with 230 additions and 62 deletions
+40 -11
View File
@@ -8,47 +8,47 @@ export class profesorDto{
@IsString()
@IsOptional()
@Length(10)
@Length(0,10)
num_trabajador: string;
@IsString()
@IsNotEmpty()
@Length(80)
@Length(0,80)
nombre: string;
@IsString()
@IsOptional()
@Length(10)
@Length(0,10)
rfc: string;
@IsString()
@IsOptional()
@Length(3)
@Length(0,3)
homoclave: string;
@IsString()
@IsOptional()
@Length(13)
@Length(0,13)
tel_oficina: string;
@IsString()
@IsOptional()
@Length(10)
@Length(0,10)
extension: string;
@IsString()
@IsOptional()
@Length(13)
@Length(0,13)
tel_personal: string;
@IsString()
@IsOptional()
@Length(65)
@Length(0,65)
correo_pcp: string;
@IsString()
@IsOptional()
@Length(65)
@Length(0,65)
correo_per: string;
@IsNumber()
@@ -65,12 +65,12 @@ export class profesorDto{
@IsString()
@IsOptional()
@Length(256)
@Length(0,256)
ubicacion: string;
@IsString()
@IsOptional()
@Length(150)
@Length(0,150)
fotografia: string;
@IsBoolean()
@@ -80,4 +80,33 @@ export class profesorDto{
@IsBoolean()
@IsOptional()
mostrar: boolean;
proyectosAcademicos: ProyectoDto[];
datosAcademicos: DatosAcademicos[];
lineasInvestigacion: LineasInvestigacion[];
}
export class ProyectoDto {
@IsOptional()
@Length(0, 500)
proyecto: string;
}
export class DatosAcademicos{
@IsOptional()
@Length(0,30)
grado_maximo: string;
@IsOptional()
@Length(0,600)
grados_obtenidos: string;
}
export class LineasInvestigacion{
@IsOptional()
@Length(0,300)
lineas_inv: string;
}
+2 -2
View File
@@ -104,10 +104,10 @@ export class Profesor {
@OneToMany(() => DatosAcademicos, datosAcademicos => datosAcademicos.profesor)
datosAcademicos: DatosAcademicos[];
@OneToMany(() => LineasInvestigacion, lineasInvestigacion => lineasInvestigacion.profesor)
@OneToMany(() => LineasInvestigacion, linea => linea.profesor)
lineasInvestigacion: LineasInvestigacion[];
@OneToMany(() => ProyectosAcademicos, proyectosAcademicos => proyectosAcademicos.profesor)
@OneToMany(() => ProyectosAcademicos, proyecto => proyecto.profesor)
proyectosAcademicos: ProyectosAcademicos[];
}
+1 -1
View File
@@ -31,7 +31,7 @@ export class ProfesorController {
@Put(':id_profesor')
@Roles(Role.Responsable,Role.Admin)
async postModify(@Param('id_profesor', ParseIntPipe) id_profesor: number, @Body() data: profesorDto) {
async modify(@Param('id_profesor', ParseIntPipe) id_profesor: number, @Body() data: profesorDto) {
return this.profesorService.modify(id_profesor, data);
}
+14 -3
View File
@@ -6,18 +6,29 @@ import { Profesor } from './entities/profesor.entity';
import { DatosAcademicosModule } from '../datos_academicos/datos_academicos.module';
import { LineasInvestigacionModule } from '../lineas_investigacion/lineas_investigacion.module';
import { ProyectosAcademicosModule } from '../proyectos_academicos/proyectos_academicos.module';
import { ProyectosAcademicos } from 'src/proyectos_academicos/entities/proyectos_academicos.entity';
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 { JwtModule } from '@nestjs/jwt';
import { RolesGuard } from '../permissions/roles.guard';
@Module({
imports: [TypeOrmModule.forFeature([Profesor]),
imports: [TypeOrmModule.forFeature([Profesor,
ProyectosAcademicos,
DatosAcademicos,
LineasInvestigacion]),
DatosAcademicosModule,
LineasInvestigacionModule,
ProyectosAcademicosModule,
JwtModule,
],
providers: [ProfesorService,RolesGuard],
controllers: [ProfesorController,RolesGuard],
providers: [ProfesorService,
ProyectosAcademicosService,
DatosAcademicosService,
LineasInvestigacionService,],
controllers: [ProfesorController],
})
export class ProfesorModule {}
+105 -7
View File
@@ -6,6 +6,9 @@ import { ProyectosAcademicosService } from '../proyectos_academicos/proyectos_ac
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { profesorDto } from './dto/profesorDto.dto';
import { ProyectosAcademicos } from '../proyectos_academicos/entities/proyectos_academicos.entity';
import { DatosAcademicos } from '../datos_academicos/entities/datos_academicos.entity'
import { LineasInvestigacion } from '../lineas_investigacion/entities/lineas_investigacion.entity'
@Injectable()
export class ProfesorService {
@@ -14,11 +17,17 @@ export class ProfesorService {
private datosAcademicosService: DatosAcademicosService,
private lineasInvestigacionService: LineasInvestigacionService,
private proyectosAcademicosService: ProyectosAcademicosService,
@InjectRepository(ProyectosAcademicos)
private readonly proyectosAcademicosRepository: Repository<ProyectosAcademicos>,
@InjectRepository(DatosAcademicos)
private readonly datosAcademicosRepository: Repository<DatosAcademicos>,
@InjectRepository(LineasInvestigacion)
private readonly lineasInvestigacionRepository: Repository<LineasInvestigacion>,
) {}
//register teacher
async register(data: profesorDto) {
const {num_trabajador,rfc } = data;
const {num_trabajador,rfc,proyectosAcademicos, datosAcademicos, lineasInvestigacion } = data;
const existrfc = await this.profesorRepository.findOne({where:{rfc}});
if(existrfc){
@@ -31,7 +40,45 @@ export class ProfesorService {
}
const newProfesor = this.profesorRepository.create(data);
return this.profesorRepository.save(newProfesor);
const savedProfesor = await this.profesorRepository.save(newProfesor);
if (proyectosAcademicos && proyectosAcademicos.length > 0) {
const proyectos = proyectosAcademicos.map(proyecto => {
const newProyecto = this.proyectosAcademicosRepository.create({
...proyecto,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newProyecto;
});
await this.proyectosAcademicosRepository.save(proyectos);
}
if (datosAcademicos && datosAcademicos.length > 0) {
const datos = datosAcademicos.map(dato => {
const newDato = this.datosAcademicosRepository.create({
...dato,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newDato;
});
await this.datosAcademicosRepository.save(datos);
}
if (lineasInvestigacion && lineasInvestigacion.length > 0) {
const lineas = lineasInvestigacion.map(linea => {
const newLinea = this.lineasInvestigacionRepository.create({
...linea,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newLinea;
});
await this.lineasInvestigacionRepository.save(lineas);
}
return savedProfesor;
}
//brings all teachers
@@ -50,8 +97,50 @@ export class ProfesorService {
throw new HttpException('Profesor not found', 404);
}
Object.assign(profesor, data);
return this.profesorRepository.save(profesor);
const { proyectosAcademicos, datosAcademicos, lineasInvestigacion, ...profesorData } = data;
Object.assign(profesor, profesorData);
const savedProfesor = await this.profesorRepository.save(profesor);
if (proyectosAcademicos) {
await this.proyectosAcademicosRepository.delete({ profesor: { id_profesor } });
const proyectos = proyectosAcademicos.map(proyecto => {
const newProyecto = this.proyectosAcademicosRepository.create({
...proyecto,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newProyecto;
});
await this.proyectosAcademicosRepository.save(proyectos);
}
if (datosAcademicos) {
await this.datosAcademicosRepository.delete({ profesor: { id_profesor } });
const datos = datosAcademicos.map(dato => {
const newDato = this.datosAcademicosRepository.create({
...dato,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newDato;
});
await this.datosAcademicosRepository.save(datos);
}
if (lineasInvestigacion) {
await this.lineasInvestigacionRepository.delete({ profesor: { id_profesor } });
const lineas = lineasInvestigacion.map(linea => {
const newLinea = this.lineasInvestigacionRepository.create({
...linea,
profesor: savedProfesor,
id_profesor: savedProfesor.id_profesor,
});
return newLinea;
});
await this.lineasInvestigacionRepository.save(lineas);
}
return savedProfesor;
}
//remove teacher
@@ -72,7 +161,11 @@ export class ProfesorService {
//brings teachers by id
async profile(id_profesor: number) {
const profesor = await this.profesorRepository.findOne({ where: { id_profesor } });
const profesor = await this.profesorRepository.findOne({
where: { id_profesor },
relations: ['proyectosAcademicos', 'datosAcademicos', 'lineasInvestigacion'],
});
if (!profesor) {
throw new HttpException('Profesor not found', 404);
}
@@ -111,8 +204,12 @@ export class ProfesorService {
return query.getMany();
}
async findAllPaginated(page: number, limit: number, filters: any): Promise<{ profesores: Profesor[], total: number, totalPages: number }> {
const query = this.profesorRepository.createQueryBuilder('profesor');
async findAllPaginated(
page: number,
limit: number,
filters: any
): Promise<{ profesores: Profesor[], total: number, totalPages: number }> {
const query = this.profesorRepository.createQueryBuilder('profesor')
if (filters.nombre) {
query.andWhere('profesor.nombre LIKE :nombre', { nombre: `%${filters.nombre}%` });
@@ -140,4 +237,5 @@ export class ProfesorService {
return { profesores, total, totalPages };
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AdscripcionService } from './adscripcion.service'; // Asegúrate de importar el servicio correcto
import { AdscripcionService } from './adscripcion.service';
describe('AdscripcionService', () => {
let service: AdscripcionService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AdscripcionService], // Asegúrate de incluir el servicio correcto aquí
providers: [AdscripcionService],
}).compile();
service = module.get<AdscripcionService>(AdscripcionService);
+8 -8
View File
@@ -20,7 +20,7 @@ import {Role} from '../permissions/role.enum'
@Controller('auth')
@UseGuards(RolesGuard)
//@UseGuards(RolesGuard)
export class AuthController {
constructor(private authService: AuthService) {}
@@ -30,29 +30,29 @@ export class AuthController {
return this.authService.signIn(data);
}
@UseGuards()
//@UseGuards()
@Post("register")
@Roles(Role.Admin)
//@Roles(Role.Admin)
async register(@Body() data: registerDto){
return this.authService.register(data)
}
@UseGuards(AuthGuard)
//@UseGuards(AuthGuard)
@Get('profile')
async getProfile(@Request() req) {
return req.user;
}
@UseGuards(AuthGuard)
//@UseGuards(AuthGuard)
@Put('Modificacion/:id')
@Roles(Role.Admin)
//@Roles(Role.Admin)
async update(@Param('id') userId: number, @Body() data: registerDto) {
return this.authService.update(userId, data);
}
@UseGuards(AuthGuard)
//@UseGuards(AuthGuard)
@Delete('Borrado/:id')
@Roles(Role.Admin)
//@Roles(Role.Admin)
async remove(@Param('id') id: number) {
await this.authService.remove(id);
return { message: 'User successfully deleted' };
+2 -2
View File
@@ -19,7 +19,7 @@ import {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
throw new UnauthorizedException('token faltante');
}
try {
const payload = await this.jwtService.verifyAsync(
@@ -31,7 +31,7 @@ import {
request['user'] = payload;
} catch {
throw new UnauthorizedException();
throw new UnauthorizedException('algo fallo');
}
return true;
}
+3 -3
View File
@@ -51,9 +51,9 @@ export class AuthService {
}
const payload = {
idUser: user.id_usuario,
username: user.usuario,
permissions: user.id_tipo_usuario,
id_usuario: user.id_usuario,
usuario: user.usuario,
id_tipo_usuario: user.id_tipo_usuario,
};
const token = this.jwtService.sign(payload);
+1 -1
View File
@@ -1,5 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CategoriaController } from './categoria.controller'; // Asumiendo que el controlador se llama EdificioController
import { CategoriaController } from './categoria.controller';
describe('CategoriaController', () => {
let controller: CategoriaController;
+2 -2
View File
@@ -1,12 +1,12 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CategoriaService } from './categoria.service'; // Asegúrate de importar el servicio correcto
import { CategoriaService } from './categoria.service';
describe('CategoriaService', () => {
let service: CategoriaService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CategoriaService], // Asegúrate de incluir el servicio correcto aquí
providers: [CategoriaService],
}).compile();
service = module.get<CategoriaService>(CategoriaService);
@@ -1,8 +1,12 @@
import { Controller, Delete, Param } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common';
import { DatosAcademicosService } from './datos_academicos.service';
@Controller('datos-academicos')
export class DatosAcademicosController {
constructor(private readonly datosAcademicosService: DatosAcademicosService) {}
@Get()
findAll() {
return this.datosAcademicosService.findAll();
}
}
@@ -14,4 +14,8 @@ export class DatosAcademicosService {
async removeByProfesorId(id_profesor: number): Promise<void> {
await this.datosAcademicosRepository.delete({ profesor: { id_profesor } });
}
async findAll(): Promise<DatosAcademicos[]> {
return this.datosAcademicosRepository.find();
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { EdificioController } from './edificio.controller'; // Asumiendo que el controlador se llama EdificioController
import { EdificioController } from './edificio.controller';
describe('EdificioController', () => {
let controller: EdificioController;
@@ -16,7 +16,7 @@ export class LineasInvestigacion {
@Column({ type: 'varchar', length: 350, nullable: true })
lineas_inv_html: string;
@ManyToOne(() => Profesor, profesor => profesor.lineasInvestigacion)
@ManyToOne(() => Profesor, profesor => profesor.lineasInvestigacion)
@JoinColumn({ name: 'id_profesor' })
profesor: Profesor;
}
@@ -1,9 +1,12 @@
import { Controller, Delete, Param } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common';
import { LineasInvestigacionService } from './lineas_investigacion.service';
@Controller('lineas-investigacion')
export class LineasInvestigacionController {
constructor(private readonly lineasInvestigacionService: LineasInvestigacionService) {}
@Get()
findAll() {
return this.lineasInvestigacionService.findAll();
}
}
@@ -14,4 +14,8 @@ export class LineasInvestigacionService {
async removeByProfesorId(id_profesor: number): Promise<void> {
await this.lineasInvestigacionRepository.delete({ profesor: { id_profesor } });
}
async findAll(): Promise<LineasInvestigacion[]> {
return this.lineasInvestigacionRepository.find();
}
}
+21 -13
View File
@@ -1,17 +1,12 @@
// roles.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Role } from './role.enum';
import { ROLES_KEY } from './roles.decorator';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
private jwtService: JwtService // Inyectar JwtService para verificar tokens JWT
) {}
constructor(private reflector: Reflector, private jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
@@ -24,15 +19,28 @@ export class RolesGuard implements CanActivate {
}
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
const authHeader = request.headers['authorization'];
if (!token) {
return false; // Denegar acceso si no hay token JWT
if (!authHeader) {
throw new UnauthorizedException('No authorization header provided');
}
const [, token] = authHeader.split(' ');
if (!token) {
throw new UnauthorizedException('No token provided');
}
let userPayload;
try {
const payload = await this.jwtService.verifyAsync(token); // Verificar y decodificar el token JWT
const userRoles: Role[] = payload.roles; // Suponiendo que los roles están en el payload del token
userPayload = this.jwtService.verify(token);
} 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));
} catch (err) {
@@ -1,9 +1,12 @@
import { Controller, Delete, Param } from '@nestjs/common';
import { Controller,Get } from '@nestjs/common';
import { ProyectosAcademicosService } from './proyectos_academicos.service';
@Controller('proyectos-academicos')
export class ProyectosAcademicosController {
constructor(private readonly proyectosAcademicosService: ProyectosAcademicosService) {}
@Get()
findAll() {
return this.proyectosAcademicosService.findAll();
}
}
@@ -14,4 +14,8 @@ export class ProyectosAcademicosService {
async removeByProfesorId(id_profesor: number): Promise<void> {
await this.proyectosAcademicosRepository.delete({ profesor: { id_profesor } });
}
async findAll(): Promise<ProyectosAcademicos[]> {
return this.proyectosAcademicosRepository.find();
}
}