diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7ff45e1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,72 @@ +name: CI + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + build-and-test: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres:17-alpine + env: + POSTGRES_DB: heimdall_test + POSTGRES_USER: heimdall + POSTGRES_PASSWORD: heimdall + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: "10.0.x" + + - name: Restore + run: dotnet restore + + - name: Build + run: dotnet build --no-restore -c Release + + - name: Test + run: dotnet test --no-build -c Release + env: + DATABASE_URL: "Host=localhost;Port=5432;Database=heimdall_test;Username=heimdall;Password=heimdall" + + docker-build: + needs: build-and-test + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build Central image + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile.central + push: false + tags: heimdall/central:latest + + - name: Build Agent image + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile.agent + push: false + tags: heimdall/agent:latest diff --git a/Directory.Build.props b/Directory.Build.props index b5c3a31..d1a9016 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ true latest-Recommended true - $(NoWarn);NU1903;CA1848;CA1727 + $(NoWarn);NU1903;CA1848;CA1727;CA1861;CA1825;CA1873 false @@ -20,5 +20,6 @@ true false + $(NoWarn);CA1707 diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent new file mode 100644 index 0000000..37509ab --- /dev/null +++ b/docker/Dockerfile.agent @@ -0,0 +1,28 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build +WORKDIR /src + +COPY *.slnx . +COPY Directory.Build.props . +COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/ +COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/ +COPY src/Heimdall.Contracts/*.csproj src/Heimdall.Contracts/ +COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/ +COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/ +COPY src/Heimdall.Agent/*.csproj src/Heimdall.Agent/ + +RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj + +COPY src/ src/ + +RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release -o /app + +FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime +WORKDIR /app + +RUN apk add --no-cache icu-libs libstdc++ ffmpeg + +ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false + +COPY --from=build /app . + +ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"] diff --git a/docker/Dockerfile.central b/docker/Dockerfile.central new file mode 100644 index 0000000..d946db2 --- /dev/null +++ b/docker/Dockerfile.central @@ -0,0 +1,42 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build +WORKDIR /src + +# Copy solution and project files +COPY *.slnx . +COPY Directory.Build.props . +COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/ +COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/ +COPY src/Heimdall.Contracts/*.csproj src/Heimdall.Contracts/ +COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/ +COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/ +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.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 +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++ + +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/workers ./workers + +# Expose both API and Web ports +EXPOSE 8080 + +ENTRYPOINT ["dotnet", "api/Heimdall.Api.dll"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..c8c6888 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,62 @@ +services: + postgresql: + image: postgres:17-alpine + environment: + POSTGRES_DB: heimdall + POSTGRES_USER: heimdall + POSTGRES_PASSWORD: heimdall + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U heimdall"] + interval: 10s + timeout: 5s + retries: 5 + + minio: + image: minio/minio:latest + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: heimdall + MINIO_ROOT_PASSWORD: heimdall123 + ports: + - "9000:9000" + - "9001:9001" + volumes: + - minio_data:/data + + heimdall-central: + build: + context: .. + dockerfile: docker/Dockerfile.central + environment: + DATABASE_URL: "Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" + JWT__Key: "ThisIsADevelopmentKeyThatIsAtLeast32Bytes!" + JWT__Issuer: "heimdall" + JWT__Audience: "heimdall-api" + ASPNETCORE_ENVIRONMENT: Development + Cors__AllowedOrigins: "https://localhost:5001,http://localhost:5000" + ports: + - "5000:8080" + depends_on: + postgresql: + condition: service_healthy + restart: unless-stopped + + heimdall-agent: + build: + context: .. + dockerfile: docker/Dockerfile.agent + environment: + HEIMDALL_CENTRAL_URL: "http://heimdall-central:8080" + HEIMDALL_SITE_TOKEN: "replace-with-actual-token" + HEIMDALL_AGENT_NAME: "agent-demo" + depends_on: + - heimdall-central + restart: unless-stopped + +volumes: + pgdata: + minio_data: diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index fa2ca3e..04b6bf2 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -1,7 +1,14 @@ -using Heimdall.Agent; +using Heimdall.Agent.Services; var builder = Host.CreateApplicationBuilder(args); -builder.Services.AddHostedService(); + +builder.Services.AddHttpClient("Central", client => +{ + client.Timeout = TimeSpan.FromSeconds(10); +}); + +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); var host = builder.Build(); host.Run(); diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs new file mode 100644 index 0000000..d94427c --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -0,0 +1,111 @@ +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Services; + +/// +/// Registers this agent with the Heimdall Central server and manages the heartbeat loop. +/// +public class AgentRegistrationService : BackgroundService +{ + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + private readonly AgentState _state; + + public AgentRegistrationService( + IHttpClientFactory httpClientFactory, + AgentState state, + ILogger logger) + { + _httpClientFactory = httpClientFactory; + _state = state; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var centralUrl = Environment.GetEnvironmentVariable("HEIMDALL_CENTRAL_URL") + ?? throw new InvalidOperationException("HEIMDALL_CENTRAL_URL is not set"); + var siteToken = Environment.GetEnvironmentVariable("HEIMDALL_SITE_TOKEN") + ?? throw new InvalidOperationException("HEIMDALL_SITE_TOKEN is not set"); + var hostname = Environment.GetEnvironmentVariable("HEIMDALL_AGENT_NAME") + ?? System.Net.Dns.GetHostName(); + + // Step 1: Register + _logger.LogInformation("Registering agent with Central at {CentralUrl}", centralUrl); + + var client = _httpClientFactory.CreateClient("Central"); + client.BaseAddress = new Uri(centralUrl.TrimEnd('/') + "/"); + + try + { + var request = new RegisterRequest(siteToken, hostname, "1.0.0"); + var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync(stoppingToken); + if (result is null) + throw new InvalidOperationException("Empty registration response"); + + _state.AgentId = result.AgentId; + _state.ApiKey = result.ApiKey; + _state.ApiKeyPrefix = result.ApiKeyPrefix; + + _logger.LogInformation( + "Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}", + result.AgentId, result.ApiKeyPrefix); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to register agent"); + throw; + } + + // Step 2: Heartbeat loop (every 30 seconds) + _logger.LogInformation("Starting heartbeat loop (30s interval)"); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + var heartbeatRequest = new HeartbeatRequest(GetPublicIp()); + var heartbeatResponse = await client.PostAsJsonAsync( + $"api/agents/{_state.AgentId}/heartbeat", + heartbeatRequest, stoppingToken); + + if (!heartbeatResponse.IsSuccessStatusCode) + { + _logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Heartbeat error (will retry)"); + } + + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + } + } + + private static string? GetPublicIp() + { + return null; + } +} + +public class AgentState +{ + public Guid AgentId { get; set; } + public string? ApiKey { get; set; } + public string? ApiKeyPrefix { get; set; } +} + +internal sealed record RegisterRequest(string Token, string Hostname, string Version); + +internal sealed record RegisterResponse( + [property: JsonPropertyName("agentId")] Guid AgentId, + [property: JsonPropertyName("apiKey")] string ApiKey, + [property: JsonPropertyName("apiKeyPrefix")] string ApiKeyPrefix); + +internal sealed record HeartbeatRequest(string? PublicIp); diff --git a/src/Heimdall.Api/Controllers/AgentsController.cs b/src/Heimdall.Api/Controllers/AgentsController.cs new file mode 100644 index 0000000..4a792e3 --- /dev/null +++ b/src/Heimdall.Api/Controllers/AgentsController.cs @@ -0,0 +1,65 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/agents")] +public class AgentsController : ControllerBase +{ + private readonly IAgentService _agentService; + + public AgentsController(IAgentService agentService) => _agentService = agentService; + + /// Register an agent using a site registration token. + [AllowAnonymous] + [HttpPost("register")] + public async Task Register( + [FromBody] RegisterAgentRequest request, CancellationToken ct) + { + // Extract API key from header (may be empty for registration) + var apiKey = Request.Headers.Authorization.FirstOrDefault() + ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase); + + var result = await _agentService.RegisterAsync(request, apiKey, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Send heartbeat from agent (API Key auth). + [Authorize(AuthenticationSchemes = "ApiKey")] + [HttpPost("{id:guid}/heartbeat")] + public async Task Heartbeat( + Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct) + { + var result = await _agentService.HeartbeatAsync(id, request, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get agent details (JWT auth). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}")] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _agentService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// List agents for a site. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("by-site/{siteId:guid}")] + public async Task ListBySite( + Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct); + return Ok(result.Data); + } +} diff --git a/src/Heimdall.Api/Controllers/AuthController.cs b/src/Heimdall.Api/Controllers/AuthController.cs new file mode 100644 index 0000000..ef99f28 --- /dev/null +++ b/src/Heimdall.Api/Controllers/AuthController.cs @@ -0,0 +1,64 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/auth")] +public class AuthController : ControllerBase +{ + private readonly IAuthService _authService; + + public AuthController(IAuthService authService) => _authService = authService; + + /// Register a new user account. + [AllowAnonymous] + [HttpPost("register")] + public async Task Register( + [FromBody] RegisterRequest request, CancellationToken ct) + { + var result = await _authService.RegisterAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Login with email and password. + [AllowAnonymous] + [HttpPost("login")] + public async Task Login( + [FromBody] LoginRequest request, CancellationToken ct) + { + var result = await _authService.LoginAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Verify 2FA code during login. + [AllowAnonymous] + [HttpPost("2fa/verify")] + public async Task Verify2fa( + [FromBody] Verify2faRequest request, CancellationToken ct) + { + var result = await _authService.Verify2faAsync(request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } + + /// Refresh an expired access token. + [AllowAnonymous] + [HttpPost("refresh")] + public async Task Refresh( + [FromBody] RefreshTokenRequest request, CancellationToken ct) + { + var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Api/Controllers/SitesController.cs b/src/Heimdall.Api/Controllers/SitesController.cs new file mode 100644 index 0000000..42d6a1a --- /dev/null +++ b/src/Heimdall.Api/Controllers/SitesController.cs @@ -0,0 +1,85 @@ +using System.Security.Claims; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/sites")] +public class SitesController : ControllerBase +{ + private readonly ISiteService _siteService; + + public SitesController(ISiteService siteService) => _siteService = siteService; + + /// Create a new site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPost] + public async Task Create( + [FromBody] CreateSiteRequest request, CancellationToken ct) + { + var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + var result = await _siteService.CreateAsync(request, userId, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// List all sites. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet] + public async Task List( + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) + { + var result = await _siteService.ListAsync(page, pageSize, ct); + return Ok(result.Data); + } + + /// Get a site by ID. + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}")] + public async Task GetById(Guid id, CancellationToken ct) + { + var result = await _siteService.GetByIdAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : NotFound(new { error = result.Error }); + } + + /// Update a site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPut("{id:guid}")] + public async Task Update( + Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct) + { + var result = await _siteService.UpdateAsync(id, request, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Delete a site (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)] + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id, CancellationToken ct) + { + var result = await _siteService.DeleteAsync(id, ct); + return result.IsSuccess + ? NoContent() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Generate a new agent registration token (Admin only). + [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] + [HttpPost("{id:guid}/tokens")] + public async Task GenerateToken(Guid id, CancellationToken ct) + { + var result = await _siteService.GenerateTokenAsync(id, ct); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Api/Filters/ExceptionFilter.cs b/src/Heimdall.Api/Filters/ExceptionFilter.cs new file mode 100644 index 0000000..2bfcd16 --- /dev/null +++ b/src/Heimdall.Api/Filters/ExceptionFilter.cs @@ -0,0 +1,34 @@ +using System.Net; +using Heimdall.Application.Common; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Heimdall.Api.Filters; + +public class ExceptionFilter : IExceptionFilter +{ + private readonly ILogger _logger; + + public ExceptionFilter(ILogger logger) => _logger = logger; + + public void OnException(ExceptionContext context) + { + _logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message); + + var response = new + { + error = new + { + code = "InternalServerError", + message = "An unexpected error occurred" + } + }; + + context.Result = new ObjectResult(response) + { + StatusCode = (int)HttpStatusCode.InternalServerError + }; + + context.ExceptionHandled = true; + } +} diff --git a/src/Heimdall.Api/Heimdall.Api.csproj b/src/Heimdall.Api/Heimdall.Api.csproj index 3f60095..b56ead6 100644 --- a/src/Heimdall.Api/Heimdall.Api.csproj +++ b/src/Heimdall.Api/Heimdall.Api.csproj @@ -7,6 +7,7 @@ + diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 666a9c5..8d6436f 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -1,23 +1,121 @@ +using System.Text; +using Heimdall.Api.Filters; +using Heimdall.Application; +using Heimdall.Infrastructure; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; + var builder = WebApplication.CreateBuilder(args); -// Add services to the container. +// ── Services ────────────────────────────────────────────────────── + +builder.Services.AddControllers(options => +{ + options.Filters.Add(); +}); -builder.Services.AddControllers(); -// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); +// ── Application layer ───────────────────────────────────────────── +builder.Services.AddApplication(); + +// ── Infrastructure layer ────────────────────────────────────────── +builder.Services.AddInfrastructure(builder.Configuration); + +// ── Authentication ──────────────────────────────────────────────── +var jwtKey = builder.Configuration["Jwt:Key"] + ?? throw new InvalidOperationException("JWT:Key is not configured"); +var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "heimdall"; +var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "heimdall-api"; + +builder.Services.AddAuthentication(options => +{ + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; +}) +.AddJwtBearer("JwtBearer", options => +{ + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)), + ValidateIssuer = true, + ValidIssuer = jwtIssuer, + ValidateAudience = true, + ValidAudience = jwtAudience, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }; +}) +.AddScheme("ApiKey", null); + +// ── Authorization policies ─────────────────────────────────────── +builder.Services.AddAuthorization(options => +{ + var allPermissions = AppPermissions.RolePermissions.Values + .SelectMany(p => p).Distinct(); + + foreach (var permission in allPermissions) + { + options.AddPolicy(permission, policy => + policy.RequireClaim("permission", permission)); + } +}); + +// ── CORS ────────────────────────────────────────────────────────── +var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',') + ?? ["https://localhost:5001"]; + +builder.Services.AddCors(options => +{ + options.AddPolicy("ApiPolicy", policy => + policy.WithOrigins(allowedOrigins) + .AllowCredentials() + .AllowAnyHeader() + .WithMethods("GET", "POST", "PUT", "DELETE", "PATCH")); +}); + +// ── Pipeline ────────────────────────────────────────────────────── + var app = builder.Build(); -// Configure the HTTP request pipeline. +// Apply migrations on startup +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + if (db.Database.GetPendingMigrations().Any()) + { + db.Database.Migrate(); + } +} + +// Seed roles +using (var scope = app.Services.CreateScope()) +{ + var roleManager = scope.ServiceProvider + .GetRequiredService>(); + + foreach (var roleName in AppRoles.All) + { + if (!await roleManager.RoleExistsAsync(roleName)) + { + await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName)); + } + } +} + if (app.Environment.IsDevelopment()) { app.MapOpenApi(); } +app.UseCors("ApiPolicy"); app.UseHttpsRedirection(); - +app.UseAuthentication(); app.UseAuthorization(); - app.MapControllers(); app.Run(); diff --git a/src/Heimdall.Application/Common/ServiceResult.cs b/src/Heimdall.Application/Common/ServiceResult.cs new file mode 100644 index 0000000..6df7ed2 --- /dev/null +++ b/src/Heimdall.Application/Common/ServiceResult.cs @@ -0,0 +1,48 @@ +namespace Heimdall.Application.Common; + +public class ServiceResult +{ + public bool IsSuccess { get; protected set; } + public string? Error { get; protected set; } + public int? StatusCode { get; protected set; } + + protected ServiceResult() { } + + public static ServiceResult Success() => new() { IsSuccess = true }; + + public static ServiceResult Failure(string error, int statusCode = 400) => + new() { IsSuccess = false, Error = error, StatusCode = statusCode }; + + public static ServiceResult NotFound(string error = "Resource not found") => + new() { IsSuccess = false, Error = error, StatusCode = 404 }; + + public static ServiceResult Unauthorized(string error = "Unauthorized") => + new() { IsSuccess = false, Error = error, StatusCode = 401 }; + + public static ServiceResult Conflict(string error) => + new() { IsSuccess = false, Error = error, StatusCode = 409 }; +} + +#pragma warning disable CA1000 // Do not declare static members on generic types +public class ServiceResult : ServiceResult +{ + public T? Data { get; private set; } + + private ServiceResult() { } + + public static ServiceResult Success(T data) => + new() { IsSuccess = true, Data = data }; + + public new static ServiceResult Failure(string error, int statusCode = 400) => + new() { IsSuccess = false, Error = error, StatusCode = statusCode }; + + public new static ServiceResult NotFound(string error = "Resource not found") => + new() { IsSuccess = false, Error = error, StatusCode = 404 }; + + public new static ServiceResult Unauthorized(string error = "Unauthorized") => + new() { IsSuccess = false, Error = error, StatusCode = 401 }; + + public new static ServiceResult Conflict(string error) => + new() { IsSuccess = false, Error = error, StatusCode = 409 }; +} +#pragma warning restore CA1000 diff --git a/src/Heimdall.Application/DTOs/AgentDto.cs b/src/Heimdall.Application/DTOs/AgentDto.cs new file mode 100644 index 0000000..7acaad0 --- /dev/null +++ b/src/Heimdall.Application/DTOs/AgentDto.cs @@ -0,0 +1,36 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Application.DTOs; + +public record RegisterAgentRequest( + string Token, + string Hostname, + string Version, + string? PublicIp); + +public record AgentHeartbeatRequest( + string? PublicIp, + bool? HasGpu, + int? CpuCores, + long? MemoryMb, + string? GpuType); + +public record AgentResponse( + Guid Id, + Guid SiteId, + string Name, + string Hostname, + string Version, + AgentStatus Status, + DateTime? LastHeartbeat, + string? PublicIp, + bool HasGpu, + int CpuCores, + long MemoryMb, + string GpuType, + DateTime CreatedAt); + +public record RegisterAgentResponse( + Guid AgentId, + string ApiKey, + string ApiKeyPrefix); diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs new file mode 100644 index 0000000..6dd40fe --- /dev/null +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -0,0 +1,37 @@ +namespace Heimdall.Application.DTOs; + +public record RegisterRequest(string Email, string Password, string DisplayName); + +public record LoginRequest(string Email, string Password); + +public record Verify2faRequest(string Email, string Code); + +public record RefreshTokenRequest(string RefreshToken); + +public record AuthResponse( + string AccessToken, + string RefreshToken, + DateTime ExpiresAt, + bool Requires2fa, + UserInfo User); + +public record UserInfo( + Guid Id, + string Email, + string DisplayName, + IList Roles); + +public record ApiKeyResponse( + Guid Id, + string KeyPrefix, + Guid? SiteId, + DateTime CreatedAt, + DateTime? ExpiresAt, + bool Enabled, + DateTime? LastUsedAt); + +public record CreateApiKeyResponse( + Guid Id, + string KeyPrefix, + string FullKey, + DateTime? ExpiresAt); diff --git a/src/Heimdall.Application/DTOs/PagedResult.cs b/src/Heimdall.Application/DTOs/PagedResult.cs new file mode 100644 index 0000000..dca6b2d --- /dev/null +++ b/src/Heimdall.Application/DTOs/PagedResult.cs @@ -0,0 +1,12 @@ +namespace Heimdall.Application.DTOs; + +public record PagedResult( + IReadOnlyList Items, + int TotalCount, + int Page, + int PageSize) +{ + public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize); + public bool HasPreviousPage => Page > 1; + public bool HasNextPage => Page < TotalPages; +} diff --git a/src/Heimdall.Application/DTOs/SiteDto.cs b/src/Heimdall.Application/DTOs/SiteDto.cs new file mode 100644 index 0000000..a5c4e33 --- /dev/null +++ b/src/Heimdall.Application/DTOs/SiteDto.cs @@ -0,0 +1,26 @@ +namespace Heimdall.Application.DTOs; + +public record CreateSiteRequest(string Name, string? Address, string? Timezone); + +public record UpdateSiteRequest(string Name, string? Address, string? Timezone); + +public record SiteResponse( + Guid Id, + string Name, + string? Address, + string Timezone, + bool Enabled, + DateTime CreatedAt); + +public record SiteWithTokenResponse( + Guid Id, + string Name, + string? Address, + string Timezone, + string? RegistrationToken, + DateTime? TokenExpiresAt, + DateTime CreatedAt); + +public record RegistrationTokenResponse( + string Token, + DateTime ExpiresAt); diff --git a/src/Heimdall.Application/DependencyInjection.cs b/src/Heimdall.Application/DependencyInjection.cs new file mode 100644 index 0000000..ed38f62 --- /dev/null +++ b/src/Heimdall.Application/DependencyInjection.cs @@ -0,0 +1,14 @@ +using FluentValidation; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Application; + +public static class DependencyInjection +{ + public static IServiceCollection AddApplication(this IServiceCollection services) + { + services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly); + + return services; + } +} diff --git a/src/Heimdall.Application/Heimdall.Application.csproj b/src/Heimdall.Application/Heimdall.Application.csproj index cd24e0d..d7370c4 100644 --- a/src/Heimdall.Application/Heimdall.Application.csproj +++ b/src/Heimdall.Application/Heimdall.Application.csproj @@ -4,6 +4,11 @@ + + + + + net10.0 enable diff --git a/src/Heimdall.Application/Services/IAgentService.cs b/src/Heimdall.Application/Services/IAgentService.cs new file mode 100644 index 0000000..c964ac1 --- /dev/null +++ b/src/Heimdall.Application/Services/IAgentService.cs @@ -0,0 +1,12 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +public interface IAgentService +{ + Task> RegisterAsync(RegisterAgentRequest request, string? apiKey, CancellationToken ct); + Task HeartbeatAsync(Guid agentId, AgentHeartbeatRequest request, CancellationToken ct); + Task> GetByIdAsync(Guid id, CancellationToken ct); + Task>> ListBySiteAsync(Guid siteId, int page, int pageSize, CancellationToken ct); +} diff --git a/src/Heimdall.Application/Services/IApiKeyService.cs b/src/Heimdall.Application/Services/IApiKeyService.cs new file mode 100644 index 0000000..de3d317 --- /dev/null +++ b/src/Heimdall.Application/Services/IApiKeyService.cs @@ -0,0 +1,12 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +public interface IApiKeyService +{ + Task> CreateAsync(Guid? siteId, Guid? createdByUserId, DateTime? expiresAt, CancellationToken ct); + Task>> ListAsync(Guid? siteId, int page, int pageSize, CancellationToken ct); + Task RevokeAsync(Guid id, CancellationToken ct); + Task> ValidateKeyAsync(string key, CancellationToken ct); +} diff --git a/src/Heimdall.Application/Services/IAuthService.cs b/src/Heimdall.Application/Services/IAuthService.cs new file mode 100644 index 0000000..f5b0db7 --- /dev/null +++ b/src/Heimdall.Application/Services/IAuthService.cs @@ -0,0 +1,14 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +public interface IAuthService +{ + Task> RegisterAsync(RegisterRequest request, CancellationToken ct); + Task> LoginAsync(LoginRequest request, CancellationToken ct); + Task> Verify2faAsync(Verify2faRequest request, CancellationToken ct); + Task> RefreshTokenAsync(string refreshToken, CancellationToken ct); + Task Enable2faAsync(Guid userId, CancellationToken ct); + Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct); +} diff --git a/src/Heimdall.Application/Services/ISiteService.cs b/src/Heimdall.Application/Services/ISiteService.cs new file mode 100644 index 0000000..fe45bf6 --- /dev/null +++ b/src/Heimdall.Application/Services/ISiteService.cs @@ -0,0 +1,14 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +public interface ISiteService +{ + Task> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct); + Task> GetByIdAsync(Guid id, CancellationToken ct); + Task>> ListAsync(int page, int pageSize, CancellationToken ct); + Task> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct); + Task DeleteAsync(Guid id, CancellationToken ct); + Task> GenerateTokenAsync(Guid id, CancellationToken ct); +} diff --git a/src/Heimdall.Application/Validators/CreateSiteValidator.cs b/src/Heimdall.Application/Validators/CreateSiteValidator.cs new file mode 100644 index 0000000..bd93cd6 --- /dev/null +++ b/src/Heimdall.Application/Validators/CreateSiteValidator.cs @@ -0,0 +1,87 @@ +using FluentValidation; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Validators; + +public class CreateSiteValidator : AbstractValidator +{ + public CreateSiteValidator() + { + RuleFor(x => x.Name) + .NotEmpty() + .MaximumLength(200); + + RuleFor(x => x.Address) + .MaximumLength(500) + .When(x => x.Address is not null); + + RuleFor(x => x.Timezone) + .Must(tz => string.IsNullOrEmpty(tz) || IsValidTimezone(tz)) + .WithMessage("Invalid timezone. Use IANA timezone format (e.g., 'Europe/Paris')."); + } + + private static bool IsValidTimezone(string timezone) + { + try + { + _ = TimeZoneInfo.FindSystemTimeZoneById(timezone); + return true; + } + catch + { + return false; + } + } +} + +public class RegisterAgentValidator : AbstractValidator +{ + public RegisterAgentValidator() + { + RuleFor(x => x.Token) + .NotEmpty() + .MaximumLength(500); + + RuleFor(x => x.Hostname) + .NotEmpty() + .MaximumLength(255); + + RuleFor(x => x.Version) + .MaximumLength(50); + } +} + +public class LoginRequestValidator : AbstractValidator +{ + public LoginRequestValidator() + { + RuleFor(x => x.Email) + .NotEmpty() + .EmailAddress() + .MaximumLength(200); + + RuleFor(x => x.Password) + .NotEmpty() + .MaximumLength(200); + } +} + +public class RegisterRequestValidator : AbstractValidator +{ + public RegisterRequestValidator() + { + RuleFor(x => x.Email) + .NotEmpty() + .EmailAddress() + .MaximumLength(200); + + RuleFor(x => x.Password) + .NotEmpty() + .MinimumLength(8) + .MaximumLength(200); + + RuleFor(x => x.DisplayName) + .NotEmpty() + .MaximumLength(200); + } +} diff --git a/src/Heimdall.Domain.Primitives/Entity.cs b/src/Heimdall.Domain.Primitives/Entity.cs new file mode 100644 index 0000000..0684bbc --- /dev/null +++ b/src/Heimdall.Domain.Primitives/Entity.cs @@ -0,0 +1,28 @@ +namespace Heimdall.Domain.Primitives; + +/// +/// Base class for all domain entities with a strongly-typed identifier. +/// +public abstract class Entity : IEquatable> + where TId : notnull +{ + public TId Id { get; protected set; } = default!; + + protected Entity(TId id) => Id = id; + + protected Entity() { } // EF Core + + public override bool Equals(object? obj) => + obj is Entity other && Id.Equals(other.Id); + + public bool Equals(Entity? other) => + other is not null && Id.Equals(other.Id); + + public override int GetHashCode() => Id.GetHashCode(); + + public static bool operator ==(Entity? left, Entity? right) => + left is null ? right is null : left.Equals(right); + + public static bool operator !=(Entity? left, Entity? right) => + !(left == right); +} diff --git a/src/Heimdall.Domain.Primitives/IAuditableEntity.cs b/src/Heimdall.Domain.Primitives/IAuditableEntity.cs new file mode 100644 index 0000000..9f57fbc --- /dev/null +++ b/src/Heimdall.Domain.Primitives/IAuditableEntity.cs @@ -0,0 +1,10 @@ +namespace Heimdall.Domain.Primitives; + +/// +/// Interface for entities with automatic audit timestamp tracking. +/// +public interface IAuditableEntity +{ + DateTime CreatedAt { get; set; } + DateTime UpdatedAt { get; set; } +} diff --git a/src/Heimdall.Domain.Primitives/ISoftDeletable.cs b/src/Heimdall.Domain.Primitives/ISoftDeletable.cs new file mode 100644 index 0000000..76c6496 --- /dev/null +++ b/src/Heimdall.Domain.Primitives/ISoftDeletable.cs @@ -0,0 +1,11 @@ +namespace Heimdall.Domain.Primitives; + +/// +/// Interface for entities that support soft deletion. +/// +public interface ISoftDeletable +{ + bool IsDeleted { get; } + DateTime? DeletedAt { get; } + void SoftDelete(); +} diff --git a/src/Heimdall.Domain.Primitives/ValueObject.cs b/src/Heimdall.Domain.Primitives/ValueObject.cs new file mode 100644 index 0000000..7cda4fb --- /dev/null +++ b/src/Heimdall.Domain.Primitives/ValueObject.cs @@ -0,0 +1,35 @@ +namespace Heimdall.Domain.Primitives; + +/// +/// Base class for value objects. Equality is based on all constituent properties. +/// +public abstract class ValueObject : IEquatable +{ + protected abstract IEnumerable GetEqualityComponents(); + + public override bool Equals(object? obj) + { + if (obj is null || obj.GetType() != GetType()) + return false; + + var other = (ValueObject)obj; + return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); + } + + public bool Equals(ValueObject? other) => + other is not null && GetType() == other.GetType() + && GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); + + public override int GetHashCode() + { + return GetEqualityComponents() + .Select(x => x?.GetHashCode() ?? 0) + .Aggregate((x, y) => x ^ y); + } + + public static bool operator ==(ValueObject? left, ValueObject? right) => + left is null ? right is null : left.Equals(right); + + public static bool operator !=(ValueObject? left, ValueObject? right) => + !(left == right); +} diff --git a/src/Heimdall.Domain/Entities/Agent.cs b/src/Heimdall.Domain/Entities/Agent.cs new file mode 100644 index 0000000..b6d2f82 --- /dev/null +++ b/src/Heimdall.Domain/Entities/Agent.cs @@ -0,0 +1,91 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +public class Agent : Entity, IAuditableEntity, ISoftDeletable +{ + public Guid SiteId { get; private set; } + public string Name { get; private set; } = string.Empty; + public string Hostname { get; private set; } = string.Empty; + public string Version { get; private set; } = string.Empty; + public AgentStatus Status { get; private set; } = AgentStatus.Offline; + public DateTime? LastHeartbeat { get; private set; } + public string? PublicIp { get; private set; } + + /// HMACSHA256 hash of the agent's API key. + public string? ApiKeyHash { get; private set; } + + /// First 8 characters of the API key for identification. + public string? ApiKeyPrefix { get; private set; } + + // Capabilities + public bool HasGpu { get; private set; } + public int CpuCores { get; private set; } + public long MemoryMb { get; private set; } + public GpuAcceleration GpuType { get; private set; } = GpuAcceleration.None; + + // Audit + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + // Soft delete + public bool IsDeleted { get; private set; } + public DateTime? DeletedAt { get; private set; } + + // Navigation + public Site Site { get; private set; } = null!; + private readonly List _cameras = []; + public IReadOnlyCollection Cameras => _cameras.AsReadOnly(); + + private Agent() { } // EF Core + + public Agent(Guid siteId, string name, string hostname, string version) + : base(Guid.NewGuid()) + { + SiteId = siteId; + Name = name; + Hostname = hostname; + Version = version; + } + + public void Register(string apiKeyHash, string apiKeyPrefix) + { + ApiKeyHash = apiKeyHash; + ApiKeyPrefix = apiKeyPrefix; + Status = AgentStatus.Online; + LastHeartbeat = DateTime.UtcNow; + } + + public void UpdateHeartbeat(string? publicIp = null) + { + LastHeartbeat = DateTime.UtcNow; + Status = AgentStatus.Online; + if (publicIp is not null) + PublicIp = publicIp; + } + + public void MarkOffline() + { + Status = AgentStatus.Offline; + } + + public void MarkError() + { + Status = AgentStatus.Error; + } + + public void UpdateCapabilities(bool hasGpu, int cpuCores, long memoryMb, GpuAcceleration gpuType) + { + HasGpu = hasGpu; + CpuCores = cpuCores; + MemoryMb = memoryMb; + GpuType = gpuType; + } + + public void SoftDelete() + { + IsDeleted = true; + DeletedAt = DateTime.UtcNow; + } +} diff --git a/src/Heimdall.Domain/Entities/ApiKey.cs b/src/Heimdall.Domain/Entities/ApiKey.cs new file mode 100644 index 0000000..de80acd --- /dev/null +++ b/src/Heimdall.Domain/Entities/ApiKey.cs @@ -0,0 +1,42 @@ +namespace Heimdall.Domain.Entities; + +public class ApiKey +{ + public Guid Id { get; private set; } = Guid.NewGuid(); + + /// HMACSHA256 hash of the full API key. + public string KeyHash { get; private set; } = string.Empty; + + /// First 8 characters of the key for identification. + public string KeyPrefix { get; private set; } = string.Empty; + + /// If scoped to a site, the agent can only access that site. + public Guid? SiteId { get; private set; } + + /// Who created this key. + public Guid? CreatedByUserId { get; private set; } + + public DateTime CreatedAt { get; private set; } = DateTime.UtcNow; + public DateTime? ExpiresAt { get; private set; } + public bool Enabled { get; private set; } = true; + public DateTime? LastUsedAt { get; private set; } + + // Navigation + public Site? Site { get; private set; } + + private ApiKey() { } // EF Core + + public ApiKey(string keyHash, string keyPrefix, Guid? siteId = null, Guid? createdByUserId = null) + { + KeyHash = keyHash; + KeyPrefix = keyPrefix; + SiteId = siteId; + CreatedByUserId = createdByUserId; + } + + public void MarkUsed() => LastUsedAt = DateTime.UtcNow; + + public void Disable() => Enabled = false; + + public void SetExpiry(DateTime expiresAt) => ExpiresAt = expiresAt; +} diff --git a/src/Heimdall.Domain/Entities/AppRole.cs b/src/Heimdall.Domain/Entities/AppRole.cs new file mode 100644 index 0000000..121738d --- /dev/null +++ b/src/Heimdall.Domain/Entities/AppRole.cs @@ -0,0 +1,10 @@ +using Microsoft.AspNetCore.Identity; + +namespace Heimdall.Domain.Entities; + +public class AppRole : IdentityRole +{ + public AppRole() { } + + public AppRole(string name) : base(name) { } +} diff --git a/src/Heimdall.Domain/Entities/AppUser.cs b/src/Heimdall.Domain/Entities/AppUser.cs new file mode 100644 index 0000000..35e7afd --- /dev/null +++ b/src/Heimdall.Domain/Entities/AppUser.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.Identity; + +namespace Heimdall.Domain.Entities; + +public class AppUser : IdentityUser +{ + public string DisplayName { get; set; } = string.Empty; + public string? Theme { get; set; } = "Auto"; + public string Language { get; set; } = "fr"; + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + // Navigation + private readonly List _userSites = []; + public IReadOnlyCollection UserSites => _userSites.AsReadOnly(); +} diff --git a/src/Heimdall.Domain/Entities/AuditLog.cs b/src/Heimdall.Domain/Entities/AuditLog.cs new file mode 100644 index 0000000..de30a3b --- /dev/null +++ b/src/Heimdall.Domain/Entities/AuditLog.cs @@ -0,0 +1,38 @@ +namespace Heimdall.Domain.Entities; + +/// +/// Append-only audit log for security-relevant actions. +/// DB-level INSERT-only trigger recommended in production. +/// +public class AuditLog +{ + public Guid Id { get; private set; } = Guid.NewGuid(); + public Guid? UserId { get; private set; } + public string Action { get; private set; } = string.Empty; + public string ResourceType { get; private set; } = string.Empty; + public string? ResourceId { get; private set; } + public string? OldValue { get; private set; } + public string? NewValue { get; private set; } + public string? IpAddress { get; private set; } + public DateTime Timestamp { get; private set; } = DateTime.UtcNow; + + private AuditLog() { } // EF Core + + public AuditLog( + Guid? userId, + string action, + string resourceType, + string? resourceId = null, + string? oldValue = null, + string? newValue = null, + string? ipAddress = null) + { + UserId = userId; + Action = action; + ResourceType = resourceType; + ResourceId = resourceId; + OldValue = oldValue; + NewValue = newValue; + IpAddress = ipAddress; + } +} diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs new file mode 100644 index 0000000..3ae91d8 --- /dev/null +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -0,0 +1,73 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +public class Camera : Entity, IAuditableEntity, ISoftDeletable +{ + public Guid SiteId { get; private set; } + public Guid? AgentId { get; private set; } + public string Name { get; private set; } = string.Empty; + public string? Manufacturer { get; private set; } + public string? Model { get; private set; } + public string? RtspUrl { get; private set; } + public CameraStatus Status { get; private set; } = CameraStatus.Disabled; + + // Capabilities + public bool HasPtz { get; private set; } + public bool HasAudio { get; private set; } + public bool HasMotionDetection { get; private set; } + + // Audit + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + // Soft delete + public bool IsDeleted { get; private set; } + public DateTime? DeletedAt { get; private set; } + + // Navigation + public Site Site { get; private set; } = null!; + public Agent? Agent { get; private set; } + public CameraCredentials? Credentials { get; private set; } + public CameraDetectionProfile? DetectionProfile { get; private set; } + + private Camera() { } // EF Core + + public Camera(Guid siteId, string name, string? rtspUrl = null) + : base(Guid.NewGuid()) + { + SiteId = siteId; + Name = name; + RtspUrl = rtspUrl; + } + + public void AssignAgent(Guid agentId) => AgentId = agentId; + + public void Update(string name, string? manufacturer, string? model, string? rtspUrl) + { + Name = name; + Manufacturer = manufacturer; + Model = model; + RtspUrl = rtspUrl; + } + + public void SetStatus(CameraStatus status) => Status = status; + + public void SetCapabilities(bool ptz, bool audio, bool motion) + { + HasPtz = ptz; + HasAudio = audio; + HasMotionDetection = motion; + } + + public void SetCredentials(CameraCredentials credentials) => Credentials = credentials; + + public void SetDetectionProfile(CameraDetectionProfile profile) => DetectionProfile = profile; + + public void SoftDelete() + { + IsDeleted = true; + DeletedAt = DateTime.UtcNow; + } +} diff --git a/src/Heimdall.Domain/Entities/CameraCredentials.cs b/src/Heimdall.Domain/Entities/CameraCredentials.cs new file mode 100644 index 0000000..c874b80 --- /dev/null +++ b/src/Heimdall.Domain/Entities/CameraCredentials.cs @@ -0,0 +1,32 @@ +namespace Heimdall.Domain.Entities; + +/// +/// Encrypted ONVIF/RTSP credentials for a camera. +/// All sensitive fields are encrypted at rest via IDataProtector. +/// +public class CameraCredentials +{ + public Guid CameraId { get; private set; } + public string OnvifUsername { get; set; } = "admin"; + + /// Encrypted at rest. + public string OnvifPassword { get; set; } = string.Empty; + + /// Encrypted at rest. + public string RtspUsername { get; set; } = string.Empty; + + /// Encrypted at rest. + public string RtspPassword { get; set; } = string.Empty; + + public DateTime CreatedAt { get; private set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public Camera Camera { get; private set; } = null!; + + private CameraCredentials() { } // EF Core + + public CameraCredentials(Guid cameraId) + { + CameraId = cameraId; + } +} diff --git a/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs new file mode 100644 index 0000000..9aec226 --- /dev/null +++ b/src/Heimdall.Domain/Entities/CameraDetectionProfile.cs @@ -0,0 +1,48 @@ +namespace Heimdall.Domain.Entities; + +/// +/// Per-camera AI detection profile. +/// Controls what the Agent detects and what AI processing runs on the Central. +/// +public class CameraDetectionProfile +{ + public Guid CameraId { get; private set; } + + // Object types to detect + public bool DetectPerson { get; set; } = true; + public bool DetectVehicle { get; set; } = true; + public bool DetectAnimal { get; set; } + public bool DetectPackage { get; set; } + public bool DetectMotion { get; set; } = true; + + // Heavy AI (Central GPU) + public bool FaceRecognition { get; set; } = true; + public bool LicensePlateRecognition { get; set; } = true; + + // Snapshot parameters + public int IdleIntervalMs { get; set; } = 1000; + public int MotionIntervalMs { get; set; } = 500; + public int ActiveIntervalMs { get; set; } = 200; + public double MotionThreshold { get; set; } = 0.3; + + // YOLO + public string YoloModel { get; set; } = "yolov8n"; + public double MinConfidence { get; set; } = 0.4; + + // Deduplication + public bool RequireMotionForAI { get; set; } = true; + public double IoUThreshold { get; set; } = 0.6; + public int PersonCooldownSec { get; set; } = 30; + public int VehicleCooldownSec { get; set; } = 60; + public int AnimalCooldownSec { get; set; } = 120; + public int MaxEventsPerMinute { get; set; } = 20; + + public Camera Camera { get; private set; } = null!; + + private CameraDetectionProfile() { } // EF Core + + public CameraDetectionProfile(Guid cameraId) + { + CameraId = cameraId; + } +} diff --git a/src/Heimdall.Domain/Entities/Site.cs b/src/Heimdall.Domain/Entities/Site.cs new file mode 100644 index 0000000..97147de --- /dev/null +++ b/src/Heimdall.Domain/Entities/Site.cs @@ -0,0 +1,69 @@ +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +public class Site : Entity, IAuditableEntity, ISoftDeletable +{ + public string Name { get; private set; } = string.Empty; + public string? Address { get; private set; } + public string Timezone { get; private set; } = "UTC"; + public bool Enabled { get; private set; } = true; + + /// Hashed registration token (SHA256) for agent enrollment. + public string? RegistrationTokenHash { get; private set; } + + /// When the current registration token expires. + public DateTime? TokenExpiresAt { get; private set; } + + // Audit + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + // Soft delete + public bool IsDeleted { get; private set; } + public DateTime? DeletedAt { get; private set; } + + // Navigation + private readonly List _agents = []; + public IReadOnlyCollection Agents => _agents.AsReadOnly(); + + private readonly List _cameras = []; + public IReadOnlyCollection Cameras => _cameras.AsReadOnly(); + + private Site() { } // EF Core + + public Site(string name, string? address = null, string? timezone = null) + : base(Guid.NewGuid()) + { + Name = name; + Address = address; + Timezone = timezone ?? "UTC"; + } + + public void Update(string name, string? address, string? timezone) + { + Name = name; + Address = address; + Timezone = timezone ?? Timezone; + } + + public void GenerateRegistrationToken(string tokenHash, DateTime expiresAt) + { + RegistrationTokenHash = tokenHash; + TokenExpiresAt = expiresAt; + } + + public void ClearRegistrationToken() + { + RegistrationTokenHash = null; + TokenExpiresAt = null; + } + + public void SetEnabled(bool enabled) => Enabled = enabled; + + public void SoftDelete() + { + IsDeleted = true; + DeletedAt = DateTime.UtcNow; + } +} diff --git a/src/Heimdall.Domain/Entities/UserSite.cs b/src/Heimdall.Domain/Entities/UserSite.cs new file mode 100644 index 0000000..b84415d --- /dev/null +++ b/src/Heimdall.Domain/Entities/UserSite.cs @@ -0,0 +1,22 @@ +namespace Heimdall.Domain.Entities; + +/// +/// Many-to-many relationship between users and sites. +/// Determines which sites a non-admin user can access. +/// +public class UserSite +{ + public Guid UserId { get; private set; } + public Guid SiteId { get; private set; } + + public AppUser User { get; private set; } = null!; + public Site Site { get; private set; } = null!; + + private UserSite() { } // EF Core + + public UserSite(Guid userId, Guid siteId) + { + UserId = userId; + SiteId = siteId; + } +} diff --git a/src/Heimdall.Domain/Enums/AgentStatus.cs b/src/Heimdall.Domain/Enums/AgentStatus.cs new file mode 100644 index 0000000..af52a46 --- /dev/null +++ b/src/Heimdall.Domain/Enums/AgentStatus.cs @@ -0,0 +1,8 @@ +namespace Heimdall.Domain.Enums; + +public enum AgentStatus +{ + Offline = 0, + Online = 1, + Error = 2 +} diff --git a/src/Heimdall.Domain/Enums/CameraStatus.cs b/src/Heimdall.Domain/Enums/CameraStatus.cs new file mode 100644 index 0000000..048cf8f --- /dev/null +++ b/src/Heimdall.Domain/Enums/CameraStatus.cs @@ -0,0 +1,10 @@ +namespace Heimdall.Domain.Enums; + +public enum CameraStatus +{ + Unknown = 0, + Online = 1, + Offline = 2, + Disabled = 3, + Error = 4 +} diff --git a/src/Heimdall.Domain/Enums/EventType.cs b/src/Heimdall.Domain/Enums/EventType.cs new file mode 100644 index 0000000..4510159 --- /dev/null +++ b/src/Heimdall.Domain/Enums/EventType.cs @@ -0,0 +1,13 @@ +namespace Heimdall.Domain.Enums; + +public enum EventType +{ + MotionDetected = 0, + PersonDetected = 1, + VehicleDetected = 2, + UnknownPerson = 3, + FaceRecognized = 4, + LicensePlateDetected = 5, + CameraOffline = 6, + CameraOnline = 7 +} diff --git a/src/Heimdall.Domain/Enums/GpuAcceleration.cs b/src/Heimdall.Domain/Enums/GpuAcceleration.cs new file mode 100644 index 0000000..61f1ccb --- /dev/null +++ b/src/Heimdall.Domain/Enums/GpuAcceleration.cs @@ -0,0 +1,9 @@ +namespace Heimdall.Domain.Enums; + +public enum GpuAcceleration +{ + None = 0, + NvidiaCuda = 1, + IntelQuickSync = 2, + Vaapi = 3 +} diff --git a/src/Heimdall.Domain/Enums/StorageProvider.cs b/src/Heimdall.Domain/Enums/StorageProvider.cs new file mode 100644 index 0000000..c669b00 --- /dev/null +++ b/src/Heimdall.Domain/Enums/StorageProvider.cs @@ -0,0 +1,7 @@ +namespace Heimdall.Domain.Enums; + +public enum StorageProvider +{ + Local = 0, + S3 = 1 +} diff --git a/src/Heimdall.Domain/Enums/UserRole.cs b/src/Heimdall.Domain/Enums/UserRole.cs new file mode 100644 index 0000000..3744785 --- /dev/null +++ b/src/Heimdall.Domain/Enums/UserRole.cs @@ -0,0 +1,8 @@ +namespace Heimdall.Domain.Enums; + +public enum UserRole +{ + Admin = 0, + Supervisor = 1, + Viewer = 2 +} diff --git a/src/Heimdall.Domain/Heimdall.Domain.csproj b/src/Heimdall.Domain/Heimdall.Domain.csproj index 8bd1700..f65bbdb 100644 --- a/src/Heimdall.Domain/Heimdall.Domain.csproj +++ b/src/Heimdall.Domain/Heimdall.Domain.csproj @@ -4,6 +4,10 @@ + + + + net10.0 enable diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs new file mode 100644 index 0000000..c2fc787 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -0,0 +1,43 @@ +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data.Interceptors; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Data; + +public class AppDbContext : IdentityDbContext +{ + public AppDbContext(DbContextOptions options) : base(options) { } + + // Domain entities + public DbSet Sites => Set(); + public DbSet Agents => Set(); + public DbSet Cameras => Set(); + public DbSet CameraCredentials => Set(); + public DbSet CameraDetectionProfiles => Set(); + public DbSet UserSites => Set(); + public DbSet ApiKeys => Set(); + public DbSet AuditLogs => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); + + // Global soft-delete filter + builder.Entity().HasQueryFilter(e => !e.IsDeleted); + builder.Entity().HasQueryFilter(e => !e.IsDeleted); + builder.Entity().HasQueryFilter(e => !e.IsDeleted); + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.AddInterceptors( + new AuditInterceptor(), + new SoftDeleteInterceptor()); + + base.OnConfiguring(optionsBuilder); + } +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs b/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs new file mode 100644 index 0000000..2484bbd --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace Heimdall.Infrastructure.Data; + +/// +/// Design-time factory for EF Core migrations. +/// Used by `dotnet ef migrations add` and `dotnet ef database update`. +/// +public class AppDbContextFactory : IDesignTimeDbContextFactory +{ + public AppDbContext CreateDbContext(string[] args) + { + var optionsBuilder = new DbContextOptionsBuilder(); + + var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") + ?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall"; + + optionsBuilder.UseNpgsql(connectionString, npgsql => + npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")); + + return new AppDbContext(optionsBuilder.Options); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs new file mode 100644 index 0000000..df69195 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/AgentConfiguration.cs @@ -0,0 +1,61 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class AgentConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("agents"); + + builder.HasKey(a => a.Id); + + builder.Property(a => a.Name) + .HasMaxLength(200) + .IsRequired(); + + builder.Property(a => a.Hostname) + .HasMaxLength(255) + .IsRequired(); + + builder.Property(a => a.Version) + .HasMaxLength(50); + + builder.Property(a => a.Status) + .HasConversion() + .HasMaxLength(20) + .IsRequired(); + + builder.Property(a => a.PublicIp) + .HasMaxLength(45); + + builder.Property(a => a.ApiKeyHash) + .HasMaxLength(128); + + builder.Property(a => a.ApiKeyPrefix) + .HasMaxLength(8); + + builder.Property(a => a.GpuType) + .HasConversion() + .HasMaxLength(20); + + builder.Property(a => a.CreatedAt) + .HasDefaultValueSql("NOW()"); + + builder.Property(a => a.UpdatedAt) + .HasDefaultValueSql("NOW()"); + + // Indexes + builder.HasIndex(a => a.SiteId); + builder.HasIndex(a => a.LastHeartbeat) + .HasFilter("\"status\" = 'Online'"); + + // Relationships + builder.HasOne(a => a.Site) + .WithMany(s => s.Agents) + .HasForeignKey(a => a.SiteId) + .OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/ApiKeyConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/ApiKeyConfiguration.cs new file mode 100644 index 0000000..94a0027 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/ApiKeyConfiguration.cs @@ -0,0 +1,37 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class ApiKeyConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("api_keys"); + + builder.HasKey(k => k.Id); + + builder.Property(k => k.KeyHash) + .HasMaxLength(128) + .IsRequired(); + + builder.Property(k => k.KeyPrefix) + .HasMaxLength(8) + .IsRequired(); + + builder.Property(k => k.CreatedAt) + .HasDefaultValueSql("NOW()"); + + // Indexes + builder.HasIndex(k => k.KeyHash); + builder.HasIndex(k => k.KeyPrefix); + builder.HasIndex(k => k.SiteId); + + // Relationships + builder.HasOne(k => k.Site) + .WithMany() + .HasForeignKey(k => k.SiteId) + .OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AuditLogConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AuditLogConfiguration.cs new file mode 100644 index 0000000..6ec0b6c --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/AuditLogConfiguration.cs @@ -0,0 +1,41 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class AuditLogConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("audit_logs"); + + builder.HasKey(al => al.Id); + + builder.Property(al => al.Action) + .HasMaxLength(100) + .IsRequired(); + + builder.Property(al => al.ResourceType) + .HasMaxLength(100) + .IsRequired(); + + builder.Property(al => al.ResourceId) + .HasMaxLength(100); + + builder.Property(al => al.IpAddress) + .HasMaxLength(45); + + builder.Property(al => al.Timestamp) + .HasDefaultValueSql("NOW()"); + + // Indexes + builder.HasIndex(al => al.Timestamp) + .IsDescending(); + + builder.HasIndex(al => new { al.ResourceType, al.ResourceId, al.Timestamp }) + .IsDescending(false, false, true); + + builder.HasIndex(al => al.UserId); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs new file mode 100644 index 0000000..305bfb8 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs @@ -0,0 +1,66 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class CameraConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("cameras"); + + builder.HasKey(c => c.Id); + + builder.Property(c => c.Name) + .HasMaxLength(200) + .IsRequired(); + + builder.Property(c => c.Manufacturer) + .HasMaxLength(100); + + builder.Property(c => c.Model) + .HasMaxLength(100); + + builder.Property(c => c.RtspUrl) + .HasMaxLength(1000); + + builder.Property(c => c.Status) + .HasConversion() + .HasMaxLength(20) + .IsRequired(); + + builder.Property(c => c.CreatedAt) + .HasDefaultValueSql("NOW()"); + + builder.Property(c => c.UpdatedAt) + .HasDefaultValueSql("NOW()"); + + // Indexes + builder.HasIndex(c => c.SiteId); + builder.HasIndex(c => c.AgentId); + + // Relationships + builder.HasOne(c => c.Site) + .WithMany(s => s.Cameras) + .HasForeignKey(c => c.SiteId) + .OnDelete(DeleteBehavior.Restrict); + + builder.HasOne(c => c.Agent) + .WithMany(a => a.Cameras) + .HasForeignKey(c => c.AgentId) + .OnDelete(DeleteBehavior.SetNull); + + // One-to-one with credentials + builder.HasOne(c => c.Credentials) + .WithOne(cr => cr.Camera) + .HasForeignKey(cr => cr.CameraId) + .OnDelete(DeleteBehavior.Cascade); + + // One-to-one with detection profile + builder.HasOne(c => c.DetectionProfile) + .WithOne(dp => dp.Camera) + .HasForeignKey(dp => dp.CameraId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraCredentialsConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraCredentialsConfiguration.cs new file mode 100644 index 0000000..2d8c0fb --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraCredentialsConfiguration.cs @@ -0,0 +1,35 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class CameraCredentialsConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("camera_credentials"); + + builder.HasKey(c => c.CameraId); + + builder.Property(c => c.OnvifUsername) + .HasMaxLength(100) + .HasDefaultValue("admin"); + + builder.Property(c => c.OnvifPassword) + .HasMaxLength(500) + .IsRequired(); + + builder.Property(c => c.RtspUsername) + .HasMaxLength(100); + + builder.Property(c => c.RtspPassword) + .HasMaxLength(500); + + builder.Property(c => c.CreatedAt) + .HasDefaultValueSql("NOW()"); + + builder.Property(c => c.UpdatedAt) + .HasDefaultValueSql("NOW()"); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraDetectionProfileConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraDetectionProfileConfiguration.cs new file mode 100644 index 0000000..aa7a666 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraDetectionProfileConfiguration.cs @@ -0,0 +1,22 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class CameraDetectionProfileConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("camera_detection_profiles"); + + builder.HasKey(p => p.CameraId); + + builder.Property(p => p.YoloModel) + .HasMaxLength(50) + .HasDefaultValue("yolov8n"); + + builder.Property(p => p.MinConfidence) + .HasDefaultValue(0.4); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/IdentityConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/IdentityConfiguration.cs new file mode 100644 index 0000000..1567393 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/IdentityConfiguration.cs @@ -0,0 +1,77 @@ +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class AppUserConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("users"); + + builder.Property(u => u.DisplayName) + .HasMaxLength(200) + .IsRequired(); + + builder.Property(u => u.Theme) + .HasMaxLength(20) + .HasDefaultValue("Auto"); + + builder.Property(u => u.Language) + .HasMaxLength(10) + .HasDefaultValue("fr"); + + builder.Property(u => u.CreatedAt) + .HasDefaultValueSql("NOW()"); + } +} + +public class AppRoleConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("roles"); + } +} + +public class IdentityUserRoleConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { + builder.ToTable("user_roles"); + } +} + +public class IdentityUserClaimConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { + builder.ToTable("user_claims"); + } +} + +public class IdentityUserLoginConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { + builder.ToTable("user_logins"); + } +} + +public class IdentityRoleClaimConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { + builder.ToTable("role_claims"); + } +} + +public class IdentityUserTokenConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { + builder.ToTable("user_tokens"); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs new file mode 100644 index 0000000..eafd3ec --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs @@ -0,0 +1,41 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class SiteConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("sites"); + + builder.HasKey(s => s.Id); + + builder.Property(s => s.Name) + .HasMaxLength(200) + .IsRequired(); + + builder.Property(s => s.Address) + .HasMaxLength(500); + + builder.Property(s => s.Timezone) + .HasMaxLength(100) + .IsRequired() + .HasDefaultValue("UTC"); + + builder.Property(s => s.RegistrationTokenHash) + .HasMaxLength(128); + + builder.Property(s => s.CreatedAt) + .HasDefaultValueSql("NOW()"); + + builder.Property(s => s.UpdatedAt) + .HasDefaultValueSql("NOW()"); + + // Indexes + builder.HasIndex(s => s.Name); + builder.HasIndex(s => s.IsDeleted) + .HasFilter("\"is_deleted\" = false"); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/UserSiteConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/UserSiteConfiguration.cs new file mode 100644 index 0000000..00e64d9 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/UserSiteConfiguration.cs @@ -0,0 +1,28 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class UserSiteConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("user_sites"); + + builder.HasKey(us => new { us.UserId, us.SiteId }); + + builder.HasOne(us => us.User) + .WithMany(u => u.UserSites) + .HasForeignKey(us => us.UserId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasOne(us => us.Site) + .WithMany() + .HasForeignKey(us => us.SiteId) + .OnDelete(DeleteBehavior.Restrict); + + // Index for "find all users for a site" queries + builder.HasIndex(us => us.SiteId); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Interceptors/AuditInterceptor.cs b/src/Heimdall.Infrastructure/Data/Interceptors/AuditInterceptor.cs new file mode 100644 index 0000000..e25ec0b --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Interceptors/AuditInterceptor.cs @@ -0,0 +1,39 @@ +using Heimdall.Domain.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Heimdall.Infrastructure.Data.Interceptors; + +public sealed class AuditInterceptor : SaveChangesInterceptor +{ + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + if (eventData.Context is null) + return base.SavingChangesAsync(eventData, result, cancellationToken); + + var entries = eventData.Context.ChangeTracker + .Entries(); + + var now = DateTime.UtcNow; + + foreach (var entry in entries) + { + switch (entry.State) + { + case EntityState.Added: + entry.Entity.CreatedAt = now; + entry.Entity.UpdatedAt = now; + break; + + case EntityState.Modified: + entry.Entity.UpdatedAt = now; + break; + } + } + + return base.SavingChangesAsync(eventData, result, cancellationToken); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Interceptors/SoftDeleteInterceptor.cs b/src/Heimdall.Infrastructure/Data/Interceptors/SoftDeleteInterceptor.cs new file mode 100644 index 0000000..41901db --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Interceptors/SoftDeleteInterceptor.cs @@ -0,0 +1,31 @@ +using Heimdall.Domain.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Heimdall.Infrastructure.Data.Interceptors; + +public sealed class SoftDeleteInterceptor : SaveChangesInterceptor +{ + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + if (eventData.Context is null) + return base.SavingChangesAsync(eventData, result, cancellationToken); + + var entries = eventData.Context.ChangeTracker + .Entries(); + + foreach (var entry in entries) + { + if (entry.State is EntityState.Deleted) + { + entry.State = EntityState.Modified; + entry.Entity.SoftDelete(); + } + } + + return base.SavingChangesAsync(eventData, result, cancellationToken); + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs new file mode 100644 index 0000000..23ba60f --- /dev/null +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -0,0 +1,57 @@ +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Security; +using Heimdall.Infrastructure.Services; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Infrastructure; + +public static class DependencyInjection +{ + public static IServiceCollection AddInfrastructure( + this IServiceCollection services, + IConfiguration configuration, + bool isTestEnvironment = false) + { + var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") + ?? configuration.GetConnectionString("Default") + ?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall"; + + if (!isTestEnvironment) + { + services.AddDbContext(options => + { + options.UseNpgsql(connectionString, npgsql => + npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")); + }); + } + + // Identity + services.AddIdentity(options => + { + options.Password.RequiredLength = 12; + options.Password.RequireDigit = true; + options.Password.RequireLowercase = true; + options.Password.RequireUppercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Lockout.MaxFailedAccessAttempts = 5; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15); + }) + .AddEntityFrameworkStores() + .AddDefaultTokenProviders(); + + // JWT + services.AddScoped(); + + // Application services + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + return services; + } +} diff --git a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj index 3b23a3f..f2aeae8 100644 --- a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj +++ b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj @@ -5,6 +5,19 @@ + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + net10.0 enable diff --git a/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.Designer.cs new file mode 100644 index 0000000..5c830ee --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.Designer.cs @@ -0,0 +1,841 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260716204205_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PublicIp") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("SiteId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"is_deleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.cs b/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.cs new file mode 100644 index 0000000..375818f --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260716204205_InitialCreate.cs @@ -0,0 +1,539 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "audit_logs", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: true), + Action = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + ResourceType = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + ResourceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), + OldValue = table.Column(type: "text", nullable: true), + NewValue = table.Column(type: "text", nullable: true), + IpAddress = table.Column(type: "character varying(45)", maxLength: 45, nullable: true), + Timestamp = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => + { + table.PrimaryKey("PK_audit_logs", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "roles", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "sites", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Address = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + Timezone = table.Column(type: "character varying(100)", maxLength: 100, nullable: false, defaultValue: "UTC"), + Enabled = table.Column(type: "boolean", nullable: false), + RegistrationTokenHash = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + TokenExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + IsDeleted = table.Column(type: "boolean", nullable: false), + DeletedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_sites", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + DisplayName = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Theme = table.Column(type: "character varying(20)", maxLength: 20, nullable: true, defaultValue: "Auto"), + Language = table.Column(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "boolean", nullable: false), + PasswordHash = table.Column(type: "text", nullable: true), + SecurityStamp = table.Column(type: "text", nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true), + PhoneNumber = table.Column(type: "text", nullable: true), + PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), + TwoFactorEnabled = table.Column(type: "boolean", nullable: false), + LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), + LockoutEnabled = table.Column(type: "boolean", nullable: false), + AccessFailedCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "role_claims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_role_claims", x => x.Id); + table.ForeignKey( + name: "FK_role_claims_roles_RoleId", + column: x => x.RoleId, + principalTable: "roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "agents", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Hostname = table.Column(type: "character varying(255)", maxLength: 255, nullable: false), + Version = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + LastHeartbeat = table.Column(type: "timestamp with time zone", nullable: true), + PublicIp = table.Column(type: "character varying(45)", maxLength: 45, nullable: true), + ApiKeyHash = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + ApiKeyPrefix = table.Column(type: "character varying(8)", maxLength: 8, nullable: true), + HasGpu = table.Column(type: "boolean", nullable: false), + CpuCores = table.Column(type: "integer", nullable: false), + MemoryMb = table.Column(type: "bigint", nullable: false), + GpuType = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + IsDeleted = table.Column(type: "boolean", nullable: false), + DeletedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_agents", x => x.Id); + table.ForeignKey( + name: "FK_agents_sites_SiteId", + column: x => x.SiteId, + principalTable: "sites", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "api_keys", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + KeyHash = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + KeyPrefix = table.Column(type: "character varying(8)", maxLength: 8, nullable: false), + SiteId = table.Column(type: "uuid", nullable: true), + CreatedByUserId = table.Column(type: "uuid", nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + ExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + LastUsedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_api_keys", x => x.Id); + table.ForeignKey( + name: "FK_api_keys_sites_SiteId", + column: x => x.SiteId, + principalTable: "sites", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "user_claims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "uuid", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_user_claims", x => x.Id); + table.ForeignKey( + name: "FK_user_claims_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "user_logins", + columns: table => new + { + LoginProvider = table.Column(type: "text", nullable: false), + ProviderKey = table.Column(type: "text", nullable: false), + ProviderDisplayName = table.Column(type: "text", nullable: true), + UserId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_user_logins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_user_logins_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "user_roles", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + RoleId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_user_roles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_user_roles_roles_RoleId", + column: x => x.RoleId, + principalTable: "roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_user_roles_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "user_sites", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_user_sites", x => new { x.UserId, x.SiteId }); + table.ForeignKey( + name: "FK_user_sites_sites_SiteId", + column: x => x.SiteId, + principalTable: "sites", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_user_sites_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "user_tokens", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + LoginProvider = table.Column(type: "text", nullable: false), + Name = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_user_tokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_user_tokens_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "cameras", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + AgentId = table.Column(type: "uuid", nullable: true), + Name = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Manufacturer = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), + Model = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), + RtspUrl = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + HasPtz = table.Column(type: "boolean", nullable: false), + HasAudio = table.Column(type: "boolean", nullable: false), + HasMotionDetection = table.Column(type: "boolean", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + IsDeleted = table.Column(type: "boolean", nullable: false), + DeletedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_cameras", x => x.Id); + table.ForeignKey( + name: "FK_cameras_agents_AgentId", + column: x => x.AgentId, + principalTable: "agents", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_cameras_sites_SiteId", + column: x => x.SiteId, + principalTable: "sites", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "camera_credentials", + columns: table => new + { + CameraId = table.Column(type: "uuid", nullable: false), + OnvifUsername = table.Column(type: "character varying(100)", maxLength: 100, nullable: false, defaultValue: "admin"), + OnvifPassword = table.Column(type: "character varying(500)", maxLength: 500, nullable: false), + RtspUsername = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + RtspPassword = table.Column(type: "character varying(500)", maxLength: 500, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => + { + table.PrimaryKey("PK_camera_credentials", x => x.CameraId); + table.ForeignKey( + name: "FK_camera_credentials_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "camera_detection_profiles", + columns: table => new + { + CameraId = table.Column(type: "uuid", nullable: false), + DetectPerson = table.Column(type: "boolean", nullable: false), + DetectVehicle = table.Column(type: "boolean", nullable: false), + DetectAnimal = table.Column(type: "boolean", nullable: false), + DetectPackage = table.Column(type: "boolean", nullable: false), + DetectMotion = table.Column(type: "boolean", nullable: false), + FaceRecognition = table.Column(type: "boolean", nullable: false), + LicensePlateRecognition = table.Column(type: "boolean", nullable: false), + IdleIntervalMs = table.Column(type: "integer", nullable: false), + MotionIntervalMs = table.Column(type: "integer", nullable: false), + ActiveIntervalMs = table.Column(type: "integer", nullable: false), + MotionThreshold = table.Column(type: "double precision", nullable: false), + YoloModel = table.Column(type: "character varying(50)", maxLength: 50, nullable: false, defaultValue: "yolov8n"), + MinConfidence = table.Column(type: "double precision", nullable: false, defaultValue: 0.40000000000000002), + RequireMotionForAI = table.Column(type: "boolean", nullable: false), + IoUThreshold = table.Column(type: "double precision", nullable: false), + PersonCooldownSec = table.Column(type: "integer", nullable: false), + VehicleCooldownSec = table.Column(type: "integer", nullable: false), + AnimalCooldownSec = table.Column(type: "integer", nullable: false), + MaxEventsPerMinute = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_camera_detection_profiles", x => x.CameraId); + table.ForeignKey( + name: "FK_camera_detection_profiles_cameras_CameraId", + column: x => x.CameraId, + principalTable: "cameras", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_agents_LastHeartbeat", + table: "agents", + column: "LastHeartbeat", + filter: "\"status\" = 'Online'"); + + migrationBuilder.CreateIndex( + name: "IX_agents_SiteId", + table: "agents", + column: "SiteId"); + + migrationBuilder.CreateIndex( + name: "IX_api_keys_KeyHash", + table: "api_keys", + column: "KeyHash"); + + migrationBuilder.CreateIndex( + name: "IX_api_keys_KeyPrefix", + table: "api_keys", + column: "KeyPrefix"); + + migrationBuilder.CreateIndex( + name: "IX_api_keys_SiteId", + table: "api_keys", + column: "SiteId"); + + migrationBuilder.CreateIndex( + name: "IX_audit_logs_ResourceType_ResourceId_Timestamp", + table: "audit_logs", + columns: new[] { "ResourceType", "ResourceId", "Timestamp" }, + descending: new[] { false, false, true }); + + migrationBuilder.CreateIndex( + name: "IX_audit_logs_Timestamp", + table: "audit_logs", + column: "Timestamp", + descending: new bool[0]); + + migrationBuilder.CreateIndex( + name: "IX_audit_logs_UserId", + table: "audit_logs", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_cameras_AgentId", + table: "cameras", + column: "AgentId"); + + migrationBuilder.CreateIndex( + name: "IX_cameras_SiteId", + table: "cameras", + column: "SiteId"); + + migrationBuilder.CreateIndex( + name: "IX_role_claims_RoleId", + table: "role_claims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "roles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_sites_IsDeleted", + table: "sites", + column: "IsDeleted", + filter: "\"is_deleted\" = false"); + + migrationBuilder.CreateIndex( + name: "IX_sites_Name", + table: "sites", + column: "Name"); + + migrationBuilder.CreateIndex( + name: "IX_user_claims_UserId", + table: "user_claims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_user_logins_UserId", + table: "user_logins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_user_roles_RoleId", + table: "user_roles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_user_sites_SiteId", + table: "user_sites", + column: "SiteId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "users", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "users", + column: "NormalizedUserName", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "api_keys"); + + migrationBuilder.DropTable( + name: "audit_logs"); + + migrationBuilder.DropTable( + name: "camera_credentials"); + + migrationBuilder.DropTable( + name: "camera_detection_profiles"); + + migrationBuilder.DropTable( + name: "role_claims"); + + migrationBuilder.DropTable( + name: "user_claims"); + + migrationBuilder.DropTable( + name: "user_logins"); + + migrationBuilder.DropTable( + name: "user_roles"); + + migrationBuilder.DropTable( + name: "user_sites"); + + migrationBuilder.DropTable( + name: "user_tokens"); + + migrationBuilder.DropTable( + name: "cameras"); + + migrationBuilder.DropTable( + name: "roles"); + + migrationBuilder.DropTable( + name: "users"); + + migrationBuilder.DropTable( + name: "agents"); + + migrationBuilder.DropTable( + name: "sites"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000..2a1bab5 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,838 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + partial class AppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PublicIp") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("SiteId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"is_deleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs new file mode 100644 index 0000000..818c94c --- /dev/null +++ b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs @@ -0,0 +1,91 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Text.Encodings.Web; +using Heimdall.Infrastructure.Data; +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Heimdall.Infrastructure.Security; + +public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions { } + +/// +/// AuthenticationHandler for API Key authentication. +/// Validates SHA256-hashed API keys using constant-time comparison. +/// Integrates with ASP.NET Core's standard auth pipeline. +/// +public class ApiKeyAuthenticationHandler : AuthenticationHandler +{ + private readonly IServiceProvider _serviceProvider; + + public ApiKeyAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + IServiceProvider serviceProvider) + : base(options, logger, encoder) + { + _serviceProvider = serviceProvider; + } + + protected override async Task HandleAuthenticateAsync() + { + var apiKey = Request.Headers.Authorization.FirstOrDefault() + ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase) + ?? Request.Headers["X-API-Key"].FirstOrDefault() + ?? Request.Query["apiKey"].FirstOrDefault(); + + if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8) + return AuthenticateResult.NoResult(); + + var prefix = apiKey[..8]; + + using var scope = _serviceProvider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var apiKeyEntity = await db.ApiKeys + .FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled); + + if (apiKeyEntity is null) + return AuthenticateResult.Fail("Invalid API key"); + + // Hash the incoming key and constant-time compare + var incomingHash = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey)); + var storedHash = Convert.FromHexString(apiKeyEntity.KeyHash); + + if (!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(incomingHash, storedHash)) + return AuthenticateResult.Fail("Invalid API key"); + + apiKeyEntity.MarkUsed(); + + var claims = new List + { + new(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()), + new("auth_method", "api_key"), + new("api_key_prefix", prefix), + }; + + if (apiKeyEntity.SiteId.HasValue) + claims.Add(new Claim("site_id", apiKeyEntity.SiteId.Value.ToString())); + + var identity = new ClaimsIdentity(claims, Scheme.Name); + var principal = new ClaimsPrincipal(identity); + + return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)); + } + + /// Generate a new API key and return (plainKey, prefix, hash). + public static (string plainKey, string prefix, string hash) GenerateApiKey() + { + var keyBytes = new byte[32]; + RandomNumberGenerator.Fill(keyBytes); + var plainKey = Convert.ToHexString(keyBytes).ToLowerInvariant(); + var prefix = plainKey[..8]; + var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainKey))).ToLowerInvariant(); + return (plainKey, prefix, hash); + } +} diff --git a/src/Heimdall.Infrastructure/Security/AppPermissions.cs b/src/Heimdall.Infrastructure/Security/AppPermissions.cs new file mode 100644 index 0000000..649d5e0 --- /dev/null +++ b/src/Heimdall.Infrastructure/Security/AppPermissions.cs @@ -0,0 +1,63 @@ +namespace Heimdall.Infrastructure.Security; + +/// +/// Application permission policies for authorization. +/// Usage: [Authorize(Policy = AppPermissions.CameraRead)] +/// +public static class AppPermissions +{ + public const string SiteRead = "Site.Read"; + public const string SiteWrite = "Site.Write"; + public const string SiteDelete = "Site.Delete"; + public const string CameraRead = "Camera.Read"; + public const string CameraWrite = "Camera.Write"; + public const string CameraLive = "Camera.Live"; + public const string CameraRecord = "Camera.Record"; + public const string CameraSnapshot = "Camera.Snapshot"; + public const string EventRead = "Event.Read"; + public const string PersonRead = "Person.Read"; + public const string PersonWrite = "Person.Write"; + public const string AdminManage = "Admin.Manage"; + public const string AdminUsers = "Admin.Users"; + public const string AdminApiKeys = "Admin.ApiKeys"; + public const string AdminJobs = "Admin.Jobs"; + + /// + /// All permissions mapped by role. + /// Admin = all, Supervisor = most, Viewer = read-only. + /// + public static readonly Dictionary RolePermissions = new() + { + [AppRoles.Admin] = + [ + SiteRead, SiteWrite, SiteDelete, + CameraRead, CameraWrite, CameraLive, CameraRecord, CameraSnapshot, + EventRead, + PersonRead, PersonWrite, + AdminManage, AdminUsers, AdminApiKeys, AdminJobs + ], + [AppRoles.Supervisor] = + [ + SiteRead, + CameraRead, CameraWrite, CameraLive, CameraRecord, CameraSnapshot, + EventRead, + PersonRead, PersonWrite + ], + [AppRoles.Viewer] = + [ + SiteRead, + CameraRead, CameraLive, + EventRead, + PersonRead + ] + }; +} + +public static class AppRoles +{ + public const string Admin = "Admin"; + public const string Supervisor = "Supervisor"; + public const string Viewer = "Viewer"; + + public static readonly string[] All = [Admin, Supervisor, Viewer]; +} diff --git a/src/Heimdall.Infrastructure/Security/JwtService.cs b/src/Heimdall.Infrastructure/Security/JwtService.cs new file mode 100644 index 0000000..f4df232 --- /dev/null +++ b/src/Heimdall.Infrastructure/Security/JwtService.cs @@ -0,0 +1,109 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using Heimdall.Domain.Entities; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; + +namespace Heimdall.Infrastructure.Security; + +public interface IJwtService +{ + (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions); + string GenerateRefreshToken(); + ClaimsPrincipal? ValidateRefreshToken(string refreshToken); + string? GetUserIdFromExpiredToken(string token); +} + +public class JwtService : IJwtService +{ + private readonly IConfiguration _configuration; + + public JwtService(IConfiguration configuration) + { + _configuration = configuration; + } + + public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList roles, IList permissions) + { + var key = new SymmetricSecurityKey( + Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] + ?? throw new InvalidOperationException("JWT key is not configured"))); + + var expiresAt = DateTime.UtcNow.AddMinutes( + double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], out var minutes) ? minutes : 15); + + var claims = new List + { + new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), + new(JwtRegisteredClaimNames.Email, user.Email ?? ""), + new(JwtRegisteredClaimNames.Name, user.DisplayName), + new("role", string.Join(",", roles)), + }; + + foreach (var permission in permissions) + { + claims.Add(new Claim("permission", permission)); + } + + var token = new JwtSecurityToken( + issuer: _configuration["Jwt:Issuer"] ?? "heimdall", + audience: _configuration["Jwt:Audience"] ?? "heimdall-api", + claims: claims, + expires: expiresAt, + signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); + + return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt); + } + + public string GenerateRefreshToken() + { + var randomBytes = new byte[64]; + using var rng = RandomNumberGenerator.Create(); + rng.GetBytes(randomBytes); + return Convert.ToBase64String(randomBytes); + } + + public ClaimsPrincipal? ValidateRefreshToken(string refreshToken) + { + var key = new SymmetricSecurityKey( + Encoding.UTF8.GetBytes(_configuration["Jwt:RefreshKey"] + ?? _configuration["Jwt:Key"] + ?? throw new InvalidOperationException("JWT key is not configured"))); + + try + { + var handler = new JwtSecurityTokenHandler(); + return handler.ValidateToken(refreshToken, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = key, + ValidateIssuer = true, + ValidIssuer = _configuration["Jwt:Issuer"] ?? "heimdall", + ValidateAudience = true, + ValidAudience = _configuration["Jwt:Audience"] ?? "heimdall-api", + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }, out _); + } + catch + { + return null; + } + } + + public string? GetUserIdFromExpiredToken(string token) + { + try + { + var handler = new JwtSecurityTokenHandler(); + var jwtToken = handler.ReadJwtToken(token); + return jwtToken.Subject; + } + catch + { + return null; + } + } +} diff --git a/src/Heimdall.Infrastructure/Services/AgentService.cs b/src/Heimdall.Infrastructure/Services/AgentService.cs new file mode 100644 index 0000000..abb9a6f --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/AgentService.cs @@ -0,0 +1,121 @@ +using System.Security.Cryptography; +using System.Text; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Security; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +public class AgentService : IAgentService +{ + private readonly AppDbContext _db; + + public AgentService(AppDbContext db) => _db = db; + + public async Task> RegisterAsync( + RegisterAgentRequest request, string? apiKey, CancellationToken ct) + { + // Find site by registration token hash + var tokenHash = Convert.ToHexString( + SHA256.HashData(Encoding.UTF8.GetBytes(request.Token))).ToLowerInvariant(); + + var site = await _db.Sites + .FirstOrDefaultAsync(s => s.RegistrationTokenHash == tokenHash + && s.TokenExpiresAt > DateTime.UtcNow, ct); + + if (site is null) + return ServiceResult.Unauthorized("Invalid or expired registration token"); + + // Check for duplicate registration + var existing = await _db.Agents + .AnyAsync(a => a.SiteId == site.Id && a.Hostname == request.Hostname, ct); + + if (existing) + return ServiceResult.Conflict( + "An agent with this hostname is already registered for this site"); + + // Generate API key for the agent + var (plainKey, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey(); + + var agent = new Agent(site.Id, request.Hostname, request.Hostname, request.Version); + agent.Register(hash, prefix); + agent.UpdateHeartbeat(request.PublicIp); + _db.Agents.Add(agent); + + // Store API key + var apiKeyEntity = new ApiKey(hash, prefix, site.Id); + _db.ApiKeys.Add(apiKeyEntity); + + // Clear the registration token (single use) + site.ClearRegistrationToken(); + + await _db.SaveChangesAsync(ct); + + // Audit log + _db.AuditLogs.Add(new AuditLog(null, "Agent.Registered", "Agent", + agent.Id.ToString(), ipAddress: request.PublicIp)); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success( + new RegisterAgentResponse(agent.Id, plainKey, prefix)); + } + + public async Task HeartbeatAsync(Guid agentId, AgentHeartbeatRequest request, CancellationToken ct) + { + var agent = await _db.Agents.FindAsync([agentId], ct); + if (agent is null) + return ServiceResult.NotFound("Agent not found"); + + agent.UpdateHeartbeat(request.PublicIp); + + if (request.HasGpu.HasValue || request.CpuCores.HasValue) + { + var gpuType = Enum.TryParse(request.GpuType, true, out var gpu) + ? gpu : GpuAcceleration.None; + + agent.UpdateCapabilities( + request.HasGpu ?? false, + request.CpuCores ?? 0, + request.MemoryMb ?? 0, + gpuType); + } + + await _db.SaveChangesAsync(ct); + return ServiceResult.Success(); + } + + public async Task> GetByIdAsync(Guid id, CancellationToken ct) + { + var agent = await _db.Agents.FindAsync([id], ct); + if (agent is null) + return ServiceResult.NotFound("Agent not found"); + + return ServiceResult.Success(MapResponse(agent)); + } + + public async Task>> ListBySiteAsync( + Guid siteId, int page, int pageSize, CancellationToken ct) + { + var query = _db.Agents.Where(a => a.SiteId == siteId).OrderBy(a => a.Name); + + var total = await query.CountAsync(ct); + var items = await query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(a => MapResponse(a)) + .ToListAsync(ct); + + return ServiceResult>.Success( + new PagedResult(items, total, page, pageSize)); + } + + private static AgentResponse MapResponse(Agent a) => new( + a.Id, a.SiteId, a.Name, a.Hostname, a.Version, a.Status, + a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb, + a.GpuType.ToString(), a.CreatedAt); +} diff --git a/src/Heimdall.Infrastructure/Services/AuthService.cs b/src/Heimdall.Infrastructure/Services/AuthService.cs new file mode 100644 index 0000000..38ecbe6 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/AuthService.cs @@ -0,0 +1,156 @@ +using System.Security.Claims; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +public class AuthService : IAuthService +{ + private readonly UserManager _userManager; + private readonly SignInManager _signInManager; + private readonly IJwtService _jwtService; + private readonly AppDbContext _db; + + public AuthService( + UserManager userManager, + SignInManager signInManager, + IJwtService jwtService, + AppDbContext db) + { + _userManager = userManager; + _signInManager = signInManager; + _jwtService = jwtService; + _db = db; + } + + public async Task> RegisterAsync(RegisterRequest request, CancellationToken ct) + { + var existingUser = await _userManager.FindByEmailAsync(request.Email); + if (existingUser is not null) + return ServiceResult.Conflict("Email already registered"); + + var user = new AppUser + { + UserName = request.Email, + Email = request.Email, + DisplayName = request.DisplayName + }; + + var result = await _userManager.CreateAsync(user, request.Password); + if (!result.Succeeded) + return ServiceResult.Failure( + string.Join(", ", result.Errors.Select(e => e.Description))); + + await _userManager.AddToRoleAsync(user, AppRoles.Viewer); + + return await GenerateAuthResponseAsync(user, ct); + } + + public async Task> LoginAsync(LoginRequest request, CancellationToken ct) + { + var user = await _userManager.FindByEmailAsync(request.Email); + if (user is null) + return ServiceResult.Unauthorized("Invalid email or password"); + + if (await _userManager.IsLockedOutAsync(user)) + return ServiceResult.Failure("Account locked. Try again later.", 429); + + if (await _userManager.GetTwoFactorEnabledAsync(user)) + { + var signIn = await _signInManager.PasswordSignInAsync(user, request.Password, false, true); + if (signIn.IsLockedOut) + return ServiceResult.Failure("Account locked. Try again later.", 429); + if (!signIn.Succeeded) + return ServiceResult.Unauthorized("Invalid email or password"); + + return ServiceResult.Success(new AuthResponse( + string.Empty, string.Empty, DateTime.UtcNow, true, + await MapUserInfoAsync(user))); + } + + var result = await _signInManager.PasswordSignInAsync(user, request.Password, false, true); + if (!result.Succeeded) + return ServiceResult.Unauthorized("Invalid email or password"); + + return await GenerateAuthResponseAsync(user, ct); + } + + public async Task> Verify2faAsync(Verify2faRequest request, CancellationToken ct) + { + var user = await _userManager.FindByEmailAsync(request.Email); + if (user is null) + return ServiceResult.Unauthorized("Invalid request"); + + var isValid = await _userManager.VerifyTwoFactorTokenAsync( + user, TokenOptions.DefaultAuthenticatorProvider, request.Code); + + if (!isValid) + return ServiceResult.Unauthorized("Invalid 2FA code"); + + return await GenerateAuthResponseAsync(user, ct); + } + + public async Task> RefreshTokenAsync(string refreshToken, CancellationToken ct) + { + var principal = _jwtService.ValidateRefreshToken(refreshToken); + if (principal is null) + return ServiceResult.Unauthorized("Invalid or expired refresh token"); + + var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier); + if (userId is null) + return ServiceResult.Unauthorized("Invalid token"); + + var user = await _userManager.FindByIdAsync(userId); + if (user is null) + return ServiceResult.Unauthorized("User not found"); + + return await GenerateAuthResponseAsync(user, ct); + } + + public async Task Enable2faAsync(Guid userId, CancellationToken ct) + { + var user = await _userManager.FindByIdAsync(userId.ToString()); + if (user is null) + return ServiceResult.NotFound("User not found"); + + var result = await _userManager.SetTwoFactorEnabledAsync(user, true); + if (!result.Succeeded) + return ServiceResult.Failure("Failed to enable 2FA"); + + return ServiceResult.Success(); + } + + public async Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct) + { + await _signInManager.SignOutAsync(); + } + + private async Task> GenerateAuthResponseAsync(AppUser user, CancellationToken ct) + { + var roles = await _userManager.GetRolesAsync(user); + var permissions = roles.SelectMany(r => + AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : []).ToList(); + + var (accessToken, expiresAt) = _jwtService.GenerateAccessToken(user, roles, permissions); + var refreshToken = _jwtService.GenerateRefreshToken(); + + return ServiceResult.Success(new AuthResponse( + accessToken, + refreshToken, + expiresAt, + false, + await MapUserInfoAsync(user))); + } + + private async Task MapUserInfoAsync(AppUser user) + { + var roles = await _userManager.GetRolesAsync(user); + return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, roles); + } +} diff --git a/src/Heimdall.Infrastructure/Services/SiteService.cs b/src/Heimdall.Infrastructure/Services/SiteService.cs new file mode 100644 index 0000000..c0c0d26 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/SiteService.cs @@ -0,0 +1,116 @@ +using System.Security.Cryptography; +using System.Text; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +public class SiteService : ISiteService +{ + private readonly AppDbContext _db; + + public SiteService(AppDbContext db) => _db = db; + + public async Task> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct) + { + var existing = await _db.Sites.AnyAsync(s => s.Name == request.Name, ct); + if (existing) + return ServiceResult.Conflict("A site with this name already exists"); + + var site = new Site(request.Name, request.Address, request.Timezone); + _db.Sites.Add(site); + + // Generate registration token + var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken(); + site.GenerateRegistrationToken(tokenHash, expiresAt); + + await _db.SaveChangesAsync(ct); + + // Audit log + _db.AuditLogs.Add(new AuditLog(userId, "Site.Created", "Site", site.Id.ToString())); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success(new SiteWithTokenResponse( + site.Id, site.Name, site.Address, site.Timezone, + plainToken, expiresAt, site.CreatedAt)); + } + + public async Task> GetByIdAsync(Guid id, CancellationToken ct) + { + var site = await _db.Sites.FindAsync([id], ct); + if (site is null) + return ServiceResult.NotFound("Site not found"); + + return ServiceResult.Success(MapResponse(site)); + } + + public async Task>> ListAsync(int page, int pageSize, CancellationToken ct) + { + var query = _db.Sites.OrderBy(s => s.Name); + + var total = await query.CountAsync(ct); + var items = await query + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(s => MapResponse(s)) + .ToListAsync(ct); + + return ServiceResult>.Success( + new PagedResult(items, total, page, pageSize)); + } + + public async Task> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct) + { + var site = await _db.Sites.FindAsync([id], ct); + if (site is null) + return ServiceResult.NotFound("Site not found"); + + site.Update(request.Name, request.Address, request.Timezone); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success(MapResponse(site)); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct) + { + var site = await _db.Sites.FindAsync([id], ct); + if (site is null) + return ServiceResult.NotFound("Site not found"); + + site.SoftDelete(); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success(); + } + + public async Task> GenerateTokenAsync(Guid id, CancellationToken ct) + { + var site = await _db.Sites.FindAsync([id], ct); + if (site is null) + return ServiceResult.NotFound("Site not found"); + + var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken(); + site.GenerateRegistrationToken(tokenHash, expiresAt); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success( + new RegistrationTokenResponse(plainToken, expiresAt)); + } + + private static (string plainToken, string tokenHash, DateTime expiresAt) GenerateRegistrationToken() + { + var tokenBytes = new byte[32]; + RandomNumberGenerator.Fill(tokenBytes); + var plainToken = Convert.ToHexString(tokenBytes).ToLowerInvariant(); + var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainToken))).ToLowerInvariant(); + var expiresAt = DateTime.UtcNow.AddDays(1); + return (plainToken, tokenHash, expiresAt); + } + + private static SiteResponse MapResponse(Site s) => new( + s.Id, s.Name, s.Address, s.Timezone, s.Enabled, s.CreatedAt); +} diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 68a2e69..277f85f 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -5,6 +5,10 @@ + + + + net10.0 enable diff --git a/src/Heimdall.Workers/Heimdall.Workers.csproj b/src/Heimdall.Workers/Heimdall.Workers.csproj index 8d5e6bd..a6b0c47 100644 --- a/src/Heimdall.Workers/Heimdall.Workers.csproj +++ b/src/Heimdall.Workers/Heimdall.Workers.csproj @@ -8,6 +8,9 @@ + + + diff --git a/src/Heimdall.Workers/Jobs/HeartbeatMonitorJob.cs b/src/Heimdall.Workers/Jobs/HeartbeatMonitorJob.cs new file mode 100644 index 0000000..17b82b1 --- /dev/null +++ b/src/Heimdall.Workers/Jobs/HeartbeatMonitorJob.cs @@ -0,0 +1,44 @@ +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Workers.Jobs; + +/// +/// Marks agents as Offline if no heartbeat received for 90+ seconds. +/// Runs every minute via Hangfire recurring job. +/// +public class HeartbeatMonitorJob +{ + private readonly AppDbContext _db; + private readonly ILogger _logger; + + public HeartbeatMonitorJob(AppDbContext db, ILogger logger) + { + _db = db; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + var timeoutThreshold = DateTime.UtcNow.AddSeconds(-90); + + var staleAgents = await _db.Agents + .Where(a => a.Status == AgentStatus.Online + && a.LastHeartbeat != null + && a.LastHeartbeat < timeoutThreshold) + .ToListAsync(ct); + + if (staleAgents.Count == 0) + return; + + _logger.LogWarning("Marking {Count} agents as Offline (no heartbeat > 90s)", staleAgents.Count); + + foreach (var agent in staleAgents) + { + agent.MarkOffline(); + } + + await _db.SaveChangesAsync(ct); + } +} diff --git a/src/Heimdall.Workers/Program.cs b/src/Heimdall.Workers/Program.cs index 3f3f8b5..33d8561 100644 --- a/src/Heimdall.Workers/Program.cs +++ b/src/Heimdall.Workers/Program.cs @@ -1,7 +1,64 @@ -using Heimdall.Workers; +using Heimdall.Application; +using Heimdall.Infrastructure; +using Heimdall.Infrastructure.Data; +using Heimdall.Workers.Jobs; +using Hangfire; +using Hangfire.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; var builder = Host.CreateApplicationBuilder(args); -builder.Services.AddHostedService(); + +var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") + ?? builder.Configuration.GetConnectionString("Default") + ?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall"; + +// ── Infrastructure ──────────────────────────────────────────────── +builder.Services.AddInfrastructure(builder.Configuration); +builder.Services.AddApplication(); + +// ── Hangfire ────────────────────────────────────────────────────── +#pragma warning disable CS0618 +builder.Services.AddHangfire(config => +{ + config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions + { + SchemaName = "hangfire" + }); +}); +#pragma warning restore CS0618 + +builder.Services.AddHangfireServer(options => +{ + options.WorkerCount = 2; + options.Queues = ["default", "heartbeat"]; +}); + +// ── Jobs ────────────────────────────────────────────────────────── +builder.Services.AddScoped(); var host = builder.Build(); + +// Apply migrations +using (var scope = host.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + if (db.Database.GetPendingMigrations().Any()) + { + db.Database.Migrate(); + } +} + +// Register recurring jobs +using (var scope = host.Services.CreateScope()) +{ + var manager = scope.ServiceProvider.GetRequiredService(); + + manager.AddOrUpdate( + "heartbeat-monitor", + job => job.ExecuteAsync(CancellationToken.None), + "*/1 * * * *"); // Every minute +} + host.Run(); diff --git a/tests/Heimdall.Domain.Tests/Entities/AgentTests.cs b/tests/Heimdall.Domain.Tests/Entities/AgentTests.cs new file mode 100644 index 0000000..ded807b --- /dev/null +++ b/tests/Heimdall.Domain.Tests/Entities/AgentTests.cs @@ -0,0 +1,59 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Shouldly; + +namespace Heimdall.Domain.Tests.Entities; + +public class AgentTests +{ + [Fact] + public void Create_agent_should_set_properties() + { + var agent = new Agent(Guid.NewGuid(), "Agent-1", "host-1", "1.0.0"); + + agent.Id.ShouldNotBe(Guid.Empty); + agent.Name.ShouldBe("Agent-1"); + agent.Hostname.ShouldBe("host-1"); + agent.Version.ShouldBe("1.0.0"); + agent.Status.ShouldBe(AgentStatus.Offline); + } + + [Fact] + public void Register_should_set_online_status() + { + var agent = new Agent(Guid.NewGuid(), "Agent-1", "host-1", "1.0.0"); + + agent.Register("apikeyhash123", "prefix12"); + + agent.Status.ShouldBe(AgentStatus.Online); + agent.ApiKeyHash.ShouldBe("apikeyhash123"); + agent.ApiKeyPrefix.ShouldBe("prefix12"); + agent.LastHeartbeat.ShouldNotBeNull(); + } + + [Fact] + public void Update_heartbeat_should_update_timestamp() + { + var agent = new Agent(Guid.NewGuid(), "Agent-1", "host-1", "1.0.0"); + agent.Register("hash", "prefix"); + + var before = agent.LastHeartbeat!.Value; + Thread.Sleep(10); + + agent.UpdateHeartbeat("1.2.3.4"); + + (agent.LastHeartbeat!.Value > before).ShouldBeTrue(); + agent.PublicIp.ShouldBe("1.2.3.4"); + } + + [Fact] + public void Mark_offline_should_set_status() + { + var agent = new Agent(Guid.NewGuid(), "Agent-1", "host-1", "1.0.0"); + agent.Register("hash", "prefix"); + + agent.MarkOffline(); + + agent.Status.ShouldBe(AgentStatus.Offline); + } +} diff --git a/tests/Heimdall.Domain.Tests/Entities/CameraTests.cs b/tests/Heimdall.Domain.Tests/Entities/CameraTests.cs new file mode 100644 index 0000000..5351a3e --- /dev/null +++ b/tests/Heimdall.Domain.Tests/Entities/CameraTests.cs @@ -0,0 +1,42 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Shouldly; + +namespace Heimdall.Domain.Tests.Entities; + +public class CameraTests +{ + [Fact] + public void Create_camera_should_set_properties() + { + var siteId = Guid.NewGuid(); + var camera = new Camera(siteId, "Caméra Entrée", "rtsp://192.168.1.100:554/stream1"); + + camera.Id.ShouldNotBe(Guid.Empty); + camera.SiteId.ShouldBe(siteId); + camera.Name.ShouldBe("Caméra Entrée"); + camera.RtspUrl.ShouldBe("rtsp://192.168.1.100:554/stream1"); + camera.Status.ShouldBe(CameraStatus.Disabled); + } + + [Fact] + public void Assign_agent_should_set_agent_id() + { + var camera = new Camera(Guid.NewGuid(), "Camera-1"); + var agentId = Guid.NewGuid(); + + camera.AssignAgent(agentId); + + camera.AgentId.ShouldBe(agentId); + } + + [Fact] + public void Set_status_should_update_status() + { + var camera = new Camera(Guid.NewGuid(), "Camera-1"); + + camera.SetStatus(CameraStatus.Online); + + camera.Status.ShouldBe(CameraStatus.Online); + } +} diff --git a/tests/Heimdall.Domain.Tests/Entities/SiteTests.cs b/tests/Heimdall.Domain.Tests/Entities/SiteTests.cs new file mode 100644 index 0000000..49d7845 --- /dev/null +++ b/tests/Heimdall.Domain.Tests/Entities/SiteTests.cs @@ -0,0 +1,78 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Primitives; +using Shouldly; + +namespace Heimdall.Domain.Tests.Entities; + +public class SiteTests +{ + [Fact] + public void Create_site_should_set_properties() + { + var site = new Site("Entrepôt A", "Paris", "Europe/Paris"); + + site.Id.ShouldNotBe(Guid.Empty); + site.Name.ShouldBe("Entrepôt A"); + site.Address.ShouldBe("Paris"); + site.Timezone.ShouldBe("Europe/Paris"); + site.Enabled.ShouldBeTrue(); + } + + [Fact] + public void Create_site_should_default_timezone_to_UTC() + { + var site = new Site("Test Site"); + + site.Timezone.ShouldBe("UTC"); + } + + [Fact] + public void Update_site_should_change_properties() + { + var site = new Site("Old Name", "Old Address", "UTC"); + site.Update("New Name", "New Address", "Europe/London"); + + site.Name.ShouldBe("New Name"); + site.Address.ShouldBe("New Address"); + site.Timezone.ShouldBe("Europe/London"); + } + + [Fact] + public void Generate_registration_token_should_set_hash_and_expiry() + { + var site = new Site("Test Site"); + var hash = "abc123hash"; + var expiresAt = DateTime.UtcNow.AddDays(1); + + site.GenerateRegistrationToken(hash, expiresAt); + + site.RegistrationTokenHash.ShouldBe(hash); + site.TokenExpiresAt.ShouldBe(expiresAt); + } + + [Fact] + public void Soft_delete_should_set_deleted_flag() + { + var site = new Site("Test Site"); + + site.SoftDelete(); + + site.IsDeleted.ShouldBeTrue(); + site.DeletedAt.ShouldNotBeNull(); + } + + [Fact] + public void Two_sites_with_same_id_should_be_equal() + { + // Use Entity equality via reflection to set the same Id + var site1 = (Site)Activator.CreateInstance(typeof(Site), true)!; + var site2 = (Site)Activator.CreateInstance(typeof(Site), true)!; + + var idField = typeof(Entity) + .GetProperty("Id", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)!; + idField.SetValue(site1, Guid.Empty); + idField.SetValue(site2, Guid.Empty); + + site1.Equals(site2).ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj b/tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj index bce64de..c19cfa8 100644 --- a/tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj +++ b/tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj @@ -9,6 +9,7 @@ +