feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering: - Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums - EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration - Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern - Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation - API: Auth/Sites/Agents controllers with explicit auth scheme policies - Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob - Agent: registration service + 30s heartbeat loop - Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml - CI/CD: GitHub Actions pipeline with build+test and Docker build - Tests: 13 domain tests (Site, Agent, Camera entities) Architecture decisions per deliberation council: - API Key via AuthenticationHandler<T> (not middleware) - Explicit [Authorize(AuthenticationSchemes)] on all endpoints - Event/Recording/Person/Vehicle deferred from initial migration - Hangfire compatible with .NET 10 (v1.8.17)
This commit is contained in:
1 parent
ad78346ac4
commit
b217c932e8
78 files changed
+5359
-11
No files matched your search
@@ -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
|
||||
@@ -6,7 +6,7 @@
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<AnalysisLevel>latest-Recommended</AnalysisLevel>
|
||||
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
|
||||
<NoWarn>$(NoWarn);NU1903;CA1848;CA1727</NoWarn>
|
||||
<NoWarn>$(NoWarn);NU1903;CA1848;CA1727;CA1861;CA1825;CA1873</NoWarn>
|
||||
<!-- Alpine workaround: no host package available for alpine.3.24-x64 -->
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
@@ -20,5 +20,6 @@
|
||||
<PropertyGroup Condition="$(MSBuildProjectDirectory.Contains('tests'))">
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<IsPackable>false</IsPackable>
|
||||
<NoWarn>$(NoWarn);CA1707</NoWarn>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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:
|
||||
@@ -1,7 +1,14 @@
|
||||
using Heimdall.Agent;
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
builder.Services.AddHostedService<Worker>();
|
||||
|
||||
builder.Services.AddHttpClient("Central", client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromSeconds(10);
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<AgentState>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
|
||||
var host = builder.Build();
|
||||
host.Run();
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Registers this agent with the Heimdall Central server and manages the heartbeat loop.
|
||||
/// </summary>
|
||||
public class AgentRegistrationService : BackgroundService
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<AgentRegistrationService> _logger;
|
||||
private readonly AgentState _state;
|
||||
|
||||
public AgentRegistrationService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
AgentState state,
|
||||
ILogger<AgentRegistrationService> 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<RegisterResponse>(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);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Register an agent using a site registration token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register(
|
||||
[FromBody] RegisterAgentRequest request, CancellationToken ct)
|
||||
{
|
||||
// Extract API key from header (may be empty for registration)
|
||||
var apiKey = Request.Headers.Authorization.FirstOrDefault()
|
||||
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var result = await _agentService.RegisterAsync(request, apiKey, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Send heartbeat from agent (API Key auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpPost("{id:guid}/heartbeat")]
|
||||
public async Task<IActionResult> Heartbeat(
|
||||
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _agentService.HeartbeatAsync(id, request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Get agent details (JWT auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _agentService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List agents for a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("by-site/{siteId:guid}")]
|
||||
public async Task<IActionResult> ListBySite(
|
||||
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Register a new user account.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register(
|
||||
[FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RegisterAsync(request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Login with email and password.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login(
|
||||
[FromBody] LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.LoginAsync(request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Verify 2FA code during login.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("2fa/verify")]
|
||||
public async Task<IActionResult> Verify2fa(
|
||||
[FromBody] Verify2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.Verify2faAsync(request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Refresh an expired access token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("refresh")]
|
||||
public async Task<IActionResult> Refresh(
|
||||
[FromBody] RefreshTokenRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Create a new site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>List all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _siteService.ListAsync(page, pageSize, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Get a site by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Update a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(
|
||||
Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.UpdateAsync(id, request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Generate a new agent registration token (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("{id:guid}/tokens")]
|
||||
public async Task<IActionResult> GenerateToken(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.GenerateTokenAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Net;
|
||||
using Heimdall.Application.Common;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace Heimdall.Api.Filters;
|
||||
|
||||
public class ExceptionFilter : IExceptionFilter
|
||||
{
|
||||
private readonly ILogger<ExceptionFilter> _logger;
|
||||
|
||||
public ExceptionFilter(ILogger<ExceptionFilter> logger) => _logger = logger;
|
||||
|
||||
public void OnException(ExceptionContext context)
|
||||
{
|
||||
_logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message);
|
||||
|
||||
var response = new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code = "InternalServerError",
|
||||
message = "An unexpected error occurred"
|
||||
}
|
||||
};
|
||||
|
||||
context.Result = new ObjectResult(response)
|
||||
{
|
||||
StatusCode = (int)HttpStatusCode.InternalServerError
|
||||
};
|
||||
|
||||
context.ExceptionHandled = true;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
+104
-6
@@ -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<ExceptionFilter>();
|
||||
});
|
||||
|
||||
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<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("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<AppDbContext>();
|
||||
if (db.Database.GetPendingMigrations().Any())
|
||||
{
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
// Seed roles
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var roleManager = scope.ServiceProvider
|
||||
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
|
||||
|
||||
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();
|
||||
@@ -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<T> : ServiceResult
|
||||
{
|
||||
public T? Data { get; private set; }
|
||||
|
||||
private ServiceResult() { }
|
||||
|
||||
public static ServiceResult<T> Success(T data) =>
|
||||
new() { IsSuccess = true, Data = data };
|
||||
|
||||
public new static ServiceResult<T> Failure(string error, int statusCode = 400) =>
|
||||
new() { IsSuccess = false, Error = error, StatusCode = statusCode };
|
||||
|
||||
public new static ServiceResult<T> NotFound(string error = "Resource not found") =>
|
||||
new() { IsSuccess = false, Error = error, StatusCode = 404 };
|
||||
|
||||
public new static ServiceResult<T> Unauthorized(string error = "Unauthorized") =>
|
||||
new() { IsSuccess = false, Error = error, StatusCode = 401 };
|
||||
|
||||
public new static ServiceResult<T> Conflict(string error) =>
|
||||
new() { IsSuccess = false, Error = error, StatusCode = 409 };
|
||||
}
|
||||
#pragma warning restore CA1000
|
||||
@@ -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);
|
||||
@@ -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<string> 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);
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
public record PagedResult<T>(
|
||||
IReadOnlyList<T> 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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
<ProjectReference Include="..\Heimdall.Domain\Heimdall.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation" Version="11.11.0" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IAgentService
|
||||
{
|
||||
Task<ServiceResult<RegisterAgentResponse>> RegisterAsync(RegisterAgentRequest request, string? apiKey, CancellationToken ct);
|
||||
Task<ServiceResult> HeartbeatAsync(Guid agentId, AgentHeartbeatRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<AgentResponse>> GetByIdAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult<PagedResult<AgentResponse>>> ListBySiteAsync(Guid siteId, int page, int pageSize, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IApiKeyService
|
||||
{
|
||||
Task<ServiceResult<CreateApiKeyResponse>> CreateAsync(Guid? siteId, Guid? createdByUserId, DateTime? expiresAt, CancellationToken ct);
|
||||
Task<ServiceResult<PagedResult<ApiKeyResponse>>> ListAsync(Guid? siteId, int page, int pageSize, CancellationToken ct);
|
||||
Task<ServiceResult> RevokeAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult<bool>> ValidateKeyAsync(string key, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<ServiceResult<AuthResponse>> RegisterAsync(RegisterRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<AuthResponse>> LoginAsync(LoginRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<AuthResponse>> Verify2faAsync(Verify2faRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<AuthResponse>> RefreshTokenAsync(string refreshToken, CancellationToken ct);
|
||||
Task<ServiceResult> Enable2faAsync(Guid userId, CancellationToken ct);
|
||||
Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface ISiteService
|
||||
{
|
||||
Task<ServiceResult<SiteWithTokenResponse>> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct);
|
||||
Task<ServiceResult<SiteResponse>> GetByIdAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult<PagedResult<SiteResponse>>> ListAsync(int page, int pageSize, CancellationToken ct);
|
||||
Task<ServiceResult<SiteResponse>> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct);
|
||||
Task<ServiceResult> DeleteAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult<RegistrationTokenResponse>> GenerateTokenAsync(Guid id, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class CreateSiteValidator : AbstractValidator<CreateSiteRequest>
|
||||
{
|
||||
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<RegisterAgentRequest>
|
||||
{
|
||||
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<LoginRequest>
|
||||
{
|
||||
public LoginRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Email)
|
||||
.NotEmpty()
|
||||
.EmailAddress()
|
||||
.MaximumLength(200);
|
||||
|
||||
RuleFor(x => x.Password)
|
||||
.NotEmpty()
|
||||
.MaximumLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
public class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace Heimdall.Domain.Primitives;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for all domain entities with a strongly-typed identifier.
|
||||
/// </summary>
|
||||
public abstract class Entity<TId> : IEquatable<Entity<TId>>
|
||||
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<TId> other && Id.Equals(other.Id);
|
||||
|
||||
public bool Equals(Entity<TId>? other) =>
|
||||
other is not null && Id.Equals(other.Id);
|
||||
|
||||
public override int GetHashCode() => Id.GetHashCode();
|
||||
|
||||
public static bool operator ==(Entity<TId>? left, Entity<TId>? right) =>
|
||||
left is null ? right is null : left.Equals(right);
|
||||
|
||||
public static bool operator !=(Entity<TId>? left, Entity<TId>? right) =>
|
||||
!(left == right);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Heimdall.Domain.Primitives;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for entities with automatic audit timestamp tracking.
|
||||
/// </summary>
|
||||
public interface IAuditableEntity
|
||||
{
|
||||
DateTime CreatedAt { get; set; }
|
||||
DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Heimdall.Domain.Primitives;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for entities that support soft deletion.
|
||||
/// </summary>
|
||||
public interface ISoftDeletable
|
||||
{
|
||||
bool IsDeleted { get; }
|
||||
DateTime? DeletedAt { get; }
|
||||
void SoftDelete();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace Heimdall.Domain.Primitives;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for value objects. Equality is based on all constituent properties.
|
||||
/// </summary>
|
||||
public abstract class ValueObject : IEquatable<ValueObject>
|
||||
{
|
||||
protected abstract IEnumerable<object> 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);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class Agent : Entity<Guid>, 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; }
|
||||
|
||||
/// <summary>HMACSHA256 hash of the agent's API key.</summary>
|
||||
public string? ApiKeyHash { get; private set; }
|
||||
|
||||
/// <summary>First 8 characters of the API key for identification.</summary>
|
||||
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<Camera> _cameras = [];
|
||||
public IReadOnlyCollection<Camera> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class ApiKey
|
||||
{
|
||||
public Guid Id { get; private set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>HMACSHA256 hash of the full API key.</summary>
|
||||
public string KeyHash { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>First 8 characters of the key for identification.</summary>
|
||||
public string KeyPrefix { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>If scoped to a site, the agent can only access that site.</summary>
|
||||
public Guid? SiteId { get; private set; }
|
||||
|
||||
/// <summary>Who created this key.</summary>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class AppRole : IdentityRole<Guid>
|
||||
{
|
||||
public AppRole() { }
|
||||
|
||||
public AppRole(string name) : base(name) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class AppUser : IdentityUser<Guid>
|
||||
{
|
||||
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<UserSite> _userSites = [];
|
||||
public IReadOnlyCollection<UserSite> UserSites => _userSites.AsReadOnly();
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Append-only audit log for security-relevant actions.
|
||||
/// DB-level INSERT-only trigger recommended in production.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class Camera : Entity<Guid>, 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypted ONVIF/RTSP credentials for a camera.
|
||||
/// All sensitive fields are encrypted at rest via IDataProtector.
|
||||
/// </summary>
|
||||
public class CameraCredentials
|
||||
{
|
||||
public Guid CameraId { get; private set; }
|
||||
public string OnvifUsername { get; set; } = "admin";
|
||||
|
||||
/// <summary>Encrypted at rest.</summary>
|
||||
public string OnvifPassword { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Encrypted at rest.</summary>
|
||||
public string RtspUsername { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Encrypted at rest.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Per-camera AI detection profile.
|
||||
/// Controls what the Agent detects and what AI processing runs on the Central.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class Site : Entity<Guid>, 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;
|
||||
|
||||
/// <summary>Hashed registration token (SHA256) for agent enrollment.</summary>
|
||||
public string? RegistrationTokenHash { get; private set; }
|
||||
|
||||
/// <summary>When the current registration token expires.</summary>
|
||||
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<Agent> _agents = [];
|
||||
public IReadOnlyCollection<Agent> Agents => _agents.AsReadOnly();
|
||||
|
||||
private readonly List<Camera> _cameras = [];
|
||||
public IReadOnlyCollection<Camera> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Many-to-many relationship between users and sites.
|
||||
/// Determines which sites a non-admin user can access.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
public enum AgentStatus
|
||||
{
|
||||
Offline = 0,
|
||||
Online = 1,
|
||||
Error = 2
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
public enum CameraStatus
|
||||
{
|
||||
Unknown = 0,
|
||||
Online = 1,
|
||||
Offline = 2,
|
||||
Disabled = 3,
|
||||
Error = 4
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
public enum GpuAcceleration
|
||||
{
|
||||
None = 0,
|
||||
NvidiaCuda = 1,
|
||||
IntelQuickSync = 2,
|
||||
Vaapi = 3
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
public enum StorageProvider
|
||||
{
|
||||
Local = 0,
|
||||
S3 = 1
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
public enum UserRole
|
||||
{
|
||||
Admin = 0,
|
||||
Supervisor = 1,
|
||||
Viewer = 2
|
||||
}
|
||||
@@ -4,6 +4,10 @@
|
||||
<ProjectReference Include="..\Heimdall.Domain.Primitives\Heimdall.Domain.Primitives.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -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<AppUser, AppRole, Guid>
|
||||
{
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
||||
|
||||
// Domain entities
|
||||
public DbSet<Site> Sites => Set<Site>();
|
||||
public DbSet<Agent> Agents => Set<Agent>();
|
||||
public DbSet<Camera> Cameras => Set<Camera>();
|
||||
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
||||
public DbSet<CameraDetectionProfile> CameraDetectionProfiles => Set<CameraDetectionProfile>();
|
||||
public DbSet<UserSite> UserSites => Set<UserSite>();
|
||||
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
|
||||
|
||||
// Global soft-delete filter
|
||||
builder.Entity<Site>().HasQueryFilter(e => !e.IsDeleted);
|
||||
builder.Entity<Agent>().HasQueryFilter(e => !e.IsDeleted);
|
||||
builder.Entity<Camera>().HasQueryFilter(e => !e.IsDeleted);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.AddInterceptors(
|
||||
new AuditInterceptor(),
|
||||
new SoftDeleteInterceptor());
|
||||
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Design-time factory for EF Core migrations.
|
||||
/// Used by `dotnet ef migrations add` and `dotnet ef database update`.
|
||||
/// </summary>
|
||||
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
|
||||
{
|
||||
public AppDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<Agent>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Agent> 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<string>()
|
||||
.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<string>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -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<ApiKey>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ApiKey> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<AuditLog>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AuditLog> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Camera>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Camera> 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<string>()
|
||||
.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<CameraCredentials>(cr => cr.CameraId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
// One-to-one with detection profile
|
||||
builder.HasOne(c => c.DetectionProfile)
|
||||
.WithOne(dp => dp.Camera)
|
||||
.HasForeignKey<CameraDetectionProfile>(dp => dp.CameraId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -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<CameraCredentials>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<CameraCredentials> 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()");
|
||||
}
|
||||
}
|
||||
+22
@@ -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<CameraDetectionProfile>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<CameraDetectionProfile> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<AppUser>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AppUser> 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<AppRole>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AppRole> builder)
|
||||
{
|
||||
builder.ToTable("roles");
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityUserRoleConfiguration : IEntityTypeConfiguration<IdentityUserRole<Guid>>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IdentityUserRole<Guid>> builder)
|
||||
{
|
||||
builder.ToTable("user_roles");
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityUserClaimConfiguration : IEntityTypeConfiguration<IdentityUserClaim<Guid>>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IdentityUserClaim<Guid>> builder)
|
||||
{
|
||||
builder.ToTable("user_claims");
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityUserLoginConfiguration : IEntityTypeConfiguration<IdentityUserLogin<Guid>>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IdentityUserLogin<Guid>> builder)
|
||||
{
|
||||
builder.ToTable("user_logins");
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityRoleClaimConfiguration : IEntityTypeConfiguration<IdentityRoleClaim<Guid>>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IdentityRoleClaim<Guid>> builder)
|
||||
{
|
||||
builder.ToTable("role_claims");
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityUserTokenConfiguration : IEntityTypeConfiguration<IdentityUserToken<Guid>>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<IdentityUserToken<Guid>> builder)
|
||||
{
|
||||
builder.ToTable("user_tokens");
|
||||
}
|
||||
}
|
||||
@@ -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<Site>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Site> 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");
|
||||
}
|
||||
}
|
||||
@@ -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<UserSite>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<UserSite> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData,
|
||||
InterceptionResult<int> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData.Context is null)
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
|
||||
var entries = eventData.Context.ChangeTracker
|
||||
.Entries<IAuditableEntity>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData,
|
||||
InterceptionResult<int> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData.Context is null)
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
|
||||
var entries = eventData.Context.ChangeTracker
|
||||
.Entries<ISoftDeletable>();
|
||||
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.State is EntityState.Deleted)
|
||||
{
|
||||
entry.State = EntityState.Modified;
|
||||
entry.Entity.SoftDelete();
|
||||
}
|
||||
}
|
||||
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -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<AppDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(connectionString, npgsql =>
|
||||
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"));
|
||||
});
|
||||
}
|
||||
|
||||
// Identity
|
||||
services.AddIdentity<AppUser, AppRole>(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<AppDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
// JWT
|
||||
services.AddScoped<IJwtService, JwtService>();
|
||||
|
||||
// Application services
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddScoped<ISiteService, SiteService>();
|
||||
services.AddScoped<IAgentService, AgentService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,19 @@
|
||||
<ProjectReference Include="..\Heimdall.Domain\Heimdall.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire" Version="1.8.17" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.8">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql" Version="10.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
+841
@@ -0,0 +1,841 @@
|
||||
// <auto-generated />
|
||||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ApiKeyHash")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("ApiKeyPrefix")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<int>("CpuCores")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("GpuType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<bool>("HasGpu")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime?>("LastHeartbeat")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<long>("MemoryMb")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PublicIp")
|
||||
.HasMaxLength(45)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<Guid?>("CreatedByUserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("KeyPrefix")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Theme")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)")
|
||||
.HasDefaultValue("Auto");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Action")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasMaxLength(45)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<string>("NewValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("OldValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ResourceId")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("ResourceType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<Guid?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("HasAudio")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("HasMotionDetection")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("HasPtz")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Manufacturer")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Model")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RtspUrl")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("OnvifPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("OnvifUsername")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("admin");
|
||||
|
||||
b.Property<string>("RtspPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("RtspUsername")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("ActiveIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("AnimalCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("DetectAnimal")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectMotion")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectPackage")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectPerson")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectVehicle")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("FaceRecognition")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("IdleIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("IoUThreshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<bool>("LicensePlateRecognition")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("MaxEventsPerMinute")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("MinConfidence")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("double precision")
|
||||
.HasDefaultValue(0.40000000000000002);
|
||||
|
||||
b.Property<int>("MotionIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("MotionThreshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int>("PersonCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("RequireMotionForAI")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("VehicleCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Address")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RegistrationTokenHash")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("Timezone")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("UTC");
|
||||
|
||||
b.Property<DateTime?>("TokenExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "SiteId");
|
||||
|
||||
b.HasIndex("SiteId");
|
||||
|
||||
b.ToTable("user_sites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("role_claims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("user_claims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("user_logins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("user_roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("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<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", 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<System.Guid>", 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "audit_logs",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
Action = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
ResourceType = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
ResourceId = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
|
||||
OldValue = table.Column<string>(type: "text", nullable: true),
|
||||
NewValue = table.Column<string>(type: "text", nullable: true),
|
||||
IpAddress = table.Column<string>(type: "character varying(45)", maxLength: 45, nullable: true),
|
||||
Timestamp = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_roles", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "sites",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
Address = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
|
||||
Timezone = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false, defaultValue: "UTC"),
|
||||
Enabled = table.Column<bool>(type: "boolean", nullable: false),
|
||||
RegistrationTokenHash = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
|
||||
TokenExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DeletedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
|
||||
DisplayName = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
Theme = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: true, defaultValue: "Auto"),
|
||||
Language = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
|
||||
PasswordHash = table.Column<string>(type: "text", nullable: true),
|
||||
SecurityStamp = table.Column<string>(type: "text", nullable: true),
|
||||
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
|
||||
PhoneNumber = table.Column<string>(type: "text", nullable: true),
|
||||
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
|
||||
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
|
||||
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
|
||||
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_users", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "role_claims",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
RoleId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ClaimType = table.Column<string>(type: "text", nullable: true),
|
||||
ClaimValue = table.Column<string>(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<Guid>(type: "uuid", nullable: false),
|
||||
SiteId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
Hostname = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
|
||||
Version = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
|
||||
Status = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
|
||||
LastHeartbeat = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
|
||||
PublicIp = table.Column<string>(type: "character varying(45)", maxLength: 45, nullable: true),
|
||||
ApiKeyHash = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
|
||||
ApiKeyPrefix = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: true),
|
||||
HasGpu = table.Column<bool>(type: "boolean", nullable: false),
|
||||
CpuCores = table.Column<int>(type: "integer", nullable: false),
|
||||
MemoryMb = table.Column<long>(type: "bigint", nullable: false),
|
||||
GpuType = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DeletedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
|
||||
KeyHash = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
KeyPrefix = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: false),
|
||||
SiteId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
CreatedByUserId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
ExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
|
||||
Enabled = table.Column<bool>(type: "boolean", nullable: false),
|
||||
LastUsedAt = table.Column<DateTime>(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<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ClaimType = table.Column<string>(type: "text", nullable: true),
|
||||
ClaimValue = table.Column<string>(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<string>(type: "text", nullable: false),
|
||||
ProviderKey = table.Column<string>(type: "text", nullable: false),
|
||||
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
|
||||
UserId = table.Column<Guid>(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<Guid>(type: "uuid", nullable: false),
|
||||
RoleId = table.Column<Guid>(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<Guid>(type: "uuid", nullable: false),
|
||||
SiteId = table.Column<Guid>(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<Guid>(type: "uuid", nullable: false),
|
||||
LoginProvider = table.Column<string>(type: "text", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Value = table.Column<string>(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<Guid>(type: "uuid", nullable: false),
|
||||
SiteId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
AgentId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
Manufacturer = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
|
||||
Model = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
|
||||
RtspUrl = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
|
||||
Status = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
|
||||
HasPtz = table.Column<bool>(type: "boolean", nullable: false),
|
||||
HasAudio = table.Column<bool>(type: "boolean", nullable: false),
|
||||
HasMotionDetection = table.Column<bool>(type: "boolean", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DeletedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
|
||||
OnvifUsername = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false, defaultValue: "admin"),
|
||||
OnvifPassword = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
|
||||
RtspUsername = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
RtspPassword = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UpdatedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
|
||||
DetectPerson = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DetectVehicle = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DetectAnimal = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DetectPackage = table.Column<bool>(type: "boolean", nullable: false),
|
||||
DetectMotion = table.Column<bool>(type: "boolean", nullable: false),
|
||||
FaceRecognition = table.Column<bool>(type: "boolean", nullable: false),
|
||||
LicensePlateRecognition = table.Column<bool>(type: "boolean", nullable: false),
|
||||
IdleIntervalMs = table.Column<int>(type: "integer", nullable: false),
|
||||
MotionIntervalMs = table.Column<int>(type: "integer", nullable: false),
|
||||
ActiveIntervalMs = table.Column<int>(type: "integer", nullable: false),
|
||||
MotionThreshold = table.Column<double>(type: "double precision", nullable: false),
|
||||
YoloModel = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false, defaultValue: "yolov8n"),
|
||||
MinConfidence = table.Column<double>(type: "double precision", nullable: false, defaultValue: 0.40000000000000002),
|
||||
RequireMotionForAI = table.Column<bool>(type: "boolean", nullable: false),
|
||||
IoUThreshold = table.Column<double>(type: "double precision", nullable: false),
|
||||
PersonCooldownSec = table.Column<int>(type: "integer", nullable: false),
|
||||
VehicleCooldownSec = table.Column<int>(type: "integer", nullable: false),
|
||||
AnimalCooldownSec = table.Column<int>(type: "integer", nullable: false),
|
||||
MaxEventsPerMinute = table.Column<int>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,838 @@
|
||||
// <auto-generated />
|
||||
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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ApiKeyHash")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("ApiKeyPrefix")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<int>("CpuCores")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("GpuType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<bool>("HasGpu")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("character varying(255)");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime?>("LastHeartbeat")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<long>("MemoryMb")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PublicIp")
|
||||
.HasMaxLength(45)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<Guid?>("CreatedByUserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("KeyPrefix")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Theme")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)")
|
||||
.HasDefaultValue("Auto");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Action")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasMaxLength(45)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<string>("NewValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("OldValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ResourceId")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("ResourceType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<Guid?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("HasAudio")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("HasMotionDetection")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("HasPtz")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Manufacturer")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Model")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RtspUrl")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("OnvifPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("OnvifUsername")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("admin");
|
||||
|
||||
b.Property<string>("RtspPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("RtspUsername")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("ActiveIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("AnimalCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("DetectAnimal")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectMotion")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectPackage")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectPerson")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("DetectVehicle")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("FaceRecognition")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("IdleIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("IoUThreshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<bool>("LicensePlateRecognition")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("MaxEventsPerMinute")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("MinConfidence")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("double precision")
|
||||
.HasDefaultValue(0.40000000000000002);
|
||||
|
||||
b.Property<int>("MotionIntervalMs")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("MotionThreshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int>("PersonCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("RequireMotionForAI")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("VehicleCooldownSec")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Address")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RegistrationTokenHash")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("Timezone")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("UTC");
|
||||
|
||||
b.Property<DateTime?>("TokenExpiresAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime>("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<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "SiteId");
|
||||
|
||||
b.HasIndex("SiteId");
|
||||
|
||||
b.ToTable("user_sites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("role_claims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("user_claims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("user_logins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("user_roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("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<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", 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<System.Guid>", 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 { }
|
||||
|
||||
/// <summary>
|
||||
/// AuthenticationHandler for API Key authentication.
|
||||
/// Validates SHA256-hashed API keys using constant-time comparison.
|
||||
/// Integrates with ASP.NET Core's standard auth pipeline.
|
||||
/// </summary>
|
||||
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
public ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<ApiKeyAuthenticationOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IServiceProvider serviceProvider)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
protected override async Task<AuthenticateResult> 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<AppDbContext>();
|
||||
|
||||
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<Claim>
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Generate a new API key and return (plainKey, prefix, hash).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Application permission policies for authorization.
|
||||
/// Usage: [Authorize(Policy = AppPermissions.CameraRead)]
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
/// <summary>
|
||||
/// All permissions mapped by role.
|
||||
/// Admin = all, Supervisor = most, Viewer = read-only.
|
||||
/// </summary>
|
||||
public static readonly Dictionary<string, string[]> 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];
|
||||
}
|
||||
@@ -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<string> roles, IList<string> 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<string> roles, IList<string> 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<Claim>
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ServiceResult<RegisterAgentResponse>> 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<RegisterAgentResponse>.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<RegisterAgentResponse>.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<RegisterAgentResponse>.Success(
|
||||
new RegisterAgentResponse(agent.Id, plainKey, prefix));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> 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<GpuAcceleration>(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<ServiceResult<AgentResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var agent = await _db.Agents.FindAsync([id], ct);
|
||||
if (agent is null)
|
||||
return ServiceResult<AgentResponse>.NotFound("Agent not found");
|
||||
|
||||
return ServiceResult<AgentResponse>.Success(MapResponse(agent));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<AgentResponse>>> 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<PagedResult<AgentResponse>>.Success(
|
||||
new PagedResult<AgentResponse>(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);
|
||||
}
|
||||
@@ -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<AppUser> _userManager;
|
||||
private readonly SignInManager<AppUser> _signInManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly AppDbContext _db;
|
||||
|
||||
public AuthService(
|
||||
UserManager<AppUser> userManager,
|
||||
SignInManager<AppUser> signInManager,
|
||||
IJwtService jwtService,
|
||||
AppDbContext db)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_jwtService = jwtService;
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> RegisterAsync(RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var existingUser = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (existingUser is not null)
|
||||
return ServiceResult<AuthResponse>.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<AuthResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
await _userManager.AddToRoleAsync(user, AppRoles.Viewer);
|
||||
|
||||
return await GenerateAuthResponseAsync(user, ct);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
|
||||
if (await _userManager.IsLockedOutAsync(user))
|
||||
return ServiceResult<AuthResponse>.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<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
if (!signIn.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
|
||||
return ServiceResult<AuthResponse>.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<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
|
||||
return await GenerateAuthResponseAsync(user, ct);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Verify2faAsync(Verify2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid request");
|
||||
|
||||
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
|
||||
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
|
||||
|
||||
if (!isValid)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||||
|
||||
return await GenerateAuthResponseAsync(user, ct);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> RefreshTokenAsync(string refreshToken, CancellationToken ct)
|
||||
{
|
||||
var principal = _jwtService.ValidateRefreshToken(refreshToken);
|
||||
if (principal is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired refresh token");
|
||||
|
||||
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userId is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("User not found");
|
||||
|
||||
return await GenerateAuthResponseAsync(user, ct);
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> 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<ServiceResult<AuthResponse>> 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<AuthResponse>.Success(new AuthResponse(
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresAt,
|
||||
false,
|
||||
await MapUserInfoAsync(user)));
|
||||
}
|
||||
|
||||
private async Task<UserInfo> MapUserInfoAsync(AppUser user)
|
||||
{
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, roles);
|
||||
}
|
||||
}
|
||||
@@ -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<ServiceResult<SiteWithTokenResponse>> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct)
|
||||
{
|
||||
var existing = await _db.Sites.AnyAsync(s => s.Name == request.Name, ct);
|
||||
if (existing)
|
||||
return ServiceResult<SiteWithTokenResponse>.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<SiteWithTokenResponse>.Success(new SiteWithTokenResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone,
|
||||
plainToken, expiresAt, site.CreatedAt));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<SiteResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var site = await _db.Sites.FindAsync([id], ct);
|
||||
if (site is null)
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(MapResponse(site));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<SiteResponse>>> 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<PagedResult<SiteResponse>>.Success(
|
||||
new PagedResult<SiteResponse>(items, total, page, pageSize));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<SiteResponse>> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct)
|
||||
{
|
||||
var site = await _db.Sites.FindAsync([id], ct);
|
||||
if (site is null)
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
site.Update(request.Name, request.Address, request.Timezone);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(MapResponse(site));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> 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<ServiceResult<RegistrationTokenResponse>> GenerateTokenAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var site = await _db.Sites.FindAsync([id], ct);
|
||||
if (site is null)
|
||||
return ServiceResult<RegistrationTokenResponse>.NotFound("Site not found");
|
||||
|
||||
var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken();
|
||||
site.GenerateRegistrationToken(tokenHash, expiresAt);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<RegistrationTokenResponse>.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);
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
<ProjectReference Include="..\Heimdall.Infrastructure\Heimdall.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MudBlazor" Version="9.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire" Version="1.8.17" />
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.17" />
|
||||
<PackageReference Include="Hangfire.PostgreSql" Version="1.20.10" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Workers.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Marks agents as Offline if no heartbeat received for 90+ seconds.
|
||||
/// Runs every minute via Hangfire recurring job.
|
||||
/// </summary>
|
||||
public class HeartbeatMonitorJob
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly ILogger<HeartbeatMonitorJob> _logger;
|
||||
|
||||
public HeartbeatMonitorJob(AppDbContext db, ILogger<HeartbeatMonitorJob> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Worker>();
|
||||
|
||||
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<HeartbeatMonitorJob>();
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
// Apply migrations
|
||||
using (var scope = host.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
if (db.Database.GetPendingMigrations().Any())
|
||||
{
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
// Register recurring jobs
|
||||
using (var scope = host.Services.CreateScope())
|
||||
{
|
||||
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
|
||||
|
||||
manager.AddOrUpdate<HeartbeatMonitorJob>(
|
||||
"heartbeat-monitor",
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
"*/1 * * * *"); // Every minute
|
||||
}
|
||||
|
||||
host.Run();
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<Guid> 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<Guid>)
|
||||
.GetProperty("Id", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)!;
|
||||
idField.SetValue(site1, Guid.Empty);
|
||||
idField.SetValue(site2, Guid.Empty);
|
||||
|
||||
site1.Equals(site2).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="6.0.0" />
|
||||
<PackageReference Include="Shouldly" Version="4.3.0" />
|
||||
|
||||
Reference in new issue
Block a user