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('QR_JWT_SECRET') || this.configService.get('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('QR_JWT_SECRET') || this.configService.get('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; } }