Files
formularios_api/src/qr/qr-token.service.ts
T
miguel bc5ddb29c7 feat: add TipoEvento entity and related functionality
- Introduced TipoEvento entity with enum for event types.
- Created DTOs for creating and updating TipoEvento.
- Implemented TipoEvento service with methods for CRUD operations and seeding initial data.
- Added TipoEvento controller for handling HTTP requests related to event types.
- Integrated TipoEvento into the main application module.
- Updated Evento entity to include a relationship with TipoEvento.
- Enhanced ParticipanteEvento service to register attendance using QR tokens.
- Implemented QR token generation and validation for event attendance.
- Updated API documentation for new endpoints and functionalities.
- Adjusted TypeOrm configuration to include new entities.
2025-08-19 10:27:06 -06:00

90 lines
2.4 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class QrTokenService {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}
/**
* Genera un token JWT específico para el QR de asistencia
* @param id_participante ID del participante
* @param id_evento ID del evento
* @param id_cuestionario ID del cuestionario
* @returns Token JWT codificado
*/
generateQrToken(
id_participante: number,
id_evento: number,
id_cuestionario: number,
): string {
const payload = {
id_participante,
id_evento,
id_cuestionario,
type: 'qr_asistencia',
iat: Math.floor(Date.now() / 1000),
};
// Usar una clave secreta específica para QR o la misma que JWT general
const secret =
this.configService.get<string>('QR_JWT_SECRET') ||
this.configService.get<string>('JWT_SECRET', 'tu_clave_secreta');
return this.jwtService.sign(payload, {
secret,
expiresIn: '30d', // El QR puede ser válido por 30 días
});
}
/**
* Valida y decodifica un token de QR
* @param token Token JWT a validar
* @returns Datos decodificados del token o null si es inválido
*/
validateQrToken(token: string): {
id_participante: number;
id_evento: number;
id_cuestionario: number;
type: string;
iat: number;
} | null {
try {
const secret =
this.configService.get<string>('QR_JWT_SECRET') ||
this.configService.get<string>('JWT_SECRET', 'tu_clave_secreta');
const decoded = this.jwtService.verify(token, { secret });
// Verificar que sea un token de tipo QR de asistencia
if (decoded.type !== 'qr_asistencia') {
return null;
}
return {
id_participante: decoded.id_participante,
id_evento: decoded.id_evento,
id_cuestionario: decoded.id_cuestionario,
type: decoded.type,
iat: decoded.iat,
};
} catch (error) {
console.error('Error validando token QR:', error.message);
return null;
}
}
/**
* Verifica si un token QR es válido y no ha expirado
* @param token Token a verificar
* @returns true si es válido, false si no
*/
isTokenValid(token: string): boolean {
const decoded = this.validateQrToken(token);
return decoded !== null;
}
}