17vo Commit
This commit is contained in:
parent
31238500e6
commit
4cace7f18c
8 changed files with 97 additions and 6 deletions
|
|
@ -6,6 +6,7 @@ import {
|
|||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { TokenService } from '../services/token.service.js';
|
||||
import { KEY_ROLES } from '../decorators/roles.decorator.js';
|
||||
import { KEY_AUTORIZACION } from '../decorators/autorizacion.decorator.js';
|
||||
|
|
@ -17,8 +18,35 @@ export class AuthGuard implements CanActivate {
|
|||
constructor(
|
||||
private tokenService: TokenService,
|
||||
private reflector: Reflector,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
/** Última escritura de `ultConexion` por persona (throttle en memoria). */
|
||||
private readonly ultimaEscritura = new Map<string, number>();
|
||||
|
||||
/**
|
||||
* "Último uso" (tanda presencia 2026-11-01): refresca
|
||||
* `persona.ultConexion` como máximo 1 vez por minuto por persona —
|
||||
* UPDATE condicional en DB + caché en memoria, para no pegarle a la
|
||||
* base en cada request. Fire-and-forget: no frena la respuesta.
|
||||
*/
|
||||
private registrarActividad(idPersona?: string): void {
|
||||
if (!idPersona) return;
|
||||
const ahora = Date.now();
|
||||
const ultima = this.ultimaEscritura.get(idPersona) ?? 0;
|
||||
if (ahora - ultima < 60_000) return;
|
||||
this.ultimaEscritura.set(idPersona, ahora);
|
||||
void this.dataSource
|
||||
.query(
|
||||
`UPDATE persona SET "ultConexion" = now()
|
||||
WHERE "idPersona" = $1
|
||||
AND ("ultConexion" IS NULL
|
||||
OR "ultConexion" < now() - interval '60 seconds')`,
|
||||
[idPersona],
|
||||
)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
|
|
@ -48,6 +76,7 @@ export class AuthGuard implements CanActivate {
|
|||
}
|
||||
|
||||
request.user = payload;
|
||||
this.registrarActividad(payload.idPersona);
|
||||
|
||||
if (payload.autorizacion === Autorizacion.Developer) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { ServicioTurno } from '../servicio-turno/entities/servicio-turno.entity.
|
|||
import { Turno } from '../turno/entities/turno.entity.js';
|
||||
import { Configuracion } from '../configuracion/entities/configuracion.entity.js';
|
||||
import { Persona } from '../persona/entities/persona.entity.js';
|
||||
import { Equipo } from '../equipo/entities/equipo.entity.js';
|
||||
import {
|
||||
AsistenciaDto,
|
||||
MarcarAsistenciaDto,
|
||||
|
|
@ -434,6 +435,24 @@ export class AsistenciaService {
|
|||
clean.fecSalida = dto.fecSalida === null ? null : new Date(dto.fecSalida);
|
||||
}
|
||||
|
||||
// Reasignación de equipo (gate de UI por whatsapp 2026-11-01): solo
|
||||
// Dev/SuperAdmin — un Líder que edite su fila no puede moverla de
|
||||
// equipo. Debe existir (evita ids colgantes vía API).
|
||||
if (dto.idEquipo !== undefined) {
|
||||
if (!isDeveloper(user) && !isSuperAdmin(user)) {
|
||||
serviceResult.message = 'Solo SuperAdmin/Developer puede cambiar el equipo.';
|
||||
return serviceResult;
|
||||
}
|
||||
const equipo = await this.asistenciaRepository.manager.findOne(Equipo, {
|
||||
where: { idEquipo: dto.idEquipo },
|
||||
});
|
||||
if (!equipo) {
|
||||
serviceResult.message = 'El equipo indicado no existe.';
|
||||
return serviceResult;
|
||||
}
|
||||
clean.idEquipo = dto.idEquipo;
|
||||
}
|
||||
|
||||
if (Object.keys(clean).length === 0) {
|
||||
serviceResult.message = 'No hay campos permitidos para actualizar.';
|
||||
return serviceResult;
|
||||
|
|
|
|||
|
|
@ -96,6 +96,15 @@ export class UpdateAsistenciaDto {
|
|||
@IsOptional()
|
||||
estado?: EstadoAsistencia;
|
||||
|
||||
/**
|
||||
* Reasignación de equipo (gate de UI por whatsapp 2026-11-01): el
|
||||
* service SOLO lo aplica para Dev/SuperAdmin.
|
||||
*/
|
||||
@ApiProperty({ required: false })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
idEquipo?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Body, Controller, Get, HttpStatus, Patch, Post, Req } from '@nestjs/common';
|
||||
import { Body, Controller, Get, HttpStatus, Patch, Post, Query, Req } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import type { Request } from 'express';
|
||||
import { AuthService } from './auth.service.js';
|
||||
|
|
@ -134,7 +134,10 @@ export class AuthController {
|
|||
|
||||
@ApiBearerAuth()
|
||||
@Get('perfil')
|
||||
async getPerfil(@Req() req: AuthRequest): Promise<ApiResult> {
|
||||
async getPerfil(
|
||||
@Req() req: AuthRequest,
|
||||
@Query('platform') platform?: string,
|
||||
): Promise<ApiResult> {
|
||||
const apiResult = defaultApiResult(routeAuth.perfil.title, routeAuth.perfil.route);
|
||||
|
||||
try {
|
||||
|
|
@ -145,7 +148,7 @@ export class AuthController {
|
|||
return apiResult;
|
||||
}
|
||||
|
||||
const result = await this.authService.getPerfil(idPersona);
|
||||
const result = await this.authService.getPerfil(idPersona, platform);
|
||||
|
||||
if (result.boolean) {
|
||||
apiResult.status = 'correct';
|
||||
|
|
|
|||
|
|
@ -233,6 +233,11 @@ export class AuthService {
|
|||
this.otpCache.delete(persona.idPersona);
|
||||
|
||||
const updates: Partial<Persona> = { ultConexion: new Date() };
|
||||
// Plataforma del login (tanda presencia 2026-11-01): Android/iOS/Web.
|
||||
const plataforma = dto.platform?.trim();
|
||||
if (plataforma) {
|
||||
updates.platform = plataforma.slice(0, 20);
|
||||
}
|
||||
if (!persona.verificado) {
|
||||
updates.verificado = true;
|
||||
}
|
||||
|
|
@ -302,7 +307,10 @@ export class AuthService {
|
|||
return serviceResult;
|
||||
}
|
||||
|
||||
async getPerfil(idPersona: string): Promise<ServiceResult> {
|
||||
async getPerfil(
|
||||
idPersona: string,
|
||||
platform?: string,
|
||||
): Promise<ServiceResult> {
|
||||
const serviceResult = defaultServiceResult();
|
||||
|
||||
const persona = await this.personaRepository.findOneBy({ idPersona });
|
||||
|
|
@ -312,6 +320,15 @@ export class AuthService {
|
|||
return serviceResult;
|
||||
}
|
||||
|
||||
// Plataforma del arranque/revalidación (tanda presencia 2026-11-01):
|
||||
// el splash la manda en cada apertura con `?platform=` y solo se
|
||||
// escribe si cambió (con token de 30d el login no refresca a diario).
|
||||
const nueva = platform?.trim().slice(0, 20);
|
||||
if (nueva && nueva !== persona.platform) {
|
||||
await this.personaRepository.update(idPersona, { platform: nueva });
|
||||
persona.platform = nueva;
|
||||
}
|
||||
|
||||
serviceResult.boolean = true;
|
||||
serviceResult.message = 'Perfil obtenido.';
|
||||
serviceResult.number = 1;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class EnviarOtpDto {
|
||||
@ApiProperty({ example: '591' })
|
||||
|
|
@ -28,6 +28,12 @@ export class LoginDto {
|
|||
@IsString()
|
||||
@IsNotEmpty()
|
||||
codigo: string;
|
||||
|
||||
/** Plataforma de la app (tanda presencia 2026-11-01): Android/iOS/Web. */
|
||||
@ApiProperty({ required: false, example: 'Android' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
platform?: string;
|
||||
}
|
||||
|
||||
export class UpdatePerfilDto {
|
||||
|
|
|
|||
|
|
@ -49,6 +49,14 @@ export class Persona {
|
|||
@Column({ type: 'timestamptz', nullable: true })
|
||||
ultConexion?: Date | null;
|
||||
|
||||
/**
|
||||
* Última plataforma desde la que inició sesión la persona
|
||||
* (`Android` | `iOS` | `Web` | `Otro`; tanda presencia 2026-11-01).
|
||||
* La manda la app en `POST /auth/login`.
|
||||
*/
|
||||
@Column({ type: 'varchar', nullable: true })
|
||||
platform?: string | null;
|
||||
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
default: EstadoGeneral.Activo,
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
Loading…
Add table
Reference in a new issue