7 Commits

16 changed files with 296 additions and 39 deletions
+26 -7
View File
@@ -19,6 +19,7 @@
"@nestjs/typeorm": "^11.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"ldapts": "^8.1.7",
"mysql2": "^3.14.4",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
@@ -2408,14 +2409,14 @@
}
},
"node_modules/@nestjs/platform-express": {
"version": "11.1.15",
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.15.tgz",
"integrity": "sha512-sR42dQ5fPy4NGbnhT4mRIJLL0h2eNY4KpLkcfd27vg5XdTjQQ07wkQORrw6rAkWkBvMRr0dmhAcUBnXpe7ro5Q==",
"version": "11.1.16",
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.16.tgz",
"integrity": "sha512-IOegr5+ZfUiMKgk+garsSU4MOkPRhm46e6w8Bp1GcO4vCdl9Piz6FlWAzKVfa/U3Hn/DdzSVJOW3TWcQQFdBDw==",
"license": "MIT",
"dependencies": {
"cors": "2.8.6",
"express": "5.2.1",
"multer": "2.1.0",
"multer": "2.1.1",
"path-to-regexp": "8.3.0",
"tslib": "2.8.1"
},
@@ -7557,6 +7558,18 @@
"json-buffer": "3.0.1"
}
},
"node_modules/ldapts": {
"version": "8.1.7",
"resolved": "https://registry.npmjs.org/ldapts/-/ldapts-8.1.7.tgz",
"integrity": "sha512-TJl6T92eIwMf/OJ0hDfKVa6ISwzo+lqCWCI5Mf//ARlKa3LKQZaSrme/H2rCRBhW0DZCQlrsV+fgoW5YHRNLUw==",
"license": "MIT",
"dependencies": {
"strict-event-emitter-types": "2.0.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -7970,9 +7983,9 @@
"license": "MIT"
},
"node_modules/multer": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.1.0.tgz",
"integrity": "sha512-TBm6j41rxNohqawsxlsWsNNh/VdV4QFXcBvRcPhXaA05EZ79z0qJ2bQFpync6JBoHTeNY5Q1JpG7AlTjdlfAEA==",
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.1.1.tgz",
"integrity": "sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
@@ -9246,6 +9259,12 @@
"node": ">=10.0.0"
}
},
"node_modules/strict-event-emitter-types": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/strict-event-emitter-types/-/strict-event-emitter-types-2.0.0.tgz",
"integrity": "sha512-Nk/brWYpD85WlOgzw5h173aci0Teyv8YdIAEtV+N88nDB0dLlazZyJMIsN6eo1/AR61l+p6CJTG1JIyFaoNEEA==",
"license": "ISC"
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+1
View File
@@ -30,6 +30,7 @@
"@nestjs/typeorm": "^11.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"ldapts": "^8.1.7",
"mysql2": "^3.14.4",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ActiveDirectoryController } from './active-directory.controller';
import { ActiveDirectoryService } from './active-directory.service';
describe('ActiveDirectoryController', () => {
let controller: ActiveDirectoryController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ActiveDirectoryController],
providers: [ActiveDirectoryService],
}).compile();
controller = module.get<ActiveDirectoryController>(ActiveDirectoryController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
@@ -0,0 +1,28 @@
import { Controller, Post, Body, Param } from '@nestjs/common';
import { ActiveDirectoryService } from './active-directory.service';
@Controller('active-directory')
export class ActiveDirectoryController {
constructor(private readonly adService: ActiveDirectoryService) {}
@Post('crear/:cuenta')
async crearUsuario(@Param('cuenta') cuenta: string) {
await this.adService.createUser(cuenta);
return { message: `Usuario ${cuenta} creado en AD` };
}
@Post('reset/:cuenta')
async resetPassword(@Param('cuenta') cuenta: string) {
await this.adService.resetPassword(cuenta);
return { message: `Contraseña de ${cuenta} reseteada` };
}
@Post('cambiar-password/:cuenta')
async cambiarPassword(
@Param('cuenta') cuenta: string,
@Body('password') password?: string,
) {
await this.adService.changePassword(cuenta, password);
return { message: `Contraseña de ${cuenta} actualizada` };
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ActiveDirectoryService } from './active-directory.service';
import { ActiveDirectoryController } from './active-directory.controller';
@Module({
imports: [ConfigModule],
providers: [ActiveDirectoryService],
controllers: [ActiveDirectoryController],
exports: [ActiveDirectoryService],
})
export class ActiveDirectoryModule {}
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ActiveDirectoryService } from './active-directory.service';
describe('ActiveDirectoryService', () => {
let service: ActiveDirectoryService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ActiveDirectoryService],
}).compile();
service = module.get<ActiveDirectoryService>(ActiveDirectoryService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
@@ -0,0 +1,124 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Client, Attribute, Change } from 'ldapts';
@Injectable()
export class ActiveDirectoryService {
private readonly logger = new Logger(ActiveDirectoryService.name);
constructor(private configService: ConfigService) { }
private createClient(): Client {
return new Client({
url: this.configService.get<string>('AD_URL')!,
tlsOptions: { rejectUnauthorized: false },
});
}
async createUser(cuenta: string): Promise<void> {
const client = this.createClient();
const bindDN = this.configService.get<string>('AD_BIND_DN')!;
const bindPass = this.configService.get<string>('AD_BIND_PASS')!;
const baseDN = this.configService.get<string>('AD_BASE_DN')!;
try {
await client.bind(bindDN, bindPass);
const userDN = `CN=${cuenta},${baseDN}`;
await client.add(userDN, {
objectClass: ['top', 'person', 'organizationalPerson', 'user'],
sAMAccountName: cuenta,
cn: cuenta,
description: 'Creado desde el Sitio',
userAccountControl: '32',
});
const encodedPassword = Buffer.from(`"${cuenta}"`, 'utf16le');
await client.modify(userDN, [
new Change({
operation: 'replace',
modification: new Attribute({ type: 'unicodePwd', values: [encodedPassword] }),
}),
]);
await client.modify(userDN, [
new Change({
operation: 'replace',
modification: new Attribute({ type: 'pwdLastSet', values: ['0'] }),
}),
]);
await client.modify(userDN, [
new Change({
operation: 'replace',
modification: new Attribute({ type: 'userAccountControl', values: ['512'] }),
}),
]);
this.logger.log(`Usuario ${cuenta} creado exitosamente en AD`);
} catch (error) {
this.logger.error(`Error al crear usuario ${cuenta} en AD`, error);
throw error;
} finally {
await client.unbind();
}
}
async resetPassword(cuenta: string): Promise<void> {
const client = this.createClient();
const bindDN = this.configService.get<string>('AD_BIND_DN')!;
const bindPass = this.configService.get<string>('AD_BIND_PASS')!;
const baseDN = this.configService.get<string>('AD_BASE_DN')!;
try {
await client.bind(bindDN, bindPass);
const userDN = `CN=${cuenta},${baseDN}`;
await client.del(userDN);
this.logger.log(`Usuario ${cuenta} eliminado de AD`);
} catch (error) {
this.logger.warn(`No se pudo eliminar ${cuenta} de AD (puede no existir)`, error);
} finally {
await client.unbind();
}
await this.createUser(cuenta);
}
async changePassword(cuenta: string, newPass?: string): Promise<void> {
const client = this.createClient();
const bindDN = this.configService.get<string>('AD_BIND_DN')!;
const bindPass = this.configService.get<string>('AD_BIND_PASS')!;
const baseDN = this.configService.get<string>('AD_BASE_DN')!;
const password = newPass ?? cuenta;
try {
await client.bind(bindDN, bindPass);
const userDN = `CN=${cuenta},${baseDN}`;
const encodedPassword = Buffer.from(`"${password}"`, 'utf16le');
await client.modify(userDN, [
new Change({
operation: 'replace',
modification: new Attribute({ type: 'unicodePwd', values: [encodedPassword] }),
}),
]);
await client.modify(userDN, [
new Change({
operation: 'replace',
modification: new Attribute({ type: 'pwdLastSet', values: ['0'] }),
}),
]);
this.logger.log(`Contraseña de ${cuenta} actualizada`);
} catch (error) {
this.logger.error(`Error al cambiar contraseña de ${cuenta}`, error);
throw error;
} finally {
await client.unbind();
}
}
}
@@ -0,0 +1 @@
export class CreateActiveDirectoryDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateActiveDirectoryDto } from './create-active-directory.dto';
export class UpdateActiveDirectoryDto extends PartialType(CreateActiveDirectoryDto) {}
@@ -0,0 +1 @@
export class ActiveDirectory {}
+19 -25
View File
@@ -61,31 +61,25 @@ export class AlumnoInscritoService {
take: 100,
});
}
async findAllInscritos(idPeriodo: number) {
return this.alumnoInscritoRepo
.createQueryBuilder('inscritos')
.innerJoin('inscritos.alumno', 'alumno')
.innerJoin('alumno.carrera', 'carrera')
.innerJoin('inscritos.plataforma', 'plataforma')
.innerJoin('inscritos.periodo', 'periodo')
.where('periodo.id_periodo = :idPeriodo', { idPeriodo })
.select([
'carrera.carrera AS carrera',
'alumno.genero AS genero',
'plataforma.nombre AS profesor',
'COUNT(DISTINCT alumno.id_cuenta) AS total'
])
.groupBy('carrera.carrera')
.addGroupBy('alumno.genero')
.addGroupBy('plataforma.nombre')
.getRawMany();
}
async findAllInscritos(idPeriodo: number) {
return this.alumnoInscritoRepo
.createQueryBuilder('inscritos')
.innerJoin('inscritos.alumno', 'alumno')
.innerJoin('alumno.carrera', 'carrera')
.innerJoin('inscritos.plataforma', 'plataforma')
.innerJoin('inscritos.periodo', 'periodo')
.where('periodo.id_periodo = :idPeriodo', { idPeriodo })
.select([
'carrera.carrera AS carrera',
'plataforma.nombre AS profesor',
'COUNT(DISTINCT CASE WHEN alumno.genero IN (\'F\', \'Femenino\') THEN alumno.id_cuenta END) AS femenino',
'COUNT(DISTINCT CASE WHEN alumno.genero IN (\'M\', \'Masculino\') THEN alumno.id_cuenta END) AS masculino',
'COUNT(DISTINCT alumno.id_cuenta) AS total'
])
.groupBy('carrera.carrera')
.addGroupBy('plataforma.nombre')
.getRawMany();
}
async findAllPlataforma() {
return this.plataformaRepo.find();
+2
View File
@@ -43,6 +43,7 @@ import { BitacoraModule } from './bitacora/bitacora.module';
import { Bitacora } from './bitacora/entities/bitacora.entity';
import { MensajeModule } from './mensaje/mensaje.module';
import { Mensaje } from './mensaje/entities/mensaje.entity';
import { ActiveDirectoryModule } from './active-directory/active-directory.module';
import { CostoModule } from './costo/costo.module';
import { Costo } from './costo/entities/costo.entity';
@@ -107,6 +108,7 @@ import { Costo } from './costo/entities/costo.entity';
BitacoraModule,
MensajeModule,
CostoModule,
ActiveDirectoryModule,
],
controllers: [AppController],
providers: [AppService],
+12 -5
View File
@@ -11,26 +11,33 @@ export class MesaController {
constructor(private readonly mesaService: MesaService) { }
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR,Role.ATENCION_USUARIOS,Role.SERVICIO_SOCIAL)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR, Role.ATENCION_USUARIOS, Role.SERVICIO_SOCIAL)
@Get()
async findAll() {
return this.mesaService.findAll();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR,Role.ATENCION_USUARIOS,Role.SERVICIO_SOCIAL)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR, Role.ATENCION_USUARIOS, Role.SERVICIO_SOCIAL)
@Get('activo')
async findAllActivo() {
return this.mesaService.findAllActivo();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR,Role.ATENCION_USUARIOS,Role.SERVICIO_SOCIAL)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR, Role.ATENCION_USUARIOS, Role.SERVICIO_SOCIAL)
@Get('uso')
async findActiveMesas() {
return this.mesaService.findActiveMesas();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR, Role.ATENCION_USUARIOS, Role.SERVICIO_SOCIAL)
@Get('usoWhitout')
async findActiveMesasWhitoudOcupado() {
return this.mesaService.findActiveMesasWhitoudOcupado();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR)
@Patch(':id')
@@ -42,7 +49,7 @@ export class MesaController {
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR,Role.ATENCION_USUARIOS,Role.SERVICIO_SOCIAL)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR, Role.ATENCION_USUARIOS, Role.SERVICIO_SOCIAL)
@Patch(':id/activo')
toggleActivo(@Param('id') id: number) {
return this.mesaService.toggleActivo(+id);
+23
View File
@@ -142,4 +142,27 @@ export class MesaService {
.orderBy('mesa.id_mesa', 'ASC')
.getRawMany();
}
findActiveMesasWhitoudOcupado() {
return this.mesaRepository
.createQueryBuilder('mesa')
.select([
'mesa.id_mesa AS id_mesa',
])
.where('mesa.activo = 1')
.andWhere(`
NOT EXISTS (
SELECT 1
FROM bitacora_mesa bm
WHERE bm.id_mesa = mesa.id_mesa
AND TIMESTAMPDIFF(
SECOND,
NOW(),
DATE_ADD(bm.tiempo_entrada, INTERVAL bm.tiempo_asignado MINUTE)
) > 0
)
`)
.orderBy('mesa.id_mesa', 'ASC')
.getRawMany();
}
}
+1 -2
View File
@@ -19,8 +19,7 @@ import { Role } from 'src/role.enum';
export class UserController {
constructor(private readonly userService: UserService) { }
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMINISTRADOR, Role.SUPER_ADMINISTRADOR)
@Get()
async getAll() {
return this.userService.getAll();
+4
View File
@@ -28,6 +28,10 @@ export class UserService {
where: { usuario, password },
});
if(user?.activo === 0){
throw new NotFoundException(`El usuario se encuentra desactivado`);
}
if (!user) {
throw new NotFoundException(`El usuario o la contraseña es incorrecta`);
}