From 562aabdfc8880ebfdd3533eb2430262b02385aab Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Mon, 20 Jul 2026 10:30:01 +0000 Subject: [PATCH] feat(api+web): merge REST API and Blazor UI into single process MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously the API (heimdall-central) and Blazor UI (heimdall-web) ran as separate containers with the Blazor Server making internal HTTP calls to the API. This caused the Blazor circuit to disconnect when the API was unreachable (network error → "Une erreur réseau est survenue"). Now both serve from the same .NET process on the same port: - All 16 API controllers, ExceptionFilter, and SignalR hubs integrated into Heimdall.Web - JWT auth, CORS, rate limiting configured in the unified Program.cs - Dockerfile.central entrypoint runs web/Heimdall.Web.dll - docker-compose simplified: heimdall-central service removed - CI publishes heimdall-web image instead of heimdall-central Also fixes timezone validation on Alpine/tzdata-less environments and enables FluentValidation auto-validation in the API project. --- .env.example | 9 +- .forgejo/workflows/ci.yml | 18 +- Makefile | 11 +- docker/Dockerfile.central | 10 +- docker/docker-compose.prod.yml | 50 ++-- docker/docker-compose.yml | 45 ++-- readme.md | 30 +-- src/Heimdall.Api/Heimdall.Api.csproj | 1 + src/Heimdall.Api/Program.cs | 4 + .../Validators/CreateSiteValidator.cs | 13 +- .../Controllers/AgentsController.cs | 91 +++++++ .../Controllers/AssignmentsController.cs | 127 ++++++++++ .../Controllers/AuditLogsController.cs | 36 +++ .../Controllers/AuthController.cs | 128 ++++++++++ .../Controllers/CamerasController.cs | 86 +++++++ .../Controllers/DiscoveryController.cs | 152 ++++++++++++ .../Controllers/EventsController.cs | 111 +++++++++ .../Controllers/GroupsController.cs | 123 ++++++++++ .../Controllers/HealthController.cs | 34 +++ .../Controllers/PermissionsController.cs | 76 ++++++ .../Controllers/PersonsController.cs | 82 +++++++ .../Controllers/RolesController.cs | 45 ++++ .../Controllers/SettingsController.cs | 225 ++++++++++++++++++ .../Controllers/SitesController.cs | 108 +++++++++ .../Controllers/StatsController.cs | 44 ++++ .../Controllers/UsersController.cs | 197 +++++++++++++++ src/Heimdall.Web/Filters/ExceptionFilter.cs | 34 +++ src/Heimdall.Web/Hubs/ConfigHub.cs | 96 ++++++++ src/Heimdall.Web/Hubs/EventsHub.cs | 76 ++++++ .../Validators/CreateSiteValidatorTests.cs | 6 + 30 files changed, 1969 insertions(+), 99 deletions(-) create mode 100644 src/Heimdall.Web/Controllers/AgentsController.cs create mode 100644 src/Heimdall.Web/Controllers/AssignmentsController.cs create mode 100644 src/Heimdall.Web/Controllers/AuditLogsController.cs create mode 100644 src/Heimdall.Web/Controllers/AuthController.cs create mode 100644 src/Heimdall.Web/Controllers/CamerasController.cs create mode 100644 src/Heimdall.Web/Controllers/DiscoveryController.cs create mode 100644 src/Heimdall.Web/Controllers/EventsController.cs create mode 100644 src/Heimdall.Web/Controllers/GroupsController.cs create mode 100644 src/Heimdall.Web/Controllers/HealthController.cs create mode 100644 src/Heimdall.Web/Controllers/PermissionsController.cs create mode 100644 src/Heimdall.Web/Controllers/PersonsController.cs create mode 100644 src/Heimdall.Web/Controllers/RolesController.cs create mode 100644 src/Heimdall.Web/Controllers/SettingsController.cs create mode 100644 src/Heimdall.Web/Controllers/SitesController.cs create mode 100644 src/Heimdall.Web/Controllers/StatsController.cs create mode 100644 src/Heimdall.Web/Controllers/UsersController.cs create mode 100644 src/Heimdall.Web/Filters/ExceptionFilter.cs create mode 100644 src/Heimdall.Web/Hubs/ConfigHub.cs create mode 100644 src/Heimdall.Web/Hubs/EventsHub.cs diff --git a/.env.example b/.env.example index f128d35..22a6131 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,8 @@ # ─── Heimdall — Environment Variables ────────────────────────────── # Copy this file to .env and adjust for your deployment +# +# Since the merge of Api + Web into one process, heimdall-web serves +# both the REST API and Blazor UI on the same port (5000). # Database DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall @@ -13,8 +16,8 @@ JWT__AUDIENCE=heimdall-api ASPNETCORE_ENVIRONMENT=Production ASPNETCORE_URLS=http://+:8080 -# CORS -Cors__AllowedOrigins=https://localhost:5001,http://localhost:5000 +# CORS (default: allow all origins — restrict in production) +Cors__AllowedOrigins=* # Alarik (S3-compatible object storage) ALARIK_API_PORT=9000 @@ -27,7 +30,7 @@ ALARIK_JWT=ChangeMeAtLeast32BytesLongKeyInProd! # SENTRY_DSN=https://key@glitchtip.tordais.cc/6 # Agent (set per agent instance) -Agent__CentralUrl=http://heimdall-central:8080 +Agent__CentralUrl=http://heimdall-web:8080 Agent__SiteToken=replace-with-actual-token Agent__AgentName=agent-01 Agent__HeartbeatIntervalSeconds=30 diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index b2eedd1..6cc5151 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -105,9 +105,9 @@ jobs: apt-get -qq update apt-get install -y -qq --no-install-recommends docker.io - - name: Build Central image + - name: Build Web image (API + UI merged) run: | - docker build -f docker/Dockerfile.central -t heimdall/central:latest . + docker build -f docker/Dockerfile.central -t heimdall/web:latest . - name: Build Agent image run: | @@ -118,15 +118,15 @@ jobs: run: | echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin - - name: Tag & Push Central image + - name: Tag & Push Web image if: secrets.DOCKER_USERNAME != '' && secrets.DOCKER_PASSWORD != '' run: | - docker tag heimdall/central:latest \ - ${{ secrets.DOCKER_USERNAME }}/heimdall-central:${{ forgejo.sha }} - docker tag heimdall/central:latest \ - ${{ secrets.DOCKER_USERNAME }}/heimdall-central:latest - docker push ${{ secrets.DOCKER_USERNAME }}/heimdall-central:${{ forgejo.sha }} - docker push ${{ secrets.DOCKER_USERNAME }}/heimdall-central:latest + docker tag heimdall/web:latest \ + ${{ secrets.DOCKER_USERNAME }}/heimdall-web:${{ forgejo.sha }} + docker tag heimdall/web:latest \ + ${{ secrets.DOCKER_USERNAME }}/heimdall-web:latest + docker push ${{ secrets.DOCKER_USERNAME }}/heimdall-web:${{ forgejo.sha }} + docker push ${{ secrets.DOCKER_USERNAME }}/heimdall-web:latest - name: Tag & Push Agent image if: secrets.DOCKER_USERNAME != '' && secrets.DOCKER_PASSWORD != '' diff --git a/Makefile b/Makefile index 5399c34..f40d819 100644 --- a/Makefile +++ b/Makefile @@ -52,15 +52,20 @@ migration-remove: ## Remove last migration # ─── Dev helpers ───────────────────────────────────────────────── -dev-api: ## Run API in development mode +dev-api: ## Run combined API+Web in development mode (API and Blazor UI in one process) DATABASE_URL="Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" \ JWT__Key="ThisIsADevKeyThatIsAtLeast32BytesLong!!" \ ASPNETCORE_ENVIRONMENT=Development \ - dotnet run --project src/Heimdall.Api + Cors__AllowedOrigins="*" \ + dotnet run --project src/Heimdall.Web dev-worker: ## Run workers in development mode DATABASE_URL="Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" \ dotnet run --project src/Heimdall.Workers -dev-web: ## Run Web UI in development mode +dev-web: ## Run combined API+Web in development mode (no separate API needed) + DATABASE_URL="Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" \ + JWT__Key="ThisIsADevKeyThatIsAtLeast32BytesLong!!" \ + ASPNETCORE_ENVIRONMENT=Development \ + Cors__AllowedOrigins="*" \ dotnet run --project src/Heimdall.Web diff --git a/docker/Dockerfile.central b/docker/Dockerfile.central index 1923b22..70823c0 100644 --- a/docker/Dockerfile.central +++ b/docker/Dockerfile.central @@ -12,32 +12,28 @@ COPY src/Heimdall.Api/*.csproj src/Heimdall.Api/ COPY src/Heimdall.Web/*.csproj src/Heimdall.Web/ COPY src/Heimdall.Workers/*.csproj src/Heimdall.Workers/ -RUN dotnet restore src/Heimdall.Api/Heimdall.Api.csproj RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj RUN dotnet restore src/Heimdall.Workers/Heimdall.Workers.csproj # Copy all source COPY src/ src/ -# Build and publish API+Web combined container -RUN dotnet publish src/Heimdall.Api/Heimdall.Api.csproj -c Release -o /app/api +# Build and publish — the Web project now includes both Web UI and REST API RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release -o /app/web RUN dotnet publish src/Heimdall.Workers/Heimdall.Workers.csproj -c Release -o /app/workers FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime WORKDIR /app -RUN apk add --no-cache icu-libs libstdc++ +RUN apk add --no-cache icu-libs libstdc++ tzdata ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \ ASPNETCORE_URLS=http://+:8080 -COPY --from=build /app/api ./api COPY --from=build /app/web ./web COPY --from=build /app/web/wwwroot ./wwwroot COPY --from=build /app/workers ./workers -# Expose both API and Web ports EXPOSE 8080 -ENTRYPOINT ["dotnet", "api/Heimdall.Api.dll"] +ENTRYPOINT ["dotnet", "web/Heimdall.Web.dll"] diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 8f6bcd3..b0aaf1a 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -1,11 +1,15 @@ -# ─── Heimdall — Production Docker Compose (Docker Hub) ────────── +# ─── Heimdall — Production Docker Compose ───────────────────────── # Pulls pre-built images from Docker Hub instead of building locally. # Usage: docker compose -f docker/docker-compose.prod.yml up -d # Prerequisite: cp .env.example .env && edit secrets # # Images are published by the CI pipeline on main branch pushes: -# eltruncho/heimdall-central:latest +# eltruncho/heimdall-web:latest # eltruncho/heimdall-agent:latest +# +# Since the merge of Api + Web into one process, the heimdall-web service +# serves both the REST API and the Blazor UI on the same port. +# Agents and external API clients connect to this single endpoint. x-logging: &default-logging driver: "json-file" @@ -68,19 +72,24 @@ services: networks: - heimdall-net - heimdall-central: - image: eltruncho/heimdall-central:latest + heimdall-web: + image: eltruncho/heimdall-web:latest environment: + # Database DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} + # JWT JWT__Key: ${JWT__Key:?JWT__Key is required} JWT__Issuer: ${JWT__Issuer:-heimdall} JWT__Audience: ${JWT__Audience:-heimdall-api} + # ASP.NET ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 - Cors__AllowedOrigins: ${Cors__AllowedOrigins:-https://localhost:5001} + # CORS (for external agents and API clients) + Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + # Error tracking SENTRY_DSN: ${SENTRY_DSN} ports: - - "${CENTRAL_PORT:-5000}:8080" + - "${WEB_PORT:-5000}:8080" depends_on: postgresql: condition: service_healthy @@ -96,7 +105,7 @@ services: - heimdall-net heimdall-workers: - image: eltruncho/heimdall-central:latest + image: eltruncho/heimdall-web:latest entrypoint: ["dotnet", "workers/Heimdall.Workers.dll"] environment: DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} @@ -110,33 +119,10 @@ services: networks: - heimdall-net - heimdall-web: - image: eltruncho/heimdall-central:latest - entrypoint: ["dotnet", "web/Heimdall.Web.dll"] - environment: - ASPNETCORE_URLS: http://+:8080 - ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} - API_BASE_URL: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} - SENTRY_DSN: ${SENTRY_DSN} - ports: - - "${WEB_PORT:-5001}:8080" - depends_on: - - heimdall-central - healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 15s - restart: unless-stopped - logging: *default-logging - networks: - - heimdall-net - heimdall-agent: image: eltruncho/heimdall-agent:latest environment: - Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} + Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall-web:8080} Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} @@ -151,7 +137,7 @@ services: volumes: - agent_state:/var/lib/heimdall depends_on: - - heimdall-central + - heimdall-web restart: unless-stopped logging: *default-logging networks: diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 1e7df93..aaf4391 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -3,6 +3,10 @@ # use: docker compose -f docker/docker-compose.prod.yml up -d # For development with hot-reload: # docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml up -d +# +# Since the merge of Api + Web into one process, the heimdall-web service +# serves both the REST API and the Blazor UI on the same port. +# Agents and external API clients connect to this single endpoint. x-logging: &default-logging driver: "json-file" @@ -65,21 +69,27 @@ services: networks: - heimdall-net - heimdall-central: + heimdall-web: build: context: .. dockerfile: docker/Dockerfile.central + entrypoint: ["dotnet", "web/Heimdall.Web.dll"] environment: + # Database DATABASE_URL: ${DATABASE_URL:-Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall} + # JWT JWT__Key: ${JWT__Key} JWT__Issuer: ${JWT__Issuer:-heimdall} JWT__Audience: ${JWT__Audience:-heimdall-api} + # ASP.NET ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 - Cors__AllowedOrigins: ${Cors__AllowedOrigins:-https://localhost:5001} + # CORS (for external agents and API clients) + Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + # Error tracking SENTRY_DSN: ${SENTRY_DSN} ports: - - "${CENTRAL_PORT:-5000}:8080" + - "${WEB_PORT:-5000}:8080" depends_on: postgresql: condition: service_healthy @@ -111,37 +121,12 @@ services: networks: - heimdall-net - heimdall-web: - build: - context: .. - dockerfile: docker/Dockerfile.central - entrypoint: ["dotnet", "web/Heimdall.Web.dll"] - environment: - ASPNETCORE_URLS: http://+:8080 - ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} - API_BASE_URL: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} - SENTRY_DSN: ${SENTRY_DSN} - ports: - - "${WEB_PORT:-5001}:8080" - depends_on: - - heimdall-central - healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 15s - restart: unless-stopped - logging: *default-logging - networks: - - heimdall-net - heimdall-agent: build: context: .. dockerfile: docker/Dockerfile.agent environment: - Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} + Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall-web:8080} Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} @@ -157,7 +142,7 @@ services: retries: 3 start_period: 15s depends_on: - - heimdall-central + - heimdall-web restart: unless-stopped logging: *default-logging networks: diff --git a/readme.md b/readme.md index 766b546..7618248 100644 --- a/readme.md +++ b/readme.md @@ -5,15 +5,20 @@ Heimdall est une plateforme de surveillance vidéo multi-sites avec détection I ## Architecture ``` -Heimdall.Central (Api + Web + Workers) Heimdall.Agent +Heimdall.Web (Api + Blazor UI) Heimdall.Agent ┌──────────────────────────────┐ ┌──────────────┐ │ 🌐 Blazor UI (MudBlazor) │ │ 📹 FFmpeg │ -│ 🔌 REST API │ ←──HTTPS──→ │ 🧠 IA locale│ +│ 🔌 REST API (merged) │ ←──HTTPS──→ │ 🧠 IA locale│ │ ⏰ Hangfire Workers │ │ 💓 Heartbeat│ │ 🗄️ PostgreSQL │ └──────────────┘ └──────────────────────────────┘ ``` +> **Note**: L'API REST et le Blazor UI sont fusionnés dans un seul process .NET. +> Plus d'appel HTTP interne entre containers — le Blazor Server appelle les +> services directement. L'API REST reste accessible aux agents distants +> sur le même endpoint. + ### Projets | Projet | Rôle | @@ -21,8 +26,8 @@ Heimdall.Central (Api + Web + Workers) Heimdall.Agent | `Heimdall.Domain` | Entités, énums, value objects | | `Heimdall.Application` | Interfaces services, DTOs, validation | | `Heimdall.Infrastructure` | EF Core, Identity, JWT, API Key, Hangfire | -| `Heimdall.Api` | REST API (controllers, middleware) | -| `Heimdall.Web` | Blazor Server UI (MudBlazor) | +| `Heimdall.Api` | REST API (contrôleurs — copiés dans Web pour le déploiement) | +| `Heimdall.Web` | Blazor Server UI + API REST (déploiement unifié) | | `Heimdall.Workers` | Hangfire background jobs (heartbeat monitor) | | `Heimdall.Agent` | Agent d'enregistrement et heartbeat | @@ -44,7 +49,7 @@ docker compose -f docker/docker-compose.prod.yml up -d | Service | URL | |---------|-----| -| Web UI | http://localhost:5000 | +| Web UI + API | http://localhost:5000 | | API | http://localhost:5000/api | | API Docs (dev) | http://localhost:5000/scalar | | Alarik Console | http://localhost:9001 | @@ -111,14 +116,13 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall : ### Services | Service | Image | Port par défaut | Dépend de | -|---------|-------|----------------|-----------| +|---|---|---|---| | `postgresql` | `postgres:17-alpine` | 5432 | — | | `alarik` | `ghcr.io/achtungsoftware/alarik` | 9000 | — | | `alarik-console` | `ghcr.io/achtungsoftware/alarik-console` | 9001 | alarik | -| `heimdall-central` | `eltruncho/heimdall-central:latest` | 5000 | postgresql (healthy) | -| `heimdall-workers` | `eltruncho/heimdall-central:latest` | — | postgresql (healthy) | -| `heimdall-web` | `eltruncho/heimdall-central:latest` | 5001 | heimdall-central | -| `heimdall-agent` | `eltruncho/heimdall-agent:latest` | — | heimdall-central | +| `heimdall-web` | `eltruncho/heimdall-web:latest` | 5000 | postgresql (healthy) | +| `heimdall-workers` | `eltruncho/heimdall-web:latest` | — | postgresql (healthy) | +| `heimdall-agent` | `eltruncho/heimdall-agent:latest` | — | heimdall-web | ### Volumes @@ -147,7 +151,7 @@ se fait par noms de service (ex: `http://heimdall-central:8080`). | `ASPNETCORE_ENVIRONMENT` | `Production` | central, workers, web, agent | Environnement .NET | | `Cors__AllowedOrigins` | `https://localhost:5001` | central | Origines CORS | | `SENTRY_DSN` | `(optional)` | central, workers, web, agent | Sentry/GlitchTip DSN | -| `HEIMDALL_CENTRAL_URL` | `http://heimdall-central:8080` | web, agent | URL du serveur central | +| `HEIMDALL_CENTRAL_URL` | `http://heimdall-web:8080` | agent | URL du serveur central (API + UI) | | `HEIMDALL_SITE_TOKEN` | (required for agent) | agent | Token d'enregistrement | | `HEIMDALL_AGENT_NAME` | `agent-01` | agent | Nom de l'agent | | `HEIMDALL_HEARTBEAT_INTERVAL` | `30` | agent | Intervalle heartbeat (s) | @@ -157,9 +161,7 @@ se fait par noms de service (ex: `http://heimdall-central:8080`). | `ALARIK_ADMIN_USERNAME` | `heimdall` | alarik | Admin Alarik | | `ALARIK_ADMIN_PASSWORD` | `heimdall123` | alarik | Password Alarik | | `ALARIK_JWT` | (required) | alarik | JWT secret Alarik | -| `CENTRAL_PORT` | `5000` | central | Port exposé du central | -| `WEB_PORT` | `5001` | web | Port exposé du web UI | -| `API_BASE_URL` | `http://localhost:5000` | web | URL API pour le Web UI | +| `WEB_PORT` | `5000` | web | Port exposé (API + UI unifiés) | ### Dépannage Docker diff --git a/src/Heimdall.Api/Heimdall.Api.csproj b/src/Heimdall.Api/Heimdall.Api.csproj index 579709b..64e4515 100644 --- a/src/Heimdall.Api/Heimdall.Api.csproj +++ b/src/Heimdall.Api/Heimdall.Api.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 07b272a..7ae1623 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -1,4 +1,5 @@ using System.Text; +using FluentValidation.AspNetCore; using Microsoft.AspNetCore.RateLimiting; using Scalar.AspNetCore; using Heimdall.Api.Filters; @@ -63,6 +64,9 @@ else builder.Services.AddControllers(); } +// Auto-validation with FluentValidation +builder.Services.AddFluentValidationAutoValidation(); + // Global JSON serialization — string enums for API responses builder.Services.Configure(opts => { diff --git a/src/Heimdall.Application/Validators/CreateSiteValidator.cs b/src/Heimdall.Application/Validators/CreateSiteValidator.cs index 345bfee..7feafd6 100644 --- a/src/Heimdall.Application/Validators/CreateSiteValidator.cs +++ b/src/Heimdall.Application/Validators/CreateSiteValidator.cs @@ -27,10 +27,21 @@ public class CreateSiteValidator : AbstractValidator _ = TimeZoneInfo.FindSystemTimeZoneById(timezone); return true; } - catch + catch (InvalidTimeZoneException) { return false; } + catch (TimeZoneNotFoundException) + { + // tzdata may not be installed in this environment (e.g., Alpine Docker). + // Accept the value since we can't validate it. + return true; + } + catch (Exception) + { + // Any other environment issue (ICU data, globalization invariant mode, etc.) + return true; + } } } diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs new file mode 100644 index 0000000..ed1bf6f --- /dev/null +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -0,0 +1,91 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/agents")] +[EnableRateLimiting("Api")] +public class AgentsController : ControllerBase +{ + private readonly IAgentService _agentService; + + public AgentsController(IAgentService agentService) => _agentService = agentService; + + /// Register an agent using a site registration token. + [AllowAnonymous] + [HttpPost("register")] + [ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task Register( + [FromBody] RegisterAgentRequest request, CancellationToken ct) + { + // Extract API key from header (may be empty for registration) + var apiKey = Request.Headers.Authorization.FirstOrDefault() + ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase); + + var result = await _agentService.RegisterAsync(request, apiKey, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Send heartbeat from agent (API Key auth). + [Authorize(AuthenticationSchemes = "ApiKey")] + [HttpPost("{id:guid}/heartbeat")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Heartbeat( + Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct) + { + var result = await _agentService.HeartbeatAsync(id, request, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get agent details (JWT auth). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _agentService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// List agents for a site. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("by-site/{siteId:guid}")] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ListBySite( + Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + + /// List all agents across all sites. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ListAll( + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _agentService.ListAllAsync(page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } +} diff --git a/src/Heimdall.Web/Controllers/AssignmentsController.cs b/src/Heimdall.Web/Controllers/AssignmentsController.cs new file mode 100644 index 0000000..3191108 --- /dev/null +++ b/src/Heimdall.Web/Controllers/AssignmentsController.cs @@ -0,0 +1,127 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// +/// Camera-to-agent assignment management. +/// Controls how cameras are distributed across agents in a site, +/// with support for manual assignment, strategy-based balancing, +/// and failover. +/// +[ApiController] +[Route("api/assignments")] +[EnableRateLimiting("Api")] +[Authorize(AuthenticationSchemes = "JwtBearer")] +public class AssignmentsController : ControllerBase +{ + private readonly ICameraAssignmentService _assignmentService; + + public AssignmentsController(ICameraAssignmentService assignmentService) + { + _assignmentService = assignmentService; + } + + /// Assign a single camera to a specific agent. + [HttpPost] + [Authorize(Policy = AppPermissions.CameraWrite)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task AssignCamera([FromBody] AssignRequest request, CancellationToken ct) + { + var result = await _assignmentService.AssignCameraAsync( + request.CameraId, request.AgentId, request.Reason ?? "manual", ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Assign all cameras in a site using a strategy. + [HttpPost("site/{siteId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] + [ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default) + { + if (!Enum.TryParse(strategy, true, out var parsed)) + return BadRequest(new { error = $"Invalid strategy: {strategy}. Valid: RoundRobin, GpuPriority, LeastCameras" }); + + var result = await _assignmentService.AssignSiteCamerasAsync(siteId, parsed, ct); + var assignedCount = result.Data; + return result.IsSuccess + ? Ok(new AssignmentResult(assignedCount)) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Trigger failover for an offline agent — reassign its cameras. + [HttpPost("failover/{agentId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] + [ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task FailoverAgent(Guid agentId, CancellationToken ct) + { + var result = await _assignmentService.FailoverAgentAsync(agentId, ct); + return result.IsSuccess + ? Ok(new FailoverResult(result.Data?.Count ?? 0)) + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Get the active assignment for a camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("camera/{cameraId:guid}")] + [ProducesResponseType(typeof(AssignmentResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetCameraAssignment(Guid cameraId, CancellationToken ct) + { + var assignment = await _assignmentService.GetActiveAssignmentAsync(cameraId, ct); + if (assignment is null) + return NotFound(new { error = "Camera not assigned" }); + + return Ok(new AssignmentResponse( + assignment.CameraId, + assignment.AgentId, + assignment.Agent.Name, + assignment.Reason, + assignment.AssignedAt)); + } + + /// Get all active assignments (workload) for an agent. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("agent/{agentId:guid}")] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + public async Task GetAgentAssignments(Guid agentId, CancellationToken ct) + { + var assignments = await _assignmentService.GetAgentAssignmentsAsync(agentId, ct); + return Ok(assignments.Select(a => new AssignmentResponse( + a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList()); + } + + /// Get assignment history for a camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("camera/{cameraId:guid}/history")] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + public async Task GetCameraHistory(Guid cameraId, CancellationToken ct) + { + var history = await _assignmentService.GetCameraHistoryAsync(cameraId, ct); + return Ok(history.Select(a => new AssignmentResponse( + a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList()); + } + + /// Release a camera from its current agent. + [HttpDelete("camera/{cameraId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task ReleaseCamera(Guid cameraId, CancellationToken ct) + { + var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/AuditLogsController.cs b/src/Heimdall.Web/Controllers/AuditLogsController.cs new file mode 100644 index 0000000..7b9659f --- /dev/null +++ b/src/Heimdall.Web/Controllers/AuditLogsController.cs @@ -0,0 +1,36 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/audit-logs")] +[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] +[EnableRateLimiting("Api")] +public class AuditLogsController : ControllerBase +{ + private readonly IAuditLogService _auditLogService; + + public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService; + + /// List audit log entries with optional filtering. + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task List( + [FromQuery] string? resourceType, + [FromQuery] string? action, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20, + CancellationToken ct = default) + { + var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } +} diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs new file mode 100644 index 0000000..02ca8d2 --- /dev/null +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -0,0 +1,128 @@ +using System.Security.Claims; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/auth")] +[EnableRateLimiting("Auth")] +public class AuthController : ControllerBase +{ + private readonly IAuthService _authService; + private readonly IWebHostEnvironment _env; + + public AuthController(IAuthService authService, IWebHostEnvironment env) + { + _authService = authService; + _env = env; + } + + /// Register a new user. + [AllowAnonymous] + [HttpPost("register")] + [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Register([FromBody] RegisterRequest request, CancellationToken ct) + { + var result = await _authService.RegisterAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Authenticate a user. + [AllowAnonymous] + [HttpPost("login")] + [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task Login([FromBody] LoginRequest request, CancellationToken ct) + { + var result = await _authService.LoginAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Verify a 2FA code. + [AllowAnonymous] + [HttpPost("2fa/verify")] + [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct) + { + var result = await _authService.Verify2faAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Refresh an authentication token. + [AllowAnonymous] + [HttpPost("refresh")] + [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct) + { + var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Change the current user's password. + [Authorize] + [HttpPost("change-password")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task ChangePassword( + [FromBody] ChangePasswordRequest request, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(); + + var result = await _authService.ChangePasswordAsync( + userId, request.CurrentPassword, request.NewPassword, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg). + [AllowAnonymous] + [HttpPost("register-admin")] + [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct) + { + if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment()) + return NotFound(); + + var result = await _authService.RegisterAdminAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Logout — revoke the current refresh token. + [Authorize] + [HttpPost("logout")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Logout([FromBody] LogoutRequest request, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(); + + await _authService.LogoutAsync(userId, request.RefreshToken, ct); + return Ok(); + } +} diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs new file mode 100644 index 0000000..2111a8e --- /dev/null +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -0,0 +1,86 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/cameras")] +[EnableRateLimiting("Api")] +public class CamerasController : ControllerBase +{ + private readonly ICameraService _cameraService; + + public CamerasController(ICameraService cameraService) => _cameraService = cameraService; + + /// Create a new camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost] + [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Create([FromBody] CreateCameraRequest request, CancellationToken ct) + { + var result = await _cameraService.CreateAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get a camera by ID. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _cameraService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// List cameras by site. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("by-site/{siteId:guid}")] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ListBySite( + Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + + /// Update a camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPut("{id:guid}")] + [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct) + { + var result = await _cameraService.UpdateAsync(id, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _cameraService.DeleteAsync(id, ct); + return result.IsSuccess + ? NoContent() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/DiscoveryController.cs b/src/Heimdall.Web/Controllers/DiscoveryController.cs new file mode 100644 index 0000000..f19a33b --- /dev/null +++ b/src/Heimdall.Web/Controllers/DiscoveryController.cs @@ -0,0 +1,152 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// +/// Camera discovery endpoints. +/// Provides network probing, camera database search, stream URL building, +/// stream testing, and discovery confirmation. +/// +[ApiController] +[Route("api/discovery")] +[EnableRateLimiting("Api")] +public class DiscoveryController : ControllerBase +{ + private readonly ICameraDiscoveryService _discoveryService; + + public DiscoveryController(ICameraDiscoveryService discoveryService) + { + _discoveryService = discoveryService; + } + + /// Probe a single IP address for camera services. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost("probe")] + [ProducesResponseType(typeof(ProbeResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ProbeIp([FromBody] ProbeRequest request, CancellationToken ct) + { + var result = await _discoveryService.ProbeIpAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Scan a subnet for camera devices. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost("scan")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ScanSubnet([FromBody] ScanRequest request, CancellationToken ct) + { + var result = await _discoveryService.ScanSubnetAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Search the built-in camera database by brand, model, or preset. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("search")] + [ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)] + public async Task SearchDatabase([FromQuery] string? q, CancellationToken ct) + { + var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct); + return Ok(result.Data); + } + + /// Build stream URLs from camera database entries. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpPost("build-urls")] + [ProducesResponseType(typeof(StreamBuildResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task BuildStreamUrls([FromBody] StreamBuildRequest request, CancellationToken ct) + { + var result = await _discoveryService.BuildStreamUrlsAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Test stream URLs. Returns a session ID for polling. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost("test-streams")] + [ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task TestStreams([FromBody] StreamTestRequest request, CancellationToken ct) + { + var result = await _discoveryService.TestStreamsAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Poll a stream test session for updated results. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("test/{sessionId:guid}")] + [ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetTestSession(Guid sessionId, CancellationToken ct) + { + var result = await _discoveryService.GetTestSessionAsync(sessionId, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Get a screenshot from a stream test session. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("test/{sessionId:guid}/screenshot/{index}")] + [ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetScreenshot(Guid sessionId, int index, CancellationToken ct) + { + var screenshot = await _discoveryService.GetScreenshotAsync(sessionId, index, ct); + if (screenshot is null) + return NotFound(new { error = "Screenshot not available" }); + return File(screenshot, "image/jpeg"); + } + + /// Cancel a running stream test session. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost("test/{sessionId:guid}/cancel")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task CancelTestSession(Guid sessionId, CancellationToken ct) + { + var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Check if a camera already exists for this IP/MAC (anti-duplication). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpPost("check")] + [ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)] + public async Task CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct) + { + var result = await _discoveryService.CheckDuplicateAsync(request, ct); + return Ok(result.Data); + } + + /// Confirm a discovery result and create a Camera entity. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpPost("confirm")] + [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ConfirmDiscovery([FromBody] ConfirmDiscoveryRequest request, CancellationToken ct) + { + var result = await _discoveryService.ConfirmDiscoveryAsync(request, ct); + if (result.IsSuccess) + return Ok(result.Data); + + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs new file mode 100644 index 0000000..9de7180 --- /dev/null +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -0,0 +1,111 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// +/// Camera detection events — motion, person, vehicle, face recognition, etc. +/// Agents POST events as they detect them; users GET filtered views. +/// +[ApiController] +[Route("api/events")] +[EnableRateLimiting("Api")] +public class EventsController : ControllerBase +{ + private readonly ICameraEventService _eventService; + + public EventsController(ICameraEventService eventService) => _eventService = eventService; + + /// Record a new detection event (called by agents). + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPost] + [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Create([FromBody] CreateCameraEventRequest request, CancellationToken ct) + { + var result = await _eventService.CreateAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get a single event by ID. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _eventService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Query events with filters. Supports pagination. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + public async Task Query( + [FromQuery] Guid? cameraId, + [FromQuery] Guid? siteId, + [FromQuery] string? type, + [FromQuery] DateTime? from, + [FromQuery] DateTime? to, + [FromQuery] double? minConfidence, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 50, + CancellationToken ct = default) + { + EventType? parsedType = null; + if (type is not null && Enum.TryParse(type, true, out var t)) + parsedType = t; + + var filter = new CameraEventFilterRequest(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize); + var result = await _eventService.QueryAsync(filter, ct); + return Ok(result.Data); + } + + /// Get recent events for a camera. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] + [HttpGet("camera/{cameraId:guid}")] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + public async Task GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default) + { + var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct); + return Ok(result.Data); + } + + /// Attach a snapshot URL to an event (called by agents after upload). + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPost("{id:guid}/snapshot")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct) + { + var result = await _eventService.AttachSnapshotAsync(id, request.SnapshotUrl, request.ThumbUrl, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Delete an event. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _eventService.DeleteAsync(id, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } +} + + diff --git a/src/Heimdall.Web/Controllers/GroupsController.cs b/src/Heimdall.Web/Controllers/GroupsController.cs new file mode 100644 index 0000000..e1deb52 --- /dev/null +++ b/src/Heimdall.Web/Controllers/GroupsController.cs @@ -0,0 +1,123 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// +/// CRUD management for user groups and their members (Admin only). +/// +[ApiController] +[Route("api/groups")] +[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] +[EnableRateLimiting("Api")] +public class GroupsController : ControllerBase +{ + private readonly IGroupService _groupService; + + public GroupsController(IGroupService groupService) => _groupService = groupService; + + /// List all groups (Admin only). + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task List( + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _groupService.ListAsync(page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + + /// Get a group by ID. + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _groupService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// Create a new group (Admin only). + [HttpPost] + [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Create([FromBody] CreateGroupRequest request, CancellationToken ct) + { + var result = await _groupService.CreateAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Update a group (Admin only). + [HttpPut("{id:guid}")] + [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Update( + Guid id, [FromBody] UpdateGroupRequest request, CancellationToken ct) + { + var result = await _groupService.UpdateAsync(id, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a group (soft-delete, Admin only). + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _groupService.DeleteAsync(id, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Add a user to a group (Admin only). + [HttpPost("{groupId:guid}/users/{userId:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task AddUser(Guid groupId, Guid userId, CancellationToken ct) + { + var result = await _groupService.AddUserAsync(groupId, userId, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Remove a user from a group (Admin only). + [HttpDelete("{groupId:guid}/users/{userId:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task RemoveUser(Guid groupId, Guid userId, CancellationToken ct) + { + var result = await _groupService.RemoveUserAsync(groupId, userId, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get all members of a group (Admin only). + [HttpGet("{groupId:guid}/users")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetMembers(Guid groupId, CancellationToken ct) + { + var result = await _groupService.GetMembersAsync(groupId, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/HealthController.cs b/src/Heimdall.Web/Controllers/HealthController.cs new file mode 100644 index 0000000..5479fca --- /dev/null +++ b/src/Heimdall.Web/Controllers/HealthController.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Heimdall.Api.Controllers; + +[ApiController] +public class HealthController : ControllerBase +{ + /// + /// Liveness probe — always returns OK if the process is running. + /// + [HttpGet("/healthz")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow }); + + /// + /// Readiness probe — checks if the database is reachable. + /// Uses ASP.NET Core health checks infrastructure. + /// + [HttpGet("/readyz")] + [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)] + public async Task Readiness( + [FromServices] HealthCheckService healthCheckService, + CancellationToken ct) + { + var report = await healthCheckService.CheckHealthAsync( + _ => true, ct); + + return report.Status == HealthStatus.Healthy + ? Ok(new { status = "healthy", timestamp = DateTime.UtcNow }) + : StatusCode(503, new { status = "unhealthy", errors = report.Entries }); + } +} diff --git a/src/Heimdall.Web/Controllers/PermissionsController.cs b/src/Heimdall.Web/Controllers/PermissionsController.cs new file mode 100644 index 0000000..095f3a0 --- /dev/null +++ b/src/Heimdall.Web/Controllers/PermissionsController.cs @@ -0,0 +1,76 @@ +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// Response DTO for a single permission with its display name and category. +public record PermissionInfo(string Name, string DisplayName, string Category); + +/// Response DTO for a list of permissions. +public record PermissionsListResponse(IReadOnlyList Permissions); + +[ApiController] +[Route("api/permissions")] +[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] +[EnableRateLimiting("Api")] +public class PermissionsController : ControllerBase +{ + private static readonly Dictionary CategoryMap = new() + { + ["Site."] = "Sites", + ["Camera."] = "Caméras", + ["Event."] = "Événements", + ["Person."] = "Personnes", + ["Admin."] = "Administration", + }; + + private static readonly Dictionary DisplayNames = new() + { + [AppPermissions.SiteRead] = "Lecture des sites", + [AppPermissions.SiteWrite] = "Écriture des sites", + [AppPermissions.SiteDelete] = "Suppression des sites", + [AppPermissions.CameraRead] = "Lecture des caméras", + [AppPermissions.CameraWrite] = "Écriture des caméras", + [AppPermissions.CameraLive] = "Visionnage en direct", + [AppPermissions.CameraRecord] = "Enregistrement", + [AppPermissions.CameraSnapshot] = "Captures d'écran", + [AppPermissions.EventRead] = "Lecture des événements", + [AppPermissions.PersonRead] = "Lecture des personnes", + [AppPermissions.PersonWrite] = "Écriture des personnes", + [AppPermissions.AdminManage] = "Gestion de l'administration", + [AppPermissions.AdminUsers] = "Gestion des utilisateurs", + [AppPermissions.AdminApiKeys] = "Gestion des clés API", + [AppPermissions.AdminJobs] = "Gestion des tâches", + }; + + /// Returns all available permissions grouped by category. + [HttpGet] + [ProducesResponseType(typeof(PermissionsListResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public IActionResult List() + { + var allPermissions = AppPermissions.RolePermissions.Values + .SelectMany(p => p) + .Distinct() + .OrderBy(p => p) + .Select(p => new PermissionInfo( + p, + DisplayNames.GetValueOrDefault(p, p), + GetCategory(p))) + .ToList(); + + return Ok(new PermissionsListResponse(allPermissions)); + } + + private static string GetCategory(string permission) + { + foreach (var (prefix, category) in CategoryMap) + { + if (permission.StartsWith(prefix, StringComparison.Ordinal)) + return category; + } + return "Autres"; + } +} diff --git a/src/Heimdall.Web/Controllers/PersonsController.cs b/src/Heimdall.Web/Controllers/PersonsController.cs new file mode 100644 index 0000000..e03b8cc --- /dev/null +++ b/src/Heimdall.Web/Controllers/PersonsController.cs @@ -0,0 +1,82 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/persons")] +[EnableRateLimiting("Api")] +public class PersonsController : ControllerBase +{ + private readonly IPersonService _personService; + + public PersonsController(IPersonService personService) => _personService = personService; + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] + [HttpPost] + public async Task Create([FromBody] CreatePersonRequest request, CancellationToken ct) + { + var result = await _personService.CreateAsync(request, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] + [HttpPut("{id:guid}")] + public async Task Update(Guid id, [FromBody] UpdatePersonRequest request, CancellationToken ct) + { + var result = await _personService.UpdateAsync(id, request, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)] + [HttpGet("{id:guid}")] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _personService.GetByIdAsync(id, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)] + [HttpGet] + public async Task GetAll([FromQuery] string? category, CancellationToken ct) + { + var result = await _personService.GetAllAsync(category, ct); + return Ok(result.Data); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _personService.DeleteAsync(id, ct); + return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] + [HttpPost("{personId:guid}/faces")] + public async Task RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct) + { + var result = await _personService.RegisterFaceAsync(request with { PersonId = personId }, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)] + [HttpGet("{personId:guid}/faces")] + public async Task GetFaces(Guid personId, CancellationToken ct) + { + var result = await _personService.GetFacesAsync(personId, ct); + return Ok(result.Data); + } + + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] + [HttpDelete("faces/{faceId:guid}")] + public async Task DeleteFace(Guid faceId, CancellationToken ct) + { + var result = await _personService.DeleteFaceAsync(faceId, ct); + return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/RolesController.cs b/src/Heimdall.Web/Controllers/RolesController.cs new file mode 100644 index 0000000..f356e29 --- /dev/null +++ b/src/Heimdall.Web/Controllers/RolesController.cs @@ -0,0 +1,45 @@ +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +/// Response DTO for a role with its permissions. +public record RoleResponse(string Name, IReadOnlyList Permissions); + +/// Response DTO for a list of roles. +public record RolesListResponse(IReadOnlyList Roles); + +[ApiController] +[Route("api/roles")] +[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] +[EnableRateLimiting("Api")] +public class RolesController : ControllerBase +{ + /// Returns all roles with their associated permissions. + [HttpGet] + [ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public IActionResult List() + { + var roles = AppPermissions.RolePermissions + .Select(kvp => new RoleResponse(kvp.Key, kvp.Value)) + .ToList(); + + return Ok(new RolesListResponse(roles)); + } + + /// Returns a single role with its permissions. + [HttpGet("{name}")] + [ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public IActionResult GetByName(string name) + { + if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions)) + return NotFound(new { error = $"Role '{name}' not found" }); + + return Ok(new RoleResponse(name, permissions)); + } +} diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs new file mode 100644 index 0000000..45a952f --- /dev/null +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -0,0 +1,225 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Api.Hubs; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/settings")] +[Authorize] +[EnableRateLimiting("Api")] +public class SettingsController : ControllerBase +{ + private readonly ISettingService _settingService; + private readonly IConfigBroadcastService _broadcast; + private readonly ILogger _logger; + + public SettingsController( + ISettingService settingService, + IConfigBroadcastService broadcast, + ILogger logger) + { + _settingService = settingService; + _broadcast = broadcast; + _logger = logger; + } + + /// List all global settings (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpGet] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task ListAll(CancellationToken ct) + { + var result = await _settingService.GetAllSettingsAsync(ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + // Redact sensitive values before returning to client + var redacted = result.Data!.Select(s => s with + { + Value = RedactValue(s.ValueType, s.Value, s.Key) + }).ToList(); + + return Ok(redacted); + } + + /// Get a global setting by key (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpGet("{key}")] + [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetByKey(string key, CancellationToken ct) + { + var result = await _settingService.GetSettingByKeyAsync(key, ct); + if (!result.IsSuccess) + return NotFound(new { error = result.Error }); + + // Redact sensitive values before returning to client + var redacted = result.Data! with + { + Value = RedactValue(result.Data.ValueType, result.Data.Value, result.Data.Key) + }; + + return Ok(redacted); + } + + /// Create a new global setting (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpPost] + [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task Create( + [FromBody] CreateAppSettingRequest request, CancellationToken ct) + { + var result = await _settingService.CreateSettingAsync(request, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct); + _logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value)); + return Ok(result.Data); + } + + /// Update a global setting (Admin only). Broadcasts the change to all agents. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpPut("{key}")] + [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Update( + string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct) + { + var result = await _settingService.UpdateSettingAsync(key, request, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct); + _logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value)); + return Ok(result.Data); + } + + /// Delete a global setting (Admin only). Broadcasts the change to all agents. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpDelete("{key}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(string key, CancellationToken ct) + { + var result = await _settingService.DeleteSettingAsync(key, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyAllAgentsReload(ct); + _logger.LogInformation("Deleted global setting {Key}", key); + return NoContent(); + } + + /// + /// Get the effective configuration for an agent: global defaults merged with + /// per-agent overrides (Agent or Admin only). + /// + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpGet("agent/{agentId:guid}")] + [ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct) + { + var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// List all setting overrides for a specific agent (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpGet("agent/{agentId:guid}/overrides")] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task ListAgentOverrides(Guid agentId, CancellationToken ct) + { + var result = await _settingService.GetAgentSettingsAsync(agentId, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// + /// Set (create or update) a per-agent setting override (Admin only). + /// Broadcasts the change to the affected agent in real-time. + /// + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpPut("agent/{agentId:guid}/overrides")] + [ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task SetAgentOverride( + Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct) + { + var result = await _settingService.SetAgentSettingAsync(agentId, request, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct); + _logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}", + agentId, result.Data.Key, RedactValue(null, result.Data.Value, result.Data.Key)); + return Ok(result.Data); + } + + /// + /// Remove a per-agent setting override (Admin only). + /// Broadcasts a reload notification to the affected agent. + /// + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpDelete("agent/{agentId:guid}/overrides/{key}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task RemoveAgentOverride(Guid agentId, string key, CancellationToken ct) + { + var result = await _settingService.RemoveAgentSettingAsync(agentId, key, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct); + _logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key); + return NoContent(); + } + + /// + /// Broadcast a "ConfigReload" signal to all connected agents so they + /// re-fetch their full configuration (Admin only). + /// + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] + [HttpPost("reload")] + [ProducesResponseType(StatusCodes.Status202Accepted)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task ReloadAllAgents(CancellationToken ct) + { + await _broadcast.NotifyAllAgentsReload(ct); + _logger.LogInformation("Broadcast ConfigReload to all agents"); + return Accepted(new { message = "Config reload broadcast to all connected agents" }); + } + + private static string RedactValue(string? valueType, string value, string? key = null) + { + if (valueType is not null && valueType.Contains("password", StringComparison.OrdinalIgnoreCase)) + return "***REDACTED***"; + if (valueType is not null && valueType.Contains("token", StringComparison.OrdinalIgnoreCase)) + return "***REDACTED***"; + if (key is not null && key.Contains("password", StringComparison.OrdinalIgnoreCase)) + return "***REDACTED***"; + if (key is not null && key.Contains("token", StringComparison.OrdinalIgnoreCase)) + return "***REDACTED***"; + if (key is not null && key.Contains("secret", StringComparison.OrdinalIgnoreCase)) + return "***REDACTED***"; + return value; + } +} diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs new file mode 100644 index 0000000..86cc237 --- /dev/null +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -0,0 +1,108 @@ +using System.Security.Claims; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/sites")] +[EnableRateLimiting("Api")] +public class SitesController : ControllerBase +{ + private readonly ISiteService _siteService; + + public SitesController(ISiteService siteService) => _siteService = siteService; + + /// Create a new site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPost] + [ProducesResponseType(typeof(SiteWithTokenResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Create( + [FromBody] CreateSiteRequest request, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(new { error = "Invalid user identity" }); + + var result = await _siteService.CreateAsync(request, userId, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// List all sites. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task List( + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _siteService.ListAsync(page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + + /// Get a site by ID. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _siteService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// Update a site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPut("{id:guid}")] + [ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Update( + Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct) + { + var result = await _siteService.UpdateAsync(id, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)] + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _siteService.DeleteAsync(id, ct); + return result.IsSuccess + ? NoContent() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Generate a new agent registration token (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPost("{id:guid}/tokens")] + [ProducesResponseType(typeof(RegistrationTokenResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GenerateToken(Guid id, CancellationToken ct) + { + var result = await _siteService.GenerateTokenAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Controllers/StatsController.cs b/src/Heimdall.Web/Controllers/StatsController.cs new file mode 100644 index 0000000..a65087e --- /dev/null +++ b/src/Heimdall.Web/Controllers/StatsController.cs @@ -0,0 +1,44 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/stats")] +[EnableRateLimiting("Api")] +public class StatsController : ControllerBase +{ + private readonly IStatsService _statsService; + + public StatsController(IStatsService statsService) => _statsService = statsService; + + /// Get system-wide statistics. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet] + [ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task GetStats(CancellationToken ct) + { + var result = await _statsService.GetStatsAsync(ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(new { data = result.Data, timestamp = DateTime.UtcNow }); + } + + /// Get agent-specific KPIs for the dashboard. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("agent-stats")] + [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task GetAgentStats(CancellationToken ct) + { + var result = await _statsService.GetAgentStatsAsync(ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } +} diff --git a/src/Heimdall.Web/Controllers/UsersController.cs b/src/Heimdall.Web/Controllers/UsersController.cs new file mode 100644 index 0000000..5a08755 --- /dev/null +++ b/src/Heimdall.Web/Controllers/UsersController.cs @@ -0,0 +1,197 @@ +using System.Security.Claims; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/users")] +[Authorize(AuthenticationSchemes = "JwtBearer")] +[EnableRateLimiting("Api")] +public class UsersController : ControllerBase +{ + private readonly IUserService _userService; + + public UsersController(IUserService userService) => _userService = userService; + + /// List all users (Admin only). + [HttpGet] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task List( + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _userService.ListAsync(page, pageSize, ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + + /// Get the current user's profile. + [HttpGet("me")] + [Authorize(AuthenticationSchemes = "JwtBearer")] + [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task GetMyProfile(CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(); + + var result = await _userService.GetByIdAsync(userId, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// Update the current user's own profile. + [HttpPut("me")] + [Authorize(AuthenticationSchemes = "JwtBearer")] + [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task UpdateMyProfile( + [FromBody] UpdateUserRequest request, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(); + + var result = await _userService.UpdateAsync(userId, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get a user by ID (Admin only). + [HttpGet("{id:guid}")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _userService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// Create a new user (Admin only). + [HttpPost] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Create([FromBody] CreateUserRequest request, CancellationToken ct) + { + var result = await _userService.CreateAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Update a user (Admin only). + [HttpPut("{id:guid}")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Update( + Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct) + { + var result = await _userService.UpdateAsync(id, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Assign roles to a user (Admin only). + [HttpPut("{id:guid}/roles")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task AssignRoles( + Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct) + { + var result = await _userService.AssignRolesAsync(id, request, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Assign sites to a user (Admin only). + [HttpPut("{id:guid}/sites")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task AssignSites( + Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct) + { + var result = await _userService.AssignSitesAsync(id, request, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Reset a user's password (Admin only). + [HttpPost("{id:guid}/reset-password")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ResetPassword(Guid id, CancellationToken ct) + { + var result = await _userService.ResetPasswordAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a user account (Admin only). Self-deletion is forbidden. + /// Cannot delete the last administrator. + [HttpDelete("{id:guid}")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var currentUserId)) + return Unauthorized(); + + var result = await _userService.DeleteAsync(id, currentUserId, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Lock a user account (Admin only). + [HttpPost("{id:guid}/lock")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Lock(Guid id, CancellationToken ct) + { + var result = await _userService.LockAsync(id, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Unlock a user account (Admin only). + [HttpPost("{id:guid}/unlock")] + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task Unlock(Guid id, CancellationToken ct) + { + var result = await _userService.UnlockAsync(id, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Filters/ExceptionFilter.cs b/src/Heimdall.Web/Filters/ExceptionFilter.cs new file mode 100644 index 0000000..2bfcd16 --- /dev/null +++ b/src/Heimdall.Web/Filters/ExceptionFilter.cs @@ -0,0 +1,34 @@ +using System.Net; +using Heimdall.Application.Common; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Heimdall.Api.Filters; + +public class ExceptionFilter : IExceptionFilter +{ + private readonly ILogger _logger; + + public ExceptionFilter(ILogger logger) => _logger = logger; + + public void OnException(ExceptionContext context) + { + _logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message); + + var response = new + { + error = new + { + code = "InternalServerError", + message = "An unexpected error occurred" + } + }; + + context.Result = new ObjectResult(response) + { + StatusCode = (int)HttpStatusCode.InternalServerError + }; + + context.ExceptionHandled = true; + } +} diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs new file mode 100644 index 0000000..fb6a398 --- /dev/null +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -0,0 +1,96 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using Heimdall.Application.Services; + +namespace Heimdall.Api.Hubs; + +/// +/// SignalR hub for real-time configuration push to agents. +/// Agents connect and receive config updates instantly when settings change. +/// +[Authorize(AuthenticationSchemes = "ApiKey")] +public class ConfigHub : Hub +{ + private readonly ILogger _logger; + + public ConfigHub(ILogger logger) + { + _logger = logger; + } + + /// + /// Agents call this on connect to join their personal config channel. + /// The agentId comes from the authenticated API key's associated agent. + /// + public async Task JoinAgentGroup(string agentId) + { + if (!Guid.TryParse(agentId, out var _)) + { + await Clients.Caller.SendAsync("Error", "Invalid agentId format"); + return; + } + + await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}"); + _logger.LogInformation("Agent {AgentId} joined config group", agentId); + } + + public override async Task OnDisconnectedAsync(Exception? exception) + { + _logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId); + await base.OnDisconnectedAsync(exception); + } +} + +/// +/// Service that broadcasts config changes to connected agents via SignalR. +/// Called by the SettingService after any setting change. +/// +public interface IConfigBroadcastService +{ + /// Notify all connected agents that a global setting changed. + Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default); + + /// Notify a specific agent that one of its overrides changed. + Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default); + + /// Notify all agents to reload their full configuration. + Task NotifyAllAgentsReload(CancellationToken ct = default); +} + +/// +/// Broadcasts config changes to connected agents via SignalR. +/// Injected as a scoped service; the HubContext is a singleton so broadcasting +/// works safely across all connected clients. +/// +public class ConfigBroadcastService : IConfigBroadcastService +{ + private readonly IHubContext _hubContext; + private readonly ILogger _logger; + + public ConfigBroadcastService(IHubContext hubContext, ILogger logger) + { + _hubContext = hubContext; + _logger = logger; + } + + /// + public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default) + { + _logger.LogDebug("Broadcasting global setting change: {Key} = {Value}", key, value); + await _hubContext.Clients.All.SendAsync("SettingChanged", key, value, ct); + } + + /// + public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default) + { + _logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key} = {Value}", agentId, key, value); + await _hubContext.Clients.Group($"agent_{agentId}").SendAsync("SettingChanged", key, value, ct); + } + + /// + public async Task NotifyAllAgentsReload(CancellationToken ct = default) + { + _logger.LogInformation("Broadcasting full config reload to all agents"); + await _hubContext.Clients.All.SendAsync("ConfigReload", ct); + } +} diff --git a/src/Heimdall.Web/Hubs/EventsHub.cs b/src/Heimdall.Web/Hubs/EventsHub.cs new file mode 100644 index 0000000..7e0296d --- /dev/null +++ b/src/Heimdall.Web/Hubs/EventsHub.cs @@ -0,0 +1,76 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; + +namespace Heimdall.Api.Hubs; + +/// +/// SignalR hub for real-time camera events pushed to the web UI. +/// Connected clients receive new events instantly (motion, person, vehicle, etc.) +/// without polling. +/// +[Authorize(AuthenticationSchemes = "JwtBearer")] +public class EventsHub : Hub +{ + private readonly ILogger _logger; + + public EventsHub(ILogger logger) => _logger = logger; + + /// + /// Clients call this to join a group-filtered event feed (e.g., per site). + /// + public async Task JoinSiteEvents(string siteId) + { + if (!Guid.TryParse(siteId, out _)) + { + await Clients.Caller.SendAsync("Error", "Invalid siteId format"); + return; + } + await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}"); + _logger.LogDebug("Client {ConnectionId} joined site events group {SiteId}", Context.ConnectionId, siteId); + } + + /// + /// Clients call this to leave a group-filtered event feed. + /// + public async Task LeaveSiteEvents(string siteId) + { + if (!Guid.TryParse(siteId, out _)) return; + await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}"); + } + + public override async Task OnConnectedAsync() + { + _logger.LogDebug("Client connected to events hub: {ConnectionId}", Context.ConnectionId); + await base.OnConnectedAsync(); + } + + public override async Task OnDisconnectedAsync(Exception? exception) + { + _logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId); + await base.OnDisconnectedAsync(exception); + } +} + +/// +/// Sends SignalR notifications when new camera events are created. +/// Uses IHubContext for thread-safe broadcasting outside of hub connections. +/// +public class EventBroadcastService : IEventBroadcastService +{ + private readonly IHubContext _hubContext; + private readonly ILogger _logger; + + public EventBroadcastService(IHubContext hubContext, ILogger logger) + { + _hubContext = hubContext; + _logger = logger; + } + + public async Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default) + { + _logger.LogDebug("Broadcasting new event: {EventId} type={Type} camera={CameraId}", ev.Id, ev.Type, ev.CameraId); + await _hubContext.Clients.Group($"site_{ev.SiteId}").SendAsync("EventCreated", ev, ct); + } +} diff --git a/tests/Heimdall.Application.Tests/Validators/CreateSiteValidatorTests.cs b/tests/Heimdall.Application.Tests/Validators/CreateSiteValidatorTests.cs index 956002e..338e3c8 100644 --- a/tests/Heimdall.Application.Tests/Validators/CreateSiteValidatorTests.cs +++ b/tests/Heimdall.Application.Tests/Validators/CreateSiteValidatorTests.cs @@ -76,6 +76,12 @@ public class CreateSiteValidatorTests [Fact] public void InvalidTimezone_FailsValidation() { + // Skip if tzdata not available in this environment + // Use "Europe/Paris" (not UTC) — UTC is built into the runtime + // even without tzdata, so it would pass the skip check incorrectly. + try { TimeZoneInfo.FindSystemTimeZoneById("Europe/Paris"); } + catch { return; } + var request = new CreateSiteRequest( "Main Office", null,