feat(api+web): merge REST API and Blazor UI into single process
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.
This commit is contained in:
1 parent
892ca88de8
commit
562aabdfc8
30 files changed
+1969
-99
No files matched your search
+6
-3
@@ -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
|
||||
|
||||
@@ -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 != ''
|
||||
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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:
|
||||
|
||||
+15
-30
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
|
||||
|
||||
@@ -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<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
|
||||
{
|
||||
|
||||
@@ -27,10 +27,21 @@ public class CreateSiteValidator : AbstractValidator<CreateSiteRequest>
|
||||
_ = 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Register an agent using a site registration token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Send heartbeat from agent (API Key auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpPost("{id:guid}/heartbeat")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get agent details (JWT auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _agentService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List agents for a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("by-site/{siteId:guid}")]
|
||||
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>List all agents across all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/assignments")]
|
||||
[EnableRateLimiting("Api")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
public class AssignmentsController : ControllerBase
|
||||
{
|
||||
private readonly ICameraAssignmentService _assignmentService;
|
||||
|
||||
public AssignmentsController(ICameraAssignmentService assignmentService)
|
||||
{
|
||||
_assignmentService = assignmentService;
|
||||
}
|
||||
|
||||
/// <summary>Assign a single camera to a specific agent.</summary>
|
||||
[HttpPost]
|
||||
[Authorize(Policy = AppPermissions.CameraWrite)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Assign all cameras in a site using a strategy.</summary>
|
||||
[HttpPost("site/{siteId:guid}")]
|
||||
[Authorize(Policy = AppPermissions.CameraWrite)]
|
||||
[ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default)
|
||||
{
|
||||
if (!Enum.TryParse<AssignmentStrategy>(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 });
|
||||
}
|
||||
|
||||
/// <summary>Trigger failover for an offline agent — reassign its cameras.</summary>
|
||||
[HttpPost("failover/{agentId:guid}")]
|
||||
[Authorize(Policy = AppPermissions.CameraWrite)]
|
||||
[ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get the active assignment for a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("camera/{cameraId:guid}")]
|
||||
[ProducesResponseType(typeof(AssignmentResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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));
|
||||
}
|
||||
|
||||
/// <summary>Get all active assignments (workload) for an agent.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("agent/{agentId:guid}")]
|
||||
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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());
|
||||
}
|
||||
|
||||
/// <summary>Get assignment history for a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("camera/{cameraId:guid}/history")]
|
||||
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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());
|
||||
}
|
||||
|
||||
/// <summary>Release a camera from its current agent.</summary>
|
||||
[HttpDelete("camera/{cameraId:guid}")]
|
||||
[Authorize(Policy = AppPermissions.CameraWrite)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ReleaseCamera(Guid cameraId, CancellationToken ct)
|
||||
{
|
||||
var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>List audit log entries with optional filtering.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<AuditLogResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>Register a new user.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Authenticate a user.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Verify a 2FA code.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("2fa/verify")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Refresh an authentication token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("refresh")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Change the current user's password.</summary>
|
||||
[Authorize]
|
||||
[HttpPost("change-password")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Logout — revoke the current refresh token.</summary>
|
||||
[Authorize]
|
||||
[HttpPost("logout")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Create a new camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get a camera by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List cameras by site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("by-site/{siteId:guid}")]
|
||||
[ProducesResponseType(typeof(PagedResult<CameraResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Update a camera.</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera.</summary>
|
||||
[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<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Camera discovery endpoints.
|
||||
/// Provides network probing, camera database search, stream URL building,
|
||||
/// stream testing, and discovery confirmation.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/discovery")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class DiscoveryController : ControllerBase
|
||||
{
|
||||
private readonly ICameraDiscoveryService _discoveryService;
|
||||
|
||||
public DiscoveryController(ICameraDiscoveryService discoveryService)
|
||||
{
|
||||
_discoveryService = discoveryService;
|
||||
}
|
||||
|
||||
/// <summary>Probe a single IP address for camera services.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("probe")]
|
||||
[ProducesResponseType(typeof(ProbeResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Scan a subnet for camera devices.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("scan")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<ProbeResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Search the built-in camera database by brand, model, or preset.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("search")]
|
||||
[ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> SearchDatabase([FromQuery] string? q, CancellationToken ct)
|
||||
{
|
||||
var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Build stream URLs from camera database entries.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpPost("build-urls")]
|
||||
[ProducesResponseType(typeof(StreamBuildResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Test stream URLs. Returns a session ID for polling.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("test-streams")]
|
||||
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Poll a stream test session for updated results.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("test/{sessionId:guid}")]
|
||||
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get a screenshot from a stream test session.</summary>
|
||||
[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<IActionResult> 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");
|
||||
}
|
||||
|
||||
/// <summary>Cancel a running stream test session.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("test/{sessionId:guid}/cancel")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> CancelTestSession(Guid sessionId, CancellationToken ct)
|
||||
{
|
||||
var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Check if a camera already exists for this IP/MAC (anti-duplication).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpPost("check")]
|
||||
[ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _discoveryService.CheckDuplicateAsync(request, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Confirm a discovery result and create a Camera entity.</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Camera detection events — motion, person, vehicle, face recognition, etc.
|
||||
/// Agents POST events as they detect them; users GET filtered views.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/events")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class EventsController : ControllerBase
|
||||
{
|
||||
private readonly ICameraEventService _eventService;
|
||||
|
||||
public EventsController(ICameraEventService eventService) => _eventService = eventService;
|
||||
|
||||
/// <summary>Record a new detection event (called by agents).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get a single event by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Query events with filters. Supports pagination.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<CameraEventResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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<EventType>(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);
|
||||
}
|
||||
|
||||
/// <summary>Get recent events for a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("camera/{cameraId:guid}")]
|
||||
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Attach a snapshot URL to an event (called by agents after upload).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{id:guid}/snapshot")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Delete an event.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _eventService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// CRUD management for user groups and their members (Admin only).
|
||||
/// </summary>
|
||||
[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;
|
||||
|
||||
/// <summary>List all groups (Admin only).</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<GroupResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Get a group by ID.</summary>
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _groupService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Create a new group (Admin only).</summary>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Update a group (Admin only).</summary>
|
||||
[HttpPut("{id:guid}")]
|
||||
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Delete a group (soft-delete, Admin only).</summary>
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _groupService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Add a user to a group (Admin only).</summary>
|
||||
[HttpPost("{groupId:guid}/users/{userId:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Remove a user from a group (Admin only).</summary>
|
||||
[HttpDelete("{groupId:guid}/users/{userId:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get all members of a group (Admin only).</summary>
|
||||
[HttpGet("{groupId:guid}/users")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<GroupMemberResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
public class HealthController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Liveness probe — always returns OK if the process is running.
|
||||
/// </summary>
|
||||
[HttpGet("/healthz")]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
||||
|
||||
/// <summary>
|
||||
/// Readiness probe — checks if the database is reachable.
|
||||
/// Uses ASP.NET Core health checks infrastructure.
|
||||
/// </summary>
|
||||
[HttpGet("/readyz")]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
/// <summary>Response DTO for a single permission with its display name and category.</summary>
|
||||
public record PermissionInfo(string Name, string DisplayName, string Category);
|
||||
|
||||
/// <summary>Response DTO for a list of permissions.</summary>
|
||||
public record PermissionsListResponse(IReadOnlyList<PermissionInfo> Permissions);
|
||||
|
||||
[ApiController]
|
||||
[Route("api/permissions")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class PermissionsController : ControllerBase
|
||||
{
|
||||
private static readonly Dictionary<string, string> CategoryMap = new()
|
||||
{
|
||||
["Site."] = "Sites",
|
||||
["Camera."] = "Caméras",
|
||||
["Event."] = "Événements",
|
||||
["Person."] = "Personnes",
|
||||
["Admin."] = "Administration",
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, string> 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",
|
||||
};
|
||||
|
||||
/// <summary>Returns all available permissions grouped by category.</summary>
|
||||
[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";
|
||||
}
|
||||
}
|
||||
@@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> DeleteFace(Guid faceId, CancellationToken ct)
|
||||
{
|
||||
var result = await _personService.DeleteFaceAsync(faceId, ct);
|
||||
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
/// <summary>Response DTO for a role with its permissions.</summary>
|
||||
public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>Response DTO for a list of roles.</summary>
|
||||
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
|
||||
|
||||
[ApiController]
|
||||
[Route("api/roles")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class RolesController : ControllerBase
|
||||
{
|
||||
/// <summary>Returns all roles with their associated permissions.</summary>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>Returns a single role with its permissions.</summary>
|
||||
[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));
|
||||
}
|
||||
}
|
||||
@@ -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<SettingsController> _logger;
|
||||
|
||||
public SettingsController(
|
||||
ISettingService settingService,
|
||||
IConfigBroadcastService broadcast,
|
||||
ILogger<SettingsController> logger)
|
||||
{
|
||||
_settingService = settingService;
|
||||
_broadcast = broadcast;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>List all global settings (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(List<AppSettingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Get a global setting by key (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("{key}")]
|
||||
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Create a new global setting (Admin only).</summary>
|
||||
[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<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Update a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
||||
[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<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Delete a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpDelete("{key}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the effective configuration for an agent: global defaults merged with
|
||||
/// per-agent overrides (Agent or Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("agent/{agentId:guid}")]
|
||||
[ProducesResponseType(typeof(Dictionary<string, string>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("agent/{agentId:guid}/overrides")]
|
||||
[ProducesResponseType(typeof(List<AgentSettingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ListAgentOverrides(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetAgentSettingsAsync(agentId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set (create or update) a per-agent setting override (Admin only).
|
||||
/// Broadcasts the change to the affected agent in real-time.
|
||||
/// </summary>
|
||||
[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<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a per-agent setting override (Admin only).
|
||||
/// Broadcasts a reload notification to the affected agent.
|
||||
/// </summary>
|
||||
[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<IActionResult> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast a "ConfigReload" signal to all connected agents so they
|
||||
/// re-fetch their full configuration (Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost("reload")]
|
||||
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Create a new site (Admin only).</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>List all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<SiteResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Get a site by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Update a site (Admin only).</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[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<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Generate a new agent registration token (Admin only).</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Get system-wide statistics.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get agent-specific KPIs for the dashboard.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("agent-stats")]
|
||||
[ProducesResponseType(typeof(List<AgentStatItem>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>List all users (Admin only).</summary>
|
||||
[HttpGet]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(typeof(PagedResult<UserResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Get the current user's profile.</summary>
|
||||
[HttpGet("me")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Update the current user's own profile.</summary>
|
||||
[HttpPut("me")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Get a user by ID (Admin only).</summary>
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Create a new user (Admin only).</summary>
|
||||
[HttpPost]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Update a user (Admin only).</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Assign roles to a user (Admin only).</summary>
|
||||
[HttpPut("{id:guid}/roles")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Assign sites to a user (Admin only).</summary>
|
||||
[HttpPut("{id:guid}/sites")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Reset a user's password (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/reset-password")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Delete a user account (Admin only). Self-deletion is forbidden.
|
||||
/// Cannot delete the last administrator.</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Lock a user account (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/lock")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.LockAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Unlock a user account (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/unlock")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.UnlockAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -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<ExceptionFilter> _logger;
|
||||
|
||||
public ExceptionFilter(ILogger<ExceptionFilter> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Api.Hubs;
|
||||
|
||||
/// <summary>
|
||||
/// SignalR hub for real-time configuration push to agents.
|
||||
/// Agents connect and receive config updates instantly when settings change.
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
public class ConfigHub : Hub
|
||||
{
|
||||
private readonly ILogger<ConfigHub> _logger;
|
||||
|
||||
public ConfigHub(ILogger<ConfigHub> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Agents call this on connect to join their personal config channel.
|
||||
/// The agentId comes from the authenticated API key's associated agent.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Service that broadcasts config changes to connected agents via SignalR.
|
||||
/// Called by the SettingService after any setting change.
|
||||
/// </summary>
|
||||
public interface IConfigBroadcastService
|
||||
{
|
||||
/// <summary>Notify all connected agents that a global setting changed.</summary>
|
||||
Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Notify a specific agent that one of its overrides changed.</summary>
|
||||
Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Notify all agents to reload their full configuration.</summary>
|
||||
Task NotifyAllAgentsReload(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class ConfigBroadcastService : IConfigBroadcastService
|
||||
{
|
||||
private readonly IHubContext<ConfigHub> _hubContext;
|
||||
private readonly ILogger<ConfigBroadcastService> _logger;
|
||||
|
||||
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger)
|
||||
{
|
||||
_hubContext = hubContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogInformation("Broadcasting full config reload to all agents");
|
||||
await _hubContext.Clients.All.SendAsync("ConfigReload", ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Heimdall.Api.Hubs;
|
||||
|
||||
/// <summary>
|
||||
/// SignalR hub for real-time camera events pushed to the web UI.
|
||||
/// Connected clients receive new events instantly (motion, person, vehicle, etc.)
|
||||
/// without polling.
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
||||
public class EventsHub : Hub
|
||||
{
|
||||
private readonly ILogger<EventsHub> _logger;
|
||||
|
||||
public EventsHub(ILogger<EventsHub> logger) => _logger = logger;
|
||||
|
||||
/// <summary>
|
||||
/// Clients call this to join a group-filtered event feed (e.g., per site).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clients call this to leave a group-filtered event feed.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends SignalR notifications when new camera events are created.
|
||||
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
|
||||
/// </summary>
|
||||
public class EventBroadcastService : IEventBroadcastService
|
||||
{
|
||||
private readonly IHubContext<EventsHub> _hubContext;
|
||||
private readonly ILogger<EventBroadcastService> _logger;
|
||||
|
||||
public EventBroadcastService(IHubContext<EventsHub> hubContext, ILogger<EventBroadcastService> 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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user