From 4b93e057a92361c93c79175f4e27745579e203d9 Mon Sep 17 00:00:00 2001 From: Lxuratorres <178488295+Lxuratorres@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:00:30 +0000 Subject: [PATCH] API: lecturas del panel (metricas, actividad, administradores) Endpoints nuevos para el panel, detras del mismo portero de /api/admin: - GET /api/admin/lugares/{id}/pois: todos los POI, tambien los inactivos. - GET /api/admin/metricas: visitas, eventos por tipo, visitas por dia y los 10 POI mas vistos, sobre la tabla eventos. - GET /api/admin/actividad: cambios registrados en auditoria, paginados, con el correo de quien los hizo. - GET y PUT /api/admin/administradores: listar y cambiar el rol en perfiles. No deja quitarse el rol a uno mismo ni quitar el ultimo admin, y la auditoria registra quien hizo el cambio. Endpoint publico POST /api/eventos para que la app registre el uso. Solo acepta los cinco tipos acordados. eventos, auditoria y auth.users entran a TourDbContext con ExcludeFromMigrations: EF las lee pero no las crea. perfiles se lee con SQL directo porque su rol es un enum de Postgres. No hay migracion nueva. Se agrega scripts/datos/perfiles_eventos_auditoria.sql, que crea esas tablas en Supabase, y se regeneran openapi.yaml y schema.d.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EB4pRoGeNrZBwz45Y4jvo5 --- README.md | 3 +- apps/admin/src/api/schema.d.ts | 326 ++++++++++++++++ packages/contracts/openapi.yaml | 363 ++++++++++++++++++ scripts/datos/perfiles_eventos_auditoria.sql | 270 +++++++++++++ .../api/Controllers/AdminPanelController.cs | 80 ++++ services/api/Controllers/EventosController.cs | 22 ++ services/api/DTOs/PanelDtos.cs | 26 ++ services/api/Data/TourDbContext.cs | 53 +++ services/api/Models/TablasSupabase.cs | 38 ++ services/api/Program.cs | 8 + services/api/Services/PanelService.cs | 260 +++++++++++++ .../Services/RequiereClaveAdminAttribute.cs | 10 + 12 files changed, 1458 insertions(+), 1 deletion(-) create mode 100644 scripts/datos/perfiles_eventos_auditoria.sql create mode 100644 services/api/Controllers/AdminPanelController.cs create mode 100644 services/api/Controllers/EventosController.cs create mode 100644 services/api/DTOs/PanelDtos.cs create mode 100644 services/api/Models/TablasSupabase.cs create mode 100644 services/api/Services/PanelService.cs diff --git a/README.md b/README.md index 46755eb..2aec83c 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,8 @@ dotnet run --launch-profile http - **Base de datos:** usa el *session pooler* (puerto `5432`). Con el *transaction pooler* (puerto `6543`) la API se queda colgada al conectar. La conexión directa (`db.[PROYECTO].supabase.co`) solo funciona con IPv6. La contraseña es la de la base (Supabase → Project Settings → Database), y el usuario lleva el id del proyecto pegado. - **Clave de administración:** los endpoints que escriben (`/api/admin/*`) piden la cabecera `X-Admin-Key`. Sin clave configurada, en `Development` quedan abiertos (la API lo avisa al arrancar) y en cualquier otro entorno responden `503`. -- **Login de administradores (Supabase Auth):** el panel también puede entrar con el token de sesión de Supabase, en `Authorization: Bearer `. La API comprueba el token con las claves públicas de `Supabase:Url` (en `appsettings.json`) y deja pasar solo a quien tenga `rol = 'admin'` en la tabla `perfiles` (`supabase/migrations/0002_perfiles_y_auth.sql`). Responde `401` sin token válido y `403` si la persona no es admin. Si el proyecto aún firma con el *JWT secret* antiguo, guárdalo con `dotnet user-secrets set "Supabase:JwtSecret" "..."`. `X-Admin-Key` sigue funcionando para Swagger y los scripts. +- **Login de administradores (Supabase Auth):** el panel también puede entrar con el token de sesión de Supabase, en `Authorization: Bearer `. La API comprueba el token con las claves públicas de `Supabase:Url` (en `appsettings.json`) y deja pasar solo a quien tenga `rol = 'admin'` en la tabla `perfiles` (la crea `scripts/datos/perfiles_eventos_auditoria.sql`; no corras `supabase/migrations` completas, porque duplican las tablas de contenido que maneja EF). Responde `401` sin token válido y `403` si la persona no es admin. Si el proyecto aún firma con el *JWT secret* antiguo, guárdalo con `dotnet user-secrets set "Supabase:JwtSecret" "..."`. `X-Admin-Key` sigue funcionando para Swagger y los scripts. +- **Lecturas del panel:** con el mismo portero, `GET /api/admin/lugares/{id}/pois` (incluye los POI inactivos), `GET /api/admin/metricas?desde=&hasta=` (sobre `eventos`, últimos 30 días si no hay fechas), `GET /api/admin/actividad` (sobre `auditoria`, paginada), `GET /api/admin/administradores` y `PUT /api/admin/administradores/{userId}` (cambiar rol; no deja quitarse el rol a uno mismo ni quitar el último admin). La app registra el uso con `POST /api/eventos`, que es público y solo acepta los cinco tipos de evento acordados. - **Uso:** la API queda en `http://localhost:5209` y Swagger en `/swagger` (botón **Authorize** para la clave). `scripts/correr_api.ps1` la levanta y reenvía el puerto a un teléfono conectado por USB. - **Migraciones:** `dotnet ef database update`, solo contra la base prevista para tu entorno. diff --git a/apps/admin/src/api/schema.d.ts b/apps/admin/src/api/schema.d.ts index ca0ac57..fdfab36 100644 --- a/apps/admin/src/api/schema.d.ts +++ b/apps/admin/src/api/schema.d.ts @@ -574,6 +574,210 @@ export interface paths { patch?: never; trace?: never; }; + "/api/admin/lugares/{lugarId}/pois": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: never; + header?: never; + path: { + lugarId: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": components["schemas"]["PoiDto"][]; + "application/json": components["schemas"]["PoiDto"][]; + "text/json": components["schemas"]["PoiDto"][]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/metricas": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: { + desde?: string; + hasta?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": components["schemas"]["MetricasDto"]; + "application/json": components["schemas"]["MetricasDto"]; + "text/json": components["schemas"]["MetricasDto"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/actividad": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: { + pagina?: number; + tamano?: number; + entidad?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": components["schemas"]["ActividadPaginaDto"]; + "application/json": components["schemas"]["ActividadPaginaDto"]; + "text/json": components["schemas"]["ActividadPaginaDto"]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/administradores": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: { + todos?: boolean; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": components["schemas"]["PerfilDto"][]; + "application/json": components["schemas"]["PerfilDto"][]; + "text/json": components["schemas"]["PerfilDto"][]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/administradores/{userId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put: { + parameters: { + query?: never; + header?: never; + path: { + userId: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": components["schemas"]["CambiarRolRequest"]; + "text/json": components["schemas"]["CambiarRolRequest"]; + "application/*+json": components["schemas"]["CambiarRolRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": components["schemas"]["PerfilDto"]; + "application/json": components["schemas"]["PerfilDto"]; + "text/json": components["schemas"]["PerfilDto"]; + }; + }; + }; + }; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/admin/pois": { parameters: { query?: never; @@ -1006,10 +1210,74 @@ export interface paths { patch?: never; trace?: never; }; + "/api/eventos": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": components["schemas"]["RegistrarEventoRequest"]; + "text/json": components["schemas"]["RegistrarEventoRequest"]; + "application/*+json": components["schemas"]["RegistrarEventoRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { schemas: { + ActividadDto: { + /** Format: int64 */ + id?: number; + /** Format: date-time */ + ts?: string; + /** Format: uuid */ + actor_id?: string | null; + actor_correo?: string | null; + accion?: string | null; + entidad?: string | null; + entidad_id?: string | null; + /** @description Objeto JSON libre. */ + antes?: Record | null; + /** @description Objeto JSON libre. */ + despues?: Record | null; + }; + ActividadPaginaDto: { + /** Format: int32 */ + pagina?: number; + /** Format: int32 */ + tamano?: number; + /** Format: int32 */ + total?: number; + items?: components["schemas"]["ActividadDto"][] | null; + }; ActualizarEscenaRequest: { /** Format: int32 */ poiId?: number | null; @@ -1077,6 +1345,14 @@ export interface components { }; /** @enum {string} */ Audiencia: "externo" | "estudiante" | "docente"; + CambiarRolRequest: { + rol?: string | null; + }; + ConteoTipoDto: { + tipo?: string | null; + /** Format: int32 */ + eventos?: number; + }; CrearEscenaRequest: { /** Format: int32 */ lugarId?: number; @@ -1269,6 +1545,28 @@ export interface components { subtitulos_url?: string | null; idioma?: string | null; }; + MetricasDto: { + /** Format: date */ + desde?: string; + /** Format: date */ + hasta?: string; + /** Format: int32 */ + visitas?: number; + /** Format: int32 */ + eventos?: number; + por_tipo?: components["schemas"]["ConteoTipoDto"][] | null; + por_dia?: components["schemas"]["VisitasDiaDto"][] | null; + pois_mas_vistos?: components["schemas"]["PoiVistoDto"][] | null; + }; + PerfilDto: { + /** Format: uuid */ + user_id?: string; + correo?: string | null; + rol?: string | null; + verificado?: boolean; + /** Format: date-time */ + creado_en?: string; + }; Poi: { /** Format: int32 */ id?: number; @@ -1319,10 +1617,30 @@ export interface components { audiencias?: components["schemas"]["Audiencia"][] | null; activo?: boolean; }; + PoiVistoDto: { + /** Format: int32 */ + poi_id?: number; + nombre?: string | null; + /** Format: int32 */ + visitas?: number; + /** Format: int32 */ + eventos?: number; + }; RecorridoDto: { escenas?: components["schemas"]["EscenaDto"][] | null; hotspots?: components["schemas"]["HotspotDto"][] | null; }; + RegistrarEventoRequest: { + /** Format: uuid */ + sesionId?: string; + tipo?: string | null; + /** Format: int32 */ + poiId?: number | null; + /** Format: int32 */ + escenaId?: number | null; + /** @description Objeto JSON libre. */ + payload?: Record | null; + }; Ruta: { /** Format: int32 */ id?: number; @@ -1359,6 +1677,14 @@ export interface components { TipoHotspot: "navegacion" | "info"; /** @enum {string} */ TipoMedio: "imagen" | "video" | "audio"; + VisitasDiaDto: { + /** Format: date */ + dia?: string; + /** Format: int32 */ + visitas?: number; + /** Format: int32 */ + eventos?: number; + }; }; responses: never; parameters: never; diff --git a/packages/contracts/openapi.yaml b/packages/contracts/openapi.yaml index 38e3b36..dc46570 100644 --- a/packages/contracts/openapi.yaml +++ b/packages/contracts/openapi.yaml @@ -437,6 +437,162 @@ paths: responses: '200': description: OK + '/api/admin/lugares/{lugarId}/pois': + get: + tags: + - AdminPanel + parameters: + - name: lugarId + in: path + required: true + schema: + type: integer + format: int32 + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/PoiDto' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PoiDto' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/PoiDto' + /api/admin/metricas: + get: + tags: + - AdminPanel + parameters: + - name: desde + in: query + schema: + type: string + format: date + - name: hasta + in: query + schema: + type: string + format: date + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/MetricasDto' + application/json: + schema: + $ref: '#/components/schemas/MetricasDto' + text/json: + schema: + $ref: '#/components/schemas/MetricasDto' + /api/admin/actividad: + get: + tags: + - AdminPanel + parameters: + - name: pagina + in: query + schema: + type: integer + format: int32 + default: 1 + - name: tamano + in: query + schema: + type: integer + format: int32 + default: 20 + - name: entidad + in: query + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/ActividadPaginaDto' + application/json: + schema: + $ref: '#/components/schemas/ActividadPaginaDto' + text/json: + schema: + $ref: '#/components/schemas/ActividadPaginaDto' + /api/admin/administradores: + get: + tags: + - AdminPanel + parameters: + - name: todos + in: query + schema: + type: boolean + default: false + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/PerfilDto' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PerfilDto' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/PerfilDto' + '/api/admin/administradores/{userId}': + put: + tags: + - AdminPanel + parameters: + - name: userId + in: path + required: true + schema: + type: string + format: uuid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CambiarRolRequest' + text/json: + schema: + $ref: '#/components/schemas/CambiarRolRequest' + application/*+json: + schema: + $ref: '#/components/schemas/CambiarRolRequest' + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/PerfilDto' + application/json: + schema: + $ref: '#/components/schemas/PerfilDto' + text/json: + schema: + $ref: '#/components/schemas/PerfilDto' /api/admin/pois: post: tags: @@ -734,8 +890,78 @@ paths: responses: '200': description: OK + /api/eventos: + post: + tags: + - Eventos + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RegistrarEventoRequest' + text/json: + schema: + $ref: '#/components/schemas/RegistrarEventoRequest' + application/*+json: + schema: + $ref: '#/components/schemas/RegistrarEventoRequest' + responses: + '200': + description: OK components: schemas: + ActividadDto: + type: object + properties: + id: + type: integer + format: int64 + ts: + type: string + format: date-time + actor_id: + type: string + format: uuid + nullable: true + actor_correo: + type: string + nullable: true + accion: + type: string + nullable: true + entidad: + type: string + nullable: true + entidad_id: + type: string + nullable: true + antes: + type: object + description: Objeto JSON libre. + nullable: true + despues: + type: object + description: Objeto JSON libre. + nullable: true + additionalProperties: false + ActividadPaginaDto: + type: object + properties: + pagina: + type: integer + format: int32 + tamano: + type: integer + format: int32 + total: + type: integer + format: int32 + items: + type: array + items: + $ref: '#/components/schemas/ActividadDto' + nullable: true + additionalProperties: false ActualizarEscenaRequest: type: object properties: @@ -765,6 +991,9 @@ components: type: number format: double nullable: true + textoAlt: + type: string + nullable: true additionalProperties: false ActualizarHotspotRequest: type: object @@ -882,6 +1111,23 @@ components: - estudiante - docente type: string + CambiarRolRequest: + type: object + properties: + rol: + type: string + nullable: true + additionalProperties: false + ConteoTipoDto: + type: object + properties: + tipo: + type: string + nullable: true + eventos: + type: integer + format: int32 + additionalProperties: false CrearEscenaRequest: type: object properties: @@ -914,6 +1160,9 @@ components: type: number format: double nullable: true + textoAlt: + type: string + nullable: true additionalProperties: false CrearHotspotRequest: type: object @@ -1076,6 +1325,9 @@ components: type: number format: double nullable: true + textoAlt: + type: string + nullable: true hotspots: type: array items: @@ -1117,6 +1369,9 @@ components: type: number format: double nullable: true + texto_alt: + type: string + nullable: true additionalProperties: false Hotspot: type: object @@ -1286,6 +1541,55 @@ components: type: string nullable: true additionalProperties: false + MetricasDto: + type: object + properties: + desde: + type: string + format: date + hasta: + type: string + format: date + visitas: + type: integer + format: int32 + eventos: + type: integer + format: int32 + por_tipo: + type: array + items: + $ref: '#/components/schemas/ConteoTipoDto' + nullable: true + por_dia: + type: array + items: + $ref: '#/components/schemas/VisitasDiaDto' + nullable: true + pois_mas_vistos: + type: array + items: + $ref: '#/components/schemas/PoiVistoDto' + nullable: true + additionalProperties: false + PerfilDto: + type: object + properties: + user_id: + type: string + format: uuid + correo: + type: string + nullable: true + rol: + type: string + nullable: true + verificado: + type: boolean + creado_en: + type: string + format: date-time + additionalProperties: false Poi: required: - audiencias @@ -1405,6 +1709,22 @@ components: activo: type: boolean additionalProperties: false + PoiVistoDto: + type: object + properties: + poi_id: + type: integer + format: int32 + nombre: + type: string + nullable: true + visitas: + type: integer + format: int32 + eventos: + type: integer + format: int32 + additionalProperties: false RecorridoDto: type: object properties: @@ -1419,6 +1739,28 @@ components: $ref: '#/components/schemas/HotspotDto' nullable: true additionalProperties: false + RegistrarEventoRequest: + type: object + properties: + sesionId: + type: string + format: uuid + tipo: + type: string + nullable: true + poiId: + type: integer + format: int32 + nullable: true + escenaId: + type: integer + format: int32 + nullable: true + payload: + type: object + description: Objeto JSON libre. + nullable: true + additionalProperties: false Ruta: required: - nombre @@ -1496,19 +1838,40 @@ components: - video - audio type: string + VisitasDiaDto: + type: object + properties: + dia: + type: string + format: date + visitas: + type: integer + format: int32 + eventos: + type: integer + format: int32 + additionalProperties: false securitySchemes: ClaveAdmin: type: apiKey description: Clave configurada en Admin:ApiKey. Necesaria para /api/admin/* y para subir mapas. name: X-Admin-Key in: header + TokenSupabase: + type: http + description: Token de sesión de Supabase Auth (access_token) de un usuario con rol admin en perfiles. + scheme: bearer + bearerFormat: JWT security: - ClaveAdmin: [ ] + - TokenSupabase: [ ] tags: - name: AdminEscenas - name: AdminHotspots - name: AdminLugares - name: AdminMedios + - name: AdminPanel - name: AdminPois - name: AdminRutas - name: Contenido + - name: Eventos diff --git a/scripts/datos/perfiles_eventos_auditoria.sql b/scripts/datos/perfiles_eventos_auditoria.sql new file mode 100644 index 0000000..32a06a2 --- /dev/null +++ b/scripts/datos/perfiles_eventos_auditoria.sql @@ -0,0 +1,270 @@ +-- ============================================================================= +-- Perfiles, eventos y auditoria para el panel de administracion +-- +-- Crea SOLO estas tres tablas y lo que necesitan para funcionar: +-- - el tipo rol_usuario +-- - la funcion y el trigger que crean un perfil al registrarse un usuario +-- - las funciones rol_actual() y es_admin() +-- - RLS (seguridad por filas) en las tres tablas +-- +-- Viene de supabase/migrations 0002, 0003 y 0004, adaptado a la base real: +-- - NO crea lugares, pois, escenas, medios, etc. Esas ya existen con los +-- nombres de EF ("Pois", "Escenas", "Medios"...) y las maneja la API. +-- - eventos apunta a "Pois" y "Escenas" (id entero) en vez de pois/escenas. +-- - auditoria no se engancha a las tablas de contenido: la API escribe con +-- su propio usuario de base, asi que el trigger no sabria quien hizo el +-- cambio. Llenarla le toca a la API mas adelante. +-- +-- Se puede correr dos veces sin dañar nada. Va todo en una transaccion: si +-- algo falla, no queda nada a medias. +-- ============================================================================= + +begin; + +-- ----------------------------------------------------------------------------- +-- Tipo de rol +-- ----------------------------------------------------------------------------- + +do $$ +begin + if not exists ( + select 1 from pg_type t join pg_namespace n on n.oid = t.typnamespace + where n.nspname = 'public' and t.typname = 'rol_usuario' + ) then + create type public.rol_usuario as enum ('externo', 'estudiante', 'docente', 'admin'); + end if; +end; +$$; + +create or replace function public.tocar_actualizado_en() +returns trigger +language plpgsql +as $$ +begin + new.actualizado_en := now(); + return new; +end; +$$; + +-- ----------------------------------------------------------------------------- +-- Perfiles: un perfil por cada usuario de Supabase Auth +-- ----------------------------------------------------------------------------- + +create table if not exists public.perfiles ( + user_id uuid primary key references auth.users (id) on delete cascade, + rol public.rol_usuario not null default 'externo', + verificado boolean not null default false, + rol_declarado public.rol_usuario, + creado_en timestamptz not null default now(), + actualizado_en timestamptz not null default now() +); + +comment on column public.perfiles.rol is + 'Rol efectivo. Nunca se asigna admin por dominio ni por autodeclaracion.'; + +drop trigger if exists perfiles_actualizado_en on public.perfiles; +create trigger perfiles_actualizado_en before update on public.perfiles + for each row execute function public.tocar_actualizado_en(); + +-- Al crearse un usuario en Supabase Auth, se le crea su perfil. +-- Correo @utb.edu.co empieza como estudiante; el resto, como externo. +create or replace function public.crear_perfil_para_usuario() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +declare + rol_inicial public.rol_usuario; +begin + if new.email is not null and lower(new.email) like '%@utb.edu.co' then + rol_inicial := 'estudiante'; + else + rol_inicial := 'externo'; + end if; + + insert into public.perfiles (user_id, rol) + values (new.id, rol_inicial) + on conflict (user_id) do nothing; + + return new; +end; +$$; + +drop trigger if exists al_crear_usuario on auth.users; +create trigger al_crear_usuario + after insert on auth.users + for each row execute function public.crear_perfil_para_usuario(); + +-- Usuarios que ya existian antes de este script: tambien reciben perfil. +insert into public.perfiles (user_id, rol) +select u.id, + case when lower(coalesce(u.email, '')) like '%@utb.edu.co' + then 'estudiante'::public.rol_usuario + else 'externo'::public.rol_usuario end +from auth.users u +on conflict (user_id) do nothing; + +create or replace function public.rol_actual() +returns public.rol_usuario +language sql +stable +security definer +set search_path = public +as $$ + select coalesce( + (select rol from public.perfiles where user_id = auth.uid()), + 'externo'::public.rol_usuario + ); +$$; + +create or replace function public.es_admin() +returns boolean +language sql +stable +security definer +set search_path = public +as $$ + select public.rol_actual() = 'admin'; +$$; + +-- ----------------------------------------------------------------------------- +-- Eventos de uso (para las metricas del panel) +-- ----------------------------------------------------------------------------- + +create table if not exists public.eventos ( + id bigint generated always as identity primary key, + sesion_id uuid not null, + user_id uuid references auth.users (id) on delete set null, + rol public.rol_usuario, + tipo text not null, + poi_id integer references public."Pois" ("Id") on delete set null, + escena_id integer references public."Escenas" ("Id") on delete set null, + payload jsonb not null default '{}'::jsonb, + ts timestamptz not null default now() +); + +create index if not exists eventos_ts_idx on public.eventos (ts desc); +create index if not exists eventos_tipo_idx on public.eventos (tipo, ts desc); +create index if not exists eventos_sesion_idx on public.eventos (sesion_id); + +comment on table public.eventos is + 'Retencion maxima 12 meses. La purga la ejecuta public.purgar_eventos_vencidos().'; + +create or replace function public.purgar_eventos_vencidos() +returns integer +language plpgsql +security definer +set search_path = public +as $$ +declare + borrados integer; +begin + delete from public.eventos where ts < now() - interval '12 months'; + get diagnostics borrados = row_count; + return borrados; +end; +$$; + +-- ----------------------------------------------------------------------------- +-- Auditoria (para la actividad del panel) +-- ----------------------------------------------------------------------------- + +create table if not exists public.auditoria ( + id bigint generated always as identity primary key, + actor_id uuid references auth.users (id) on delete set null, + accion text not null, + entidad text not null, + entidad_id text, + antes jsonb, + despues jsonb, + ip inet, + ts timestamptz not null default now() +); + +create index if not exists auditoria_entidad_idx on public.auditoria (entidad, entidad_id, ts desc); +create index if not exists auditoria_actor_idx on public.auditoria (actor_id, ts desc); + +create or replace function public.registrar_auditoria() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +declare + id_afectado text; +begin + id_afectado := coalesce( + to_jsonb(new) ->> 'id', + to_jsonb(old) ->> 'id', + to_jsonb(new) ->> 'user_id', + to_jsonb(old) ->> 'user_id' + ); + + insert into public.auditoria (actor_id, accion, entidad, entidad_id, antes, despues) + values ( + auth.uid(), + lower(tg_op), + tg_table_name, + id_afectado, + case when tg_op in ('UPDATE', 'DELETE') then to_jsonb(old) end, + case when tg_op in ('INSERT', 'UPDATE') then to_jsonb(new) end + ); + + return coalesce(new, old); +end; +$$; + +-- Cambiar el rol de alguien queda registrado. +drop trigger if exists auditar_perfiles on public.perfiles; +create trigger auditar_perfiles + after update on public.perfiles + for each row execute function public.registrar_auditoria(); + +-- ----------------------------------------------------------------------------- +-- RLS: por defecto nadie ve nada; cada permiso se da a proposito. +-- La API entra como dueña de las tablas y no pasa por estas reglas. +-- ----------------------------------------------------------------------------- + +alter table public.perfiles enable row level security; +alter table public.eventos enable row level security; +alter table public.auditoria enable row level security; + +grant select on public.perfiles to authenticated; +grant insert on public.eventos to anon, authenticated; +grant select on public.eventos, public.auditoria to authenticated; + +-- Cada quien ve su propio perfil; un admin ve todos. +drop policy if exists perfiles_lectura_propia on public.perfiles; +create policy perfiles_lectura_propia on public.perfiles + for select to authenticated + using (user_id = auth.uid() or public.es_admin()); + +-- Solo un admin cambia perfiles (por ejemplo, el rol de otra persona). +grant insert, update, delete on public.perfiles to authenticated; +drop policy if exists perfiles_escritura_admin on public.perfiles; +create policy perfiles_escritura_admin on public.perfiles + for all to authenticated using (public.es_admin()) with check (public.es_admin()); + +-- Cualquiera puede registrar eventos de su sesion; solo un admin los lee. +drop policy if exists eventos_emision on public.eventos; +create policy eventos_emision on public.eventos + for insert to anon, authenticated + with check (user_id is null or user_id = auth.uid()); + +drop policy if exists eventos_lectura_admin on public.eventos; +create policy eventos_lectura_admin on public.eventos + for select to authenticated using (public.es_admin()); + +-- Auditoria: solo lectura y solo para admins. No se puede editar ni borrar. +drop policy if exists auditoria_lectura_admin on public.auditoria; +create policy auditoria_lectura_admin on public.auditoria + for select to authenticated using (public.es_admin()); + +commit; + +-- Comprobacion: debe mostrar las 3 tablas. +select table_name +from information_schema.tables +where table_schema = 'public' and table_name in ('perfiles', 'eventos', 'auditoria') +order by table_name; diff --git a/services/api/Controllers/AdminPanelController.cs b/services/api/Controllers/AdminPanelController.cs new file mode 100644 index 0000000..aa5c40c --- /dev/null +++ b/services/api/Controllers/AdminPanelController.cs @@ -0,0 +1,80 @@ +using Microsoft.AspNetCore.Mvc; +using TourVirtualUTB.Api.DTOs; +using TourVirtualUTB.Api.Services; + +namespace TourVirtualUTB.Api.Controllers; + +/// +/// Lo que el panel necesita leer: POIs con inactivos, métricas, actividad y +/// administradores. Mismo portero que el resto de /api/admin. +/// +[ApiController] +[Route("api/admin")] +[RequiereClaveAdmin] +public class AdminPanelController(PanelService panel) : ControllerBase +{ + /// Todos los POI del lugar, también los inactivos. + [HttpGet("lugares/{lugarId:int}/pois")] + public async Task>> PoisConInactivos(int lugarId) + { + var pois = await panel.PoisConInactivosAsync(lugarId); + if (pois is null) return NotFound("El lugar no existe."); + return Ok(pois); + } + + /// + /// Uso del tour entre dos fechas (formato 2026-11-01, hora de Colombia, + /// ambas incluidas). Sin fechas: los últimos 30 días. + /// + [HttpGet("metricas")] + public async Task> Metricas([FromQuery] DateOnly? desde, [FromQuery] DateOnly? hasta) + { + var fin = hasta ?? PanelService.HoyEnColombia(); + var inicio = desde ?? fin.AddDays(-29); + if (inicio > fin) return BadRequest("desde no puede ser después de hasta."); + if (fin.DayNumber - inicio.DayNumber > 366) return BadRequest("El rango máximo es de un año."); + + return Ok(await panel.MetricasAsync(inicio, fin)); + } + + /// Los últimos cambios registrados, del más nuevo al más viejo. + [HttpGet("actividad")] + public async Task> Actividad( + [FromQuery] int pagina = 1, [FromQuery] int tamano = 20, [FromQuery] string? entidad = null) + { + if (pagina < 1) return BadRequest("pagina empieza en 1."); + if (tamano is < 1 or > 100) return BadRequest("tamano va de 1 a 100."); + + return Ok(await panel.ActividadAsync(pagina, tamano, entidad)); + } + + /// + /// Las personas con rol admin. Con todos=true, todos los perfiles, para + /// buscar a quién darle el rol. + /// + [HttpGet("administradores")] + public async Task>> Administradores([FromQuery] bool todos = false) => + Ok(await panel.PerfilesAsync(todos)); + + /// + /// Da o quita el rol admin (o pone otro rol). No deja quitarse el rol a + /// uno mismo ni quitar el último admin. La cuenta se crea en Supabase. + /// + [HttpPut("administradores/{userId:guid}")] + public async Task> CambiarRol(Guid userId, [FromBody] CambiarRolRequest request) + { + var rol = request.Rol?.Trim().ToLowerInvariant() ?? ""; + if (!PanelService.Roles.Contains(rol)) + return BadRequest($"rol debe ser uno de: {string.Join(", ", PanelService.Roles)}."); + + var (resultado, perfil) = await panel.CambiarRolAsync(userId, rol, + RequiereClaveAdminAttribute.UsuarioDe(HttpContext)); + return resultado switch + { + PanelService.ResultadoCambioRol.NoExiste => NotFound("Esa persona no tiene perfil. Créala primero en Supabase (Authentication > Users)."), + PanelService.ResultadoCambioRol.EsUnoMismo => Conflict("No puedes quitarte el rol de administrador a ti misma o a ti mismo."), + PanelService.ResultadoCambioRol.UltimoAdmin => Conflict("Debe quedar al menos un administrador."), + _ => Ok(perfil) + }; + } +} diff --git a/services/api/Controllers/EventosController.cs b/services/api/Controllers/EventosController.cs new file mode 100644 index 0000000..b81a2fe --- /dev/null +++ b/services/api/Controllers/EventosController.cs @@ -0,0 +1,22 @@ +using Microsoft.AspNetCore.Mvc; +using TourVirtualUTB.Api.DTOs; +using TourVirtualUTB.Api.Services; + +namespace TourVirtualUTB.Api.Controllers; + +/// +/// La app avisa aquí lo que pasa en el tour (abrir el mapa, ver una escena...). +/// Es público: no lleva clave. Con estos eventos se calculan las métricas. +/// +[ApiController] +[Route("api/eventos")] +public class EventosController(PanelService panel) : ControllerBase +{ + [HttpPost] + public async Task Registrar([FromBody] RegistrarEventoRequest request) + { + var error = await panel.RegistrarEventoAsync(request); + if (error is not null) return BadRequest(error); + return NoContent(); + } +} diff --git a/services/api/DTOs/PanelDtos.cs b/services/api/DTOs/PanelDtos.cs new file mode 100644 index 0000000..5479a91 --- /dev/null +++ b/services/api/DTOs/PanelDtos.cs @@ -0,0 +1,26 @@ +using System.Text.Json; + +namespace TourVirtualUTB.Api.DTOs; + +// --- Métricas (tabla eventos) --- +public sealed record MetricasDto(DateOnly desde, DateOnly hasta, int visitas, int eventos, + IReadOnlyList por_tipo, IReadOnlyList por_dia, + IReadOnlyList pois_mas_vistos); +public sealed record ConteoTipoDto(string tipo, int eventos); +public sealed record VisitasDiaDto(DateOnly dia, int visitas, int eventos); +public sealed record PoiVistoDto(int poi_id, string nombre, int visitas, int eventos); + +// --- Actividad (tabla auditoria) --- +public sealed record ActividadPaginaDto(int pagina, int tamano, int total, + IReadOnlyList items); +public sealed record ActividadDto(long id, DateTimeOffset ts, Guid? actor_id, string? actor_correo, + string accion, string entidad, string? entidad_id, JsonElement? antes, JsonElement? despues); + +// --- Administradores (tabla perfiles) --- +public sealed record PerfilDto(Guid user_id, string? correo, string rol, bool verificado, + DateTimeOffset creado_en); +public sealed record CambiarRolRequest(string Rol); + +// --- Registro de eventos de la app --- +public sealed record RegistrarEventoRequest(Guid SesionId, string Tipo, int? PoiId, int? EscenaId, + JsonElement? Payload); diff --git a/services/api/Data/TourDbContext.cs b/services/api/Data/TourDbContext.cs index 8f1594e..6aae51b 100644 --- a/services/api/Data/TourDbContext.cs +++ b/services/api/Data/TourDbContext.cs @@ -13,6 +13,11 @@ public class TourDbContext(DbContextOptions options) : DbContext( public DbSet Rutas => Set(); public DbSet RutaPois => Set(); + // Tablas de Supabase: existen fuera de las migraciones de EF. + public DbSet Eventos => Set(); + public DbSet Auditoria => Set(); + public DbSet UsuariosAuth => Set(); + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasIndex(x => x.Slug).IsUnique(); @@ -53,5 +58,53 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany() .HasForeignKey(x => x.PoiId) .OnDelete(DeleteBehavior.Cascade); + + ConfigurarTablasSupabase(modelBuilder); + } + + /// + /// eventos, auditoria y auth.users los crea Supabase + /// (scripts/datos/perfiles_eventos_auditoria.sql). ExcludeFromMigrations + /// hace que EF las pueda leer pero nunca intente crearlas ni cambiarlas. + /// perfiles no se mapea: su columna rol es un enum de Postgres y se lee + /// con SQL directo en PanelService. + /// + private static void ConfigurarTablasSupabase(ModelBuilder modelBuilder) + { + modelBuilder.Entity(e => + { + e.ToTable("eventos", "public", t => t.ExcludeFromMigrations()); + e.HasKey(x => x.Id); + e.Property(x => x.Id).HasColumnName("id").ValueGeneratedOnAdd(); + e.Property(x => x.SesionId).HasColumnName("sesion_id"); + e.Property(x => x.UserId).HasColumnName("user_id"); + e.Property(x => x.Tipo).HasColumnName("tipo"); + e.Property(x => x.PoiId).HasColumnName("poi_id"); + e.Property(x => x.EscenaId).HasColumnName("escena_id"); + e.Property(x => x.Payload).HasColumnName("payload").HasColumnType("jsonb"); + e.Property(x => x.Ts).HasColumnName("ts"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("auditoria", "public", t => t.ExcludeFromMigrations()); + e.HasKey(x => x.Id); + e.Property(x => x.Id).HasColumnName("id").ValueGeneratedOnAdd(); + e.Property(x => x.ActorId).HasColumnName("actor_id"); + e.Property(x => x.Accion).HasColumnName("accion"); + e.Property(x => x.Entidad).HasColumnName("entidad"); + e.Property(x => x.EntidadId).HasColumnName("entidad_id"); + e.Property(x => x.Antes).HasColumnName("antes").HasColumnType("jsonb"); + e.Property(x => x.Despues).HasColumnName("despues").HasColumnType("jsonb"); + e.Property(x => x.Ts).HasColumnName("ts"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("users", "auth", t => t.ExcludeFromMigrations()); + e.HasKey(x => x.Id); + e.Property(x => x.Id).HasColumnName("id"); + e.Property(x => x.Email).HasColumnName("email"); + }); } } diff --git a/services/api/Models/TablasSupabase.cs b/services/api/Models/TablasSupabase.cs new file mode 100644 index 0000000..37d7029 --- /dev/null +++ b/services/api/Models/TablasSupabase.cs @@ -0,0 +1,38 @@ +namespace TourVirtualUTB.Api.Models; + +// Tablas que viven en Supabase y que la API solo consulta (o, en el caso de +// eventos, solo agrega filas). Las crea scripts/datos/perfiles_eventos_auditoria.sql, +// no las migraciones de EF: en TourDbContext van con ExcludeFromMigrations. + +/// Un evento de uso que manda la app (tabla public.eventos). +public class Evento +{ + public long Id { get; set; } + public Guid SesionId { get; set; } + public Guid? UserId { get; set; } + public string Tipo { get; set; } = string.Empty; + public int? PoiId { get; set; } + public int? EscenaId { get; set; } + public string Payload { get; set; } = "{}"; + public DateTimeOffset Ts { get; set; } +} + +/// Un cambio registrado (tabla public.auditoria). +public class RegistroAuditoria +{ + public long Id { get; set; } + public Guid? ActorId { get; set; } + public string Accion { get; set; } = string.Empty; + public string Entidad { get; set; } = string.Empty; + public string? EntidadId { get; set; } + public string? Antes { get; set; } + public string? Despues { get; set; } + public DateTimeOffset Ts { get; set; } +} + +/// Usuario de Supabase Auth (tabla auth.users). Solo id y correo. +public class UsuarioAuth +{ + public Guid Id { get; set; } + public string? Email { get; set; } +} diff --git a/services/api/Program.cs b/services/api/Program.cs index c61e222..ab6d42d 100644 --- a/services/api/Program.cs +++ b/services/api/Program.cs @@ -24,6 +24,13 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => { + // Campos JSON libres (payload de eventos, antes/después de la actividad). + options.MapType(() => new OpenApiSchema + { + Type = JsonSchemaType.Object, + Description = "Objeto JSON libre." + }); + // Botón "Authorize" en Swagger para mandar la clave de administración. options.AddSecurityDefinition("ClaveAdmin", new OpenApiSecurityScheme { @@ -53,6 +60,7 @@ [new OpenApiSecuritySchemeReference("TokenSupabase", document)] = [] builder.Services.AgregarAutenticacionSupabase(builder.Configuration, builder.Environment); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); // 3. Configurar CORS (Permitir peticiones desde Flutter) builder.Services.AddCors(options => diff --git a/services/api/Services/PanelService.cs b/services/api/Services/PanelService.cs new file mode 100644 index 0000000..61342d4 --- /dev/null +++ b/services/api/Services/PanelService.cs @@ -0,0 +1,260 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using TourVirtualUTB.Api.Data; +using TourVirtualUTB.Api.DTOs; +using TourVirtualUTB.Api.Models; + +namespace TourVirtualUTB.Api.Services; + +/// +/// Lo que el panel lee de las tablas de Supabase (eventos, auditoria, +/// perfiles) y el registro de eventos que manda la app. +/// +public class PanelService(TourDbContext db) +{ + /// Los tipos de evento que acepta POST /api/eventos. + public static readonly IReadOnlySet TiposEvento = new HashSet + { + "virtual_map_open", "scene_viewed", "hotspot_tapped", "poi_media_played", "tour_completed" + }; + + public static readonly IReadOnlySet Roles = new HashSet + { + "externo", "estudiante", "docente", "admin" + }; + + // Colombia no cambia de hora: los días se cuentan en UTC-5. + private static readonly TimeSpan HoraColombia = TimeSpan.FromHours(-5); + + public static DateOnly HoyEnColombia() => + DateOnly.FromDateTime(DateTimeOffset.UtcNow.ToOffset(HoraColombia).DateTime); + + // ------------------------------------------------------------------ + // POIs, incluidos los inactivos + // ------------------------------------------------------------------ + + public async Task?> PoisConInactivosAsync(int lugarId) + { + if (!await db.Lugares.AnyAsync(l => l.Id == lugarId)) + return null; + + var pois = await db.Pois.AsNoTracking() + .Where(p => p.LugarId == lugarId) + .OrderBy(p => p.Id) + .ToListAsync(); + return pois.Select(Dto.Poi).ToList(); + } + + // ------------------------------------------------------------------ + // Métricas + // ------------------------------------------------------------------ + + private sealed class FilaResumen { public int Visitas { get; set; } public int Eventos { get; set; } } + private sealed class FilaTipo { public string Tipo { get; set; } = ""; public int Eventos { get; set; } } + private sealed class FilaDia { public DateOnly Dia { get; set; } public int Visitas { get; set; } public int Eventos { get; set; } } + private sealed class FilaPoi { public int PoiId { get; set; } public string Nombre { get; set; } = ""; public int Visitas { get; set; } public int Eventos { get; set; } } + + public async Task MetricasAsync(DateOnly desde, DateOnly hasta) + { + // [desde 00:00, hasta + 1 día 00:00) en hora de Colombia. + var inicio = new DateTimeOffset(desde.ToDateTime(TimeOnly.MinValue), HoraColombia).ToUniversalTime(); + var fin = new DateTimeOffset(hasta.AddDays(1).ToDateTime(TimeOnly.MinValue), HoraColombia).ToUniversalTime(); + + var resumen = await db.Database.SqlQuery($""" + select count(distinct sesion_id)::int as "Visitas", count(*)::int as "Eventos" + from public.eventos where ts >= {inicio} and ts < {fin} + """).SingleAsync(); + + var porTipo = await db.Database.SqlQuery($""" + select tipo as "Tipo", count(*)::int as "Eventos" + from public.eventos where ts >= {inicio} and ts < {fin} + group by tipo order by count(*) desc, tipo + """).ToListAsync(); + + var porDia = await db.Database.SqlQuery($""" + select (ts at time zone 'America/Bogota')::date as "Dia", + count(distinct sesion_id)::int as "Visitas", count(*)::int as "Eventos" + from public.eventos where ts >= {inicio} and ts < {fin} + group by 1 order by 1 + """).ToListAsync(); + + // Un evento cuenta para un POI si trae poi_id o si su escena es de ese POI. + var pois = await db.Database.SqlQuery($""" + select p."Id" as "PoiId", p."Nombre" as "Nombre", + count(distinct e.sesion_id)::int as "Visitas", count(*)::int as "Eventos" + from public.eventos e + left join public."Escenas" s on s."Id" = e.escena_id + join public."Pois" p on p."Id" = coalesce(e.poi_id, s."PoiId") + where e.ts >= {inicio} and e.ts < {fin} + group by p."Id", p."Nombre" + order by 3 desc, 4 desc, p."Id" + limit 10 + """).ToListAsync(); + + // Un día sin eventos sale con 0, para que la gráfica no tenga huecos. + var dias = porDia.ToDictionary(d => d.Dia); + var serie = new List(); + for (var dia = desde; dia <= hasta; dia = dia.AddDays(1)) + serie.Add(dias.TryGetValue(dia, out var d) + ? new VisitasDiaDto(dia, d.Visitas, d.Eventos) + : new VisitasDiaDto(dia, 0, 0)); + + return new MetricasDto(desde, hasta, resumen.Visitas, resumen.Eventos, + porTipo.Select(t => new ConteoTipoDto(t.Tipo, t.Eventos)).ToList(), + serie, + pois.Select(p => new PoiVistoDto(p.PoiId, p.Nombre, p.Visitas, p.Eventos)).ToList()); + } + + // ------------------------------------------------------------------ + // Actividad + // ------------------------------------------------------------------ + + public async Task ActividadAsync(int pagina, int tamano, string? entidad) + { + var consulta = db.Auditoria.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(entidad)) + consulta = consulta.Where(a => a.Entidad == entidad); + + var total = await consulta.CountAsync(); + var filas = await ( + from a in consulta + join u in db.UsuariosAuth on a.ActorId equals (Guid?)u.Id into usuarios + from u in usuarios.DefaultIfEmpty() + orderby a.Ts descending, a.Id descending + select new { a, Correo = u == null ? null : u.Email }) + .Skip((pagina - 1) * tamano) + .Take(tamano) + .ToListAsync(); + + var items = filas.Select(f => new ActividadDto(f.a.Id, f.a.Ts, f.a.ActorId, f.Correo, + f.a.Accion, f.a.Entidad, f.a.EntidadId, Json(f.a.Antes), Json(f.a.Despues))).ToList(); + return new ActividadPaginaDto(pagina, tamano, total, items); + } + + private static JsonElement? Json(string? texto) + { + if (texto is null) return null; + using var documento = JsonDocument.Parse(texto); + return documento.RootElement.Clone(); + } + + // ------------------------------------------------------------------ + // Administradores + // ------------------------------------------------------------------ + + private sealed class FilaPerfil + { + public Guid UserId { get; set; } + public string? Correo { get; set; } + public string Rol { get; set; } = ""; + public bool Verificado { get; set; } + public DateTimeOffset CreadoEn { get; set; } + } + + private static PerfilDto Perfil(FilaPerfil f) => new(f.UserId, f.Correo, f.Rol, f.Verificado, f.CreadoEn); + + /// Solo los admin, o todos los perfiles si . + public async Task> PerfilesAsync(bool todos) + { + var filas = await db.Database.SqlQuery($""" + select p.user_id as "UserId", u.email as "Correo", p.rol::text as "Rol", + p.verificado as "Verificado", p.creado_en as "CreadoEn" + from public.perfiles p + left join auth.users u on u.id = p.user_id + where {todos} or p.rol = 'admin' + order by u.email nulls last, p.user_id + limit 500 + """).ToListAsync(); + return filas.Select(Perfil).ToList(); + } + + public enum ResultadoCambioRol { Hecho, NoExiste, EsUnoMismo, UltimoAdmin } + + /// + /// Cambia el rol de una persona y la marca como verificada. Si quien lo + /// pide entró con token, la auditoria registra su id como actor. + /// + public async Task<(ResultadoCambioRol resultado, PerfilDto? perfil)> CambiarRolAsync( + Guid usuario, string rol, Guid? llamante) + { + await using var transaccion = await db.Database.BeginTransactionAsync(); + + var actual = await db.Database.SqlQuery($""" + select rol::text as "Value" from public.perfiles where user_id = {usuario} for update + """).FirstOrDefaultAsync(); + if (actual is null) + return (ResultadoCambioRol.NoExiste, null); + + if (actual == "admin" && rol != "admin") + { + if (llamante == usuario) + return (ResultadoCambioRol.EsUnoMismo, null); + + var admins = await db.Database.SqlQuery($""" + select count(*)::int as "Value" from public.perfiles where rol = 'admin' + """).SingleAsync(); + if (admins <= 1) + return (ResultadoCambioRol.UltimoAdmin, null); + } + + // auth.uid() lee este valor; así el trigger de auditoria sabe quién fue. + var actor = llamante?.ToString() ?? ""; + await db.Database.ExecuteSqlAsync($"select set_config('request.jwt.claim.sub', {actor}, true)"); + await db.Database.ExecuteSqlAsync($""" + update public.perfiles set rol = {rol}::public.rol_usuario, verificado = true + where user_id = {usuario} + """); + await transaccion.CommitAsync(); + + var fila = await db.Database.SqlQuery($""" + select p.user_id as "UserId", u.email as "Correo", p.rol::text as "Rol", + p.verificado as "Verificado", p.creado_en as "CreadoEn" + from public.perfiles p + left join auth.users u on u.id = p.user_id + where p.user_id = {usuario} + """).SingleAsync(); + return (ResultadoCambioRol.Hecho, Perfil(fila)); + } + + // ------------------------------------------------------------------ + // Registro de eventos + // ------------------------------------------------------------------ + + /// Null si todo está bien; si no, el motivo del rechazo. + public async Task RegistrarEventoAsync(RegistrarEventoRequest request) + { + if (request.SesionId == Guid.Empty) + return "Falta sesionId."; + if (request.Tipo is null || !TiposEvento.Contains(request.Tipo)) + return $"tipo debe ser uno de: {string.Join(", ", TiposEvento)}."; + + var payload = "{}"; + if (request.Payload is { } p && p.ValueKind != JsonValueKind.Null) + { + if (p.ValueKind != JsonValueKind.Object) + return "payload debe ser un objeto JSON."; + payload = p.GetRawText(); + if (payload.Length > 2048) + return "payload no puede pasar de 2 KB."; + } + + if (request.PoiId is int poiId && !await db.Pois.AnyAsync(x => x.Id == poiId)) + return "El poiId no existe."; + if (request.EscenaId is int escenaId && !await db.Escenas.AnyAsync(x => x.Id == escenaId)) + return "El escenaId no existe."; + + // user_id queda vacío: la app no manda sesión de Supabase y no se + // puede confiar en un id que llegue en el cuerpo. + db.Eventos.Add(new Evento + { + SesionId = request.SesionId, + Tipo = request.Tipo, + PoiId = request.PoiId, + EscenaId = request.EscenaId, + Payload = payload, + Ts = DateTimeOffset.UtcNow + }); + await db.SaveChangesAsync(); + return null; + } +} diff --git a/services/api/Services/RequiereClaveAdminAttribute.cs b/services/api/Services/RequiereClaveAdminAttribute.cs index 2f105d2..5e5789c 100644 --- a/services/api/Services/RequiereClaveAdminAttribute.cs +++ b/services/api/Services/RequiereClaveAdminAttribute.cs @@ -30,6 +30,14 @@ namespace TourVirtualUTB.Api.Services; public sealed class RequiereClaveAdminAttribute : Attribute, IAsyncAuthorizationFilter { public const string Cabecera = "X-Admin-Key"; + private const string ClaveUsuario = "UsuarioAdmin"; + + /// + /// Id del administrador que entró con token. Null si entró con la clave + /// compartida (esa clave no dice quién es la persona). + /// + public static Guid? UsuarioDe(HttpContext http) => + http.Items.TryGetValue(ClaveUsuario, out var valor) && valor is Guid id ? id : null; public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { @@ -80,6 +88,8 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) if (rol != "admin") context.Result = new ObjectResult("Tu usuario no tiene rol de administrador.") { StatusCode = StatusCodes.Status403Forbidden }; + else + http.Items[ClaveUsuario] = usuario; return; }