feat(mvp): complete MVP hardening — API, Web, config system, SignalR, tests
This commit is contained in:
1 parent
3fc42be4b2
commit
c2837af089
59 files changed
+4920
-81
No files matched your search
@@ -12,4 +12,8 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -40,6 +40,7 @@ builder.Services.AddSingleton<AgentState>(sp =>
|
||||
|
||||
builder.Services.AddSingleton<SystemMetricsProvider>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
builder.Services.AddHostedService<ConfigReceiverService>();
|
||||
|
||||
// Health checks — used by Docker HEALTHCHECK
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the Central SignalR ConfigHub to receive real-time configuration updates.
|
||||
/// When a setting changes, applies it locally and logs the change.
|
||||
/// Service will auto-reconnect on connection loss.
|
||||
/// </summary>
|
||||
public sealed class ConfigReceiverService : BackgroundService
|
||||
{
|
||||
private readonly AgentState _state;
|
||||
private readonly AgentOptions _options;
|
||||
private readonly ILogger<ConfigReceiverService> _logger;
|
||||
private HubConnection? _connection;
|
||||
|
||||
public ConfigReceiverService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
ILogger<ConfigReceiverService> logger)
|
||||
{
|
||||
_state = state;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
// Wait until the agent is registered (has an AgentId)
|
||||
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(1000, stoppingToken);
|
||||
}
|
||||
|
||||
if (stoppingToken.IsCancellationRequested) return;
|
||||
|
||||
var hubUrl = $"{_options.CentralUrl.TrimEnd('/')}/hubs/config";
|
||||
|
||||
_connection = new HubConnectionBuilder()
|
||||
.WithUrl(hubUrl, options =>
|
||||
{
|
||||
options.AccessTokenProvider = () => Task.FromResult(_state.ApiKey);
|
||||
})
|
||||
.WithAutomaticReconnect(new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)))
|
||||
.Build();
|
||||
|
||||
// Listen for setting changes
|
||||
_connection.On<string, string>("SettingChanged", (key, value) =>
|
||||
{
|
||||
_logger.LogInformation("Config update received: {Key} = {Value}", key, value);
|
||||
ApplySetting(key, value);
|
||||
});
|
||||
|
||||
// Listen for full reload signal
|
||||
_connection.On("ConfigReload", () =>
|
||||
{
|
||||
_logger.LogInformation("Full config reload requested, fetching from API...");
|
||||
_ = FetchFullConfigAsync(CancellationToken.None);
|
||||
});
|
||||
|
||||
// Reconnection events
|
||||
_connection.Reconnecting += _ =>
|
||||
{
|
||||
_logger.LogWarning("Config hub connection lost, reconnecting...");
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
_connection.Reconnected += async _ =>
|
||||
{
|
||||
_logger.LogInformation("Config hub reconnected, rejoining agent group...");
|
||||
try
|
||||
{
|
||||
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to rejoin agent group after reconnect");
|
||||
}
|
||||
};
|
||||
|
||||
// Retry loop for initial connection (auto-reconnect handles the rest)
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _connection.StartAsync(stoppingToken);
|
||||
_logger.LogInformation("Connected to config hub at {HubUrl}", hubUrl);
|
||||
|
||||
// Join our personal config channel
|
||||
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
|
||||
|
||||
// Fetch initial full config
|
||||
await FetchFullConfigAsync(stoppingToken);
|
||||
|
||||
// Keep service alive until cancellation — auto-reconnect handles reconnection
|
||||
await Task.Delay(Timeout.Infinite, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Config hub connection failed, retrying in 15s...");
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_connection is not null)
|
||||
{
|
||||
try { await _connection.DisposeAsync(); }
|
||||
catch { /* best effort */ }
|
||||
}
|
||||
await base.StopAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private void ApplySetting(string key, string value)
|
||||
{
|
||||
// Apply known settings locally
|
||||
switch (key)
|
||||
{
|
||||
case "heartbeat.interval.seconds":
|
||||
if (int.TryParse(value, out var interval) && interval >= 5)
|
||||
{
|
||||
// The heartbeat interval will be read from options on next heartbeat
|
||||
_logger.LogInformation("Heartbeat interval updated to {Interval}s (applied on next restart)", interval);
|
||||
}
|
||||
break;
|
||||
case "log.level":
|
||||
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
|
||||
break;
|
||||
default:
|
||||
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchFullConfigAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}");
|
||||
|
||||
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
|
||||
var response = await http.GetAsync(url, ct);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogInformation("Full configuration fetched successfully");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to fetch full configuration");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retry policy for SignalR reconnection with specific delays.
|
||||
/// </summary>
|
||||
internal sealed class RetryDelayed : IRetryPolicy
|
||||
{
|
||||
private readonly TimeSpan[] _delays;
|
||||
|
||||
public RetryDelayed(params TimeSpan[] delays) => _delays = delays;
|
||||
|
||||
public TimeSpan? NextRetryDelay(RetryContext context)
|
||||
{
|
||||
if (context.PreviousRetryCount < _delays.Length)
|
||||
return _delays[context.PreviousRetryCount];
|
||||
|
||||
// After exhausting specified delays, retry every 60 seconds
|
||||
return TimeSpan.FromSeconds(60);
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,13 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/agents")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class AgentsController : ControllerBase
|
||||
{
|
||||
private readonly IAgentService _agentService;
|
||||
@@ -17,6 +19,8 @@ public class AgentsController : ControllerBase
|
||||
/// <summary>Register an agent using a site registration token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Register(
|
||||
[FromBody] RegisterAgentRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -33,6 +37,8 @@ public class AgentsController : ControllerBase
|
||||
/// <summary>Send heartbeat from agent (API Key auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpPost("{id:guid}/heartbeat")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Heartbeat(
|
||||
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -45,6 +51,8 @@ public class AgentsController : ControllerBase
|
||||
/// <summary>Get agent details (JWT auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _agentService.GetByIdAsync(id, ct);
|
||||
@@ -56,10 +64,14 @@ public class AgentsController : ControllerBase
|
||||
/// <summary>List agents for a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("by-site/{siteId:guid}")]
|
||||
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ListBySite(
|
||||
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,24 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/audit-logs")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class AuditLogsController : ControllerBase
|
||||
{
|
||||
private readonly IAuditLogService _auditLogService;
|
||||
|
||||
public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService;
|
||||
|
||||
/// <summary>List audit log entries with optional filtering.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<AuditLogResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] string? resourceType,
|
||||
[FromQuery] string? action,
|
||||
@@ -24,6 +29,8 @@ public class AuditLogsController : ControllerBase
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,13 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
[EnableRateLimiting("Auth")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IAuthService _authService;
|
||||
@@ -19,8 +21,11 @@ public class AuthController : ControllerBase
|
||||
_env = env;
|
||||
}
|
||||
|
||||
/// <summary>Register a new user.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RegisterAsync(request, ct);
|
||||
@@ -29,8 +34,11 @@ public class AuthController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Authenticate a user.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.LoginAsync(request, ct);
|
||||
@@ -39,8 +47,11 @@ public class AuthController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Verify a 2FA code.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("2fa/verify")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.Verify2faAsync(request, ct);
|
||||
@@ -49,8 +60,11 @@ public class AuthController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Refresh an authentication token.</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("refresh")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
|
||||
@@ -62,6 +76,9 @@ public class AuthController : ControllerBase
|
||||
/// <summary>Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment())
|
||||
|
||||
@@ -3,19 +3,24 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/cameras")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class CamerasController : ControllerBase
|
||||
{
|
||||
private readonly ICameraService _cameraService;
|
||||
|
||||
public CamerasController(ICameraService cameraService) => _cameraService = cameraService;
|
||||
|
||||
/// <summary>Create a new camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateCameraRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.CreateAsync(request, ct);
|
||||
@@ -24,8 +29,11 @@ public class CamerasController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Get a camera by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.GetByIdAsync(id, ct);
|
||||
@@ -34,17 +42,26 @@ public class CamerasController : ControllerBase
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List cameras by site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("by-site/{siteId:guid}")]
|
||||
[ProducesResponseType(typeof(PagedResult<CameraResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ListBySite(
|
||||
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Update a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPut("{id:guid}")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.UpdateAsync(id, request, ct);
|
||||
@@ -53,8 +70,12 @@ public class CamerasController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _cameraService.DeleteAsync(id, ct);
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[AllowAnonymous]
|
||||
public class HealthController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Liveness probe — always returns OK if the process is running.
|
||||
/// </summary>
|
||||
[HttpGet("/healthz")]
|
||||
public IActionResult Health()
|
||||
{
|
||||
return Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
||||
}
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
||||
|
||||
/// <summary>
|
||||
/// Readiness probe — checks if the database is reachable.
|
||||
/// Uses ASP.NET Core health checks infrastructure.
|
||||
/// </summary>
|
||||
[HttpGet("/readyz")]
|
||||
public async Task<IActionResult> Readiness([FromServices] AppDbContext db)
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
|
||||
public async Task<IActionResult> Readiness(
|
||||
[FromServices] HealthCheckService healthCheckService,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var canConnect = await db.Database.CanConnectAsync();
|
||||
if (!canConnect)
|
||||
return StatusCode(503, new { status = "unhealthy", database = "disconnected" });
|
||||
var report = await healthCheckService.CheckHealthAsync(
|
||||
_ => true, ct);
|
||||
|
||||
return Ok(new { status = "ready", database = "connected" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(503, new { status = "unhealthy", database = ex.Message });
|
||||
}
|
||||
return report.Status == HealthStatus.Healthy
|
||||
? Ok(new { status = "healthy", timestamp = DateTime.UtcNow })
|
||||
: StatusCode(503, new { status = "unhealthy", errors = report.Entries });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Api.Hubs;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/settings")]
|
||||
[Authorize]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class SettingsController : ControllerBase
|
||||
{
|
||||
private readonly ISettingService _settingService;
|
||||
private readonly IConfigBroadcastService _broadcast;
|
||||
private readonly ILogger<SettingsController> _logger;
|
||||
|
||||
public SettingsController(
|
||||
ISettingService settingService,
|
||||
IConfigBroadcastService broadcast,
|
||||
ILogger<SettingsController> logger)
|
||||
{
|
||||
_settingService = settingService;
|
||||
_broadcast = broadcast;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>List all global settings (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(List<AppSettingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> ListAll(CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetAllSettingsAsync(ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Get a global setting by key (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("{key}")]
|
||||
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetByKey(string key, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetSettingByKeyAsync(key, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Create a new global setting (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Create(
|
||||
[FromBody] CreateAppSettingRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.CreateSettingAsync(request, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, result.Data.Value);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Update a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPut("{key}")]
|
||||
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(
|
||||
string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.UpdateSettingAsync(key, request, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, result.Data.Value);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Delete a global setting (Admin only). Broadcasts the change to all agents.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpDelete("{key}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(string key, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.DeleteSettingAsync(key, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyAllAgentsReload(ct);
|
||||
_logger.LogInformation("Deleted global setting {Key}", key);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the effective configuration for an agent: global defaults merged with
|
||||
/// per-agent overrides (Agent or Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("agent/{agentId:guid}")]
|
||||
[ProducesResponseType(typeof(Dictionary<string, string>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpGet("agent/{agentId:guid}/overrides")]
|
||||
[ProducesResponseType(typeof(List<AgentSettingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ListAgentOverrides(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.GetAgentSettingsAsync(agentId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set (create or update) a per-agent setting override (Admin only).
|
||||
/// Broadcasts the change to the affected agent in real-time.
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPut("agent/{agentId:guid}/overrides")]
|
||||
[ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SetAgentOverride(
|
||||
Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.SetAgentSettingAsync(agentId, request, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct);
|
||||
_logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}",
|
||||
agentId, result.Data.Key, result.Data.Value);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a per-agent setting override (Admin only).
|
||||
/// Broadcasts a reload notification to the affected agent.
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpDelete("agent/{agentId:guid}/overrides/{key}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> RemoveAgentOverride(Guid agentId, string key, CancellationToken ct)
|
||||
{
|
||||
var result = await _settingService.RemoveAgentSettingAsync(agentId, key, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct);
|
||||
_logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast a "ConfigReload" signal to all connected agents so they
|
||||
/// re-fetch their full configuration (Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost("reload")]
|
||||
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> ReloadAllAgents(CancellationToken ct)
|
||||
{
|
||||
await _broadcast.NotifyAllAgentsReload(ct);
|
||||
_logger.LogInformation("Broadcast ConfigReload to all agents");
|
||||
return Accepted(new { message = "Config reload broadcast to all connected agents" });
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,13 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/sites")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class SitesController : ControllerBase
|
||||
{
|
||||
private readonly ISiteService _siteService;
|
||||
@@ -18,10 +20,16 @@ public class SitesController : ControllerBase
|
||||
/// <summary>Create a new site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(SiteWithTokenResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Create(
|
||||
[FromBody] CreateSiteRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
var result = await _siteService.CreateAsync(request, userId, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
@@ -31,16 +39,22 @@ public class SitesController : ControllerBase
|
||||
/// <summary>List all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<SiteResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _siteService.ListAsync(page, pageSize, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Get a site by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.GetByIdAsync(id, ct);
|
||||
@@ -52,6 +66,9 @@ public class SitesController : ControllerBase
|
||||
/// <summary>Update a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPut("{id:guid}")]
|
||||
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(
|
||||
Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -64,6 +81,9 @@ public class SitesController : ControllerBase
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.DeleteAsync(id, ct);
|
||||
@@ -75,6 +95,9 @@ public class SitesController : ControllerBase
|
||||
/// <summary>Generate a new agent registration token (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("{id:guid}/tokens")]
|
||||
[ProducesResponseType(typeof(RegistrationTokenResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GenerateToken(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _siteService.GenerateTokenAsync(id, ct);
|
||||
|
||||
@@ -3,22 +3,29 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/stats")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class StatsController : ControllerBase
|
||||
{
|
||||
private readonly IStatsService _statsService;
|
||||
|
||||
public StatsController(IStatsService statsService) => _statsService = statsService;
|
||||
|
||||
/// <summary>Get system-wide statistics.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> GetStats(CancellationToken ct)
|
||||
{
|
||||
var result = await _statsService.GetStatsAsync(ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(new { data = result.Data, timestamp = DateTime.UtcNow });
|
||||
}
|
||||
}
|
||||
@@ -3,27 +3,37 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class UsersController : ControllerBase
|
||||
{
|
||||
private readonly IUserService _userService;
|
||||
|
||||
public UsersController(IUserService userService) => _userService = userService;
|
||||
|
||||
/// <summary>List all users (Admin only).</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<UserResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _userService.ListAsync(page, pageSize, ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Get a user by ID.</summary>
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.GetByIdAsync(id, ct);
|
||||
@@ -32,7 +42,10 @@ public class UsersController : ControllerBase
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Create a new user (Admin only).</summary>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.CreateAsync(request, ct);
|
||||
@@ -41,7 +54,11 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Update a user (Admin only).</summary>
|
||||
[HttpPut("{id:guid}")]
|
||||
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(
|
||||
Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -51,7 +68,10 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Assign roles to a user (Admin only).</summary>
|
||||
[HttpPut("{id:guid}/roles")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> AssignRoles(
|
||||
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -61,7 +81,10 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Assign sites to a user (Admin only).</summary>
|
||||
[HttpPut("{id:guid}/sites")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> AssignSites(
|
||||
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
|
||||
{
|
||||
@@ -71,7 +94,10 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Reset a user's password (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/reset-password")]
|
||||
[ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.ResetPasswordAsync(id, ct);
|
||||
@@ -80,7 +106,10 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Lock a user account (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/lock")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.LockAsync(id, ct);
|
||||
@@ -89,7 +118,10 @@ public class UsersController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Unlock a user account (Admin only).</summary>
|
||||
[HttpPost("{id:guid}/unlock")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.UnlockAsync(id, ct);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Api.Hubs;
|
||||
|
||||
/// <summary>
|
||||
/// SignalR hub for real-time configuration push to agents.
|
||||
/// Agents connect and receive config updates instantly when settings change.
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
public class ConfigHub : Hub
|
||||
{
|
||||
private readonly ILogger<ConfigHub> _logger;
|
||||
|
||||
public ConfigHub(ILogger<ConfigHub> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Agents call this on connect to join their personal config channel.
|
||||
/// The agentId comes from the authenticated API key's associated agent.
|
||||
/// </summary>
|
||||
public async Task JoinAgentGroup(string agentId)
|
||||
{
|
||||
if (!Guid.TryParse(agentId, out var _))
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Invalid agentId format");
|
||||
return;
|
||||
}
|
||||
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
|
||||
_logger.LogInformation("Agent {AgentId} joined config group", agentId);
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
_logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Service that broadcasts config changes to connected agents via SignalR.
|
||||
/// Called by the SettingService after any setting change.
|
||||
/// </summary>
|
||||
public interface IConfigBroadcastService
|
||||
{
|
||||
/// <summary>Notify all connected agents that a global setting changed.</summary>
|
||||
Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Notify a specific agent that one of its overrides changed.</summary>
|
||||
Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Notify all agents to reload their full configuration.</summary>
|
||||
Task NotifyAllAgentsReload(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts config changes to connected agents via SignalR.
|
||||
/// Injected as a scoped service; the HubContext is a singleton so broadcasting
|
||||
/// works safely across all connected clients.
|
||||
/// </summary>
|
||||
public class ConfigBroadcastService : IConfigBroadcastService
|
||||
{
|
||||
private readonly IHubContext<ConfigHub> _hubContext;
|
||||
private readonly ILogger<ConfigBroadcastService> _logger;
|
||||
|
||||
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger)
|
||||
{
|
||||
_hubContext = hubContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting global setting change: {Key} = {Value}", key, value);
|
||||
await _hubContext.Clients.All.SendAsync("SettingChanged", key, value, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key} = {Value}", agentId, key, value);
|
||||
await _hubContext.Clients.Group($"agent_{agentId}").SendAsync("SettingChanged", key, value, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogInformation("Broadcasting full config reload to all agents");
|
||||
await _hubContext.Clients.All.SendAsync("ConfigReload", ct);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Scalar.AspNetCore;
|
||||
using Heimdall.Api.Filters;
|
||||
using Heimdall.Application;
|
||||
using Heimdall.Infrastructure;
|
||||
using Heimdall.Api.Hubs;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
@@ -46,6 +47,9 @@ else
|
||||
builder.Services.AddControllers();
|
||||
}
|
||||
|
||||
builder.Services.AddSignalR();
|
||||
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
// ── Application layer ─────────────────────────────────────────────
|
||||
@@ -191,5 +195,6 @@ app.UseRateLimiter();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.MapHub<ConfigHub>("/hubs/config");
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// A global application setting visible to all agents unless overridden.
|
||||
/// </summary>
|
||||
public sealed record AppSettingDto(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("description")] string? Description,
|
||||
[property: JsonPropertyName("category")] string Category,
|
||||
[property: JsonPropertyName("valueType")] string ValueType,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues,
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Per-agent setting override.
|
||||
/// </summary>
|
||||
public sealed record AgentSettingDto(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("agentId")] Guid AgentId,
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Request to create a new global setting.
|
||||
/// </summary>
|
||||
public sealed record CreateAppSettingRequest(
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("category")] string Category = "General",
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("valueType")] string ValueType = "string",
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Request to update an existing global setting value.
|
||||
/// </summary>
|
||||
public sealed record UpdateAppSettingRequest(
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("category")] string? Category = null,
|
||||
[property: JsonPropertyName("valueType")] string? ValueType = null,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Request to set a per-agent setting override.
|
||||
/// </summary>
|
||||
public sealed record SetAgentSettingRequest(
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Manages global settings and per-agent setting overrides.
|
||||
/// All changes are broadcast to connected agents via SignalR in real-time.
|
||||
/// </summary>
|
||||
public interface ISettingService
|
||||
{
|
||||
// Global settings
|
||||
Task<ServiceResult<List<AppSettingDto>>> GetAllSettingsAsync(CancellationToken ct = default);
|
||||
Task<ServiceResult<AppSettingDto>> GetSettingByKeyAsync(string key, CancellationToken ct = default);
|
||||
Task<ServiceResult<AppSettingDto>> CreateSettingAsync(CreateAppSettingRequest request, CancellationToken ct = default);
|
||||
Task<ServiceResult<AppSettingDto>> UpdateSettingAsync(string key, UpdateAppSettingRequest request, CancellationToken ct = default);
|
||||
Task<ServiceResult> DeleteSettingAsync(string key, CancellationToken ct = default);
|
||||
|
||||
// Agent-specific overrides
|
||||
Task<ServiceResult<List<AgentSettingDto>>> GetAgentSettingsAsync(Guid agentId, CancellationToken ct = default);
|
||||
Task<ServiceResult<AgentSettingDto>> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request, CancellationToken ct = default);
|
||||
Task<ServiceResult> RemoveAgentSettingAsync(Guid agentId, string key, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the effective configuration for an agent: global defaults merged with
|
||||
/// per-agent overrides. Used by agents to fetch their full config on connect.
|
||||
/// </summary>
|
||||
Task<ServiceResult<Dictionary<string, string>>> GetEffectiveAgentConfigAsync(Guid agentId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class CreateAppSettingValidator : AbstractValidator<CreateAppSettingRequest>
|
||||
{
|
||||
public CreateAppSettingValidator()
|
||||
{
|
||||
RuleFor(x => x.Key).NotEmpty().MaximumLength(200)
|
||||
.Matches(@"^[a-z0-9][a-z0-9._-]*[a-z0-9]$")
|
||||
.WithMessage("Key must start and end with a lowercase alphanumeric character, and contain only lowercase letters, digits, dots, hyphens, or underscores");
|
||||
RuleFor(x => x.Value).NotNull();
|
||||
RuleFor(x => x.Category).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.ValueType).Must(t => t is "string" or "int" or "bool" or "double" or "select")
|
||||
.WithMessage("ValueType must be one of: string, int, bool, double, select");
|
||||
}
|
||||
}
|
||||
|
||||
public class UpdateAppSettingValidator : AbstractValidator<UpdateAppSettingRequest>
|
||||
{
|
||||
public UpdateAppSettingValidator()
|
||||
{
|
||||
RuleFor(x => x.Value).NotEmpty();
|
||||
When(x => x.Category is not null, () =>
|
||||
RuleFor(x => x.Category!).MaximumLength(100));
|
||||
When(x => x.ValueType is not null, () =>
|
||||
RuleFor(x => x.ValueType!).Must(t => t is "string" or "int" or "bool" or "double" or "select")
|
||||
.WithMessage("ValueType must be one of: string, int, bool, double, select"));
|
||||
}
|
||||
}
|
||||
|
||||
public class SetAgentSettingValidator : AbstractValidator<SetAgentSettingRequest>
|
||||
{
|
||||
public SetAgentSettingValidator()
|
||||
{
|
||||
RuleFor(x => x.Key).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.Value).NotNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class CreateCameraValidator : AbstractValidator<CreateCameraRequest>
|
||||
{
|
||||
public CreateCameraValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
|
||||
.WithMessage("RTSP URL must be a valid absolute URI");
|
||||
RuleFor(x => x.SiteId).NotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ public class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
||||
|
||||
RuleFor(x => x.Password)
|
||||
.NotEmpty()
|
||||
.MinimumLength(8)
|
||||
.MinimumLength(12)
|
||||
.MaximumLength(200);
|
||||
|
||||
RuleFor(x => x.DisplayName)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class CreateUserValidator : AbstractValidator<CreateUserRequest>
|
||||
{
|
||||
public CreateUserValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Password).NotEmpty().MinimumLength(12)
|
||||
.WithMessage("Password must be at least 12 characters");
|
||||
When(x => x.Roles is not null, () =>
|
||||
RuleFor(x => x.Roles!)
|
||||
.Must(roles => roles.All(r => r is "Admin" or "Supervisor" or "Viewer"))
|
||||
.WithMessage("Roles must be Admin, Supervisor, or Viewer"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class UpdateCameraValidator : AbstractValidator<UpdateCameraRequest>
|
||||
{
|
||||
public UpdateCameraValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
|
||||
.WithMessage("RTSP URL must be a valid absolute URI");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class UpdateSiteValidator : AbstractValidator<UpdateSiteRequest>
|
||||
{
|
||||
public UpdateSiteValidator()
|
||||
{
|
||||
When(x => x.Name is not null, () =>
|
||||
RuleFor(x => x.Name!).MaximumLength(200));
|
||||
When(x => x.Address is not null, () =>
|
||||
RuleFor(x => x.Address!).MaximumLength(500));
|
||||
When(x => x.Timezone is not null, () =>
|
||||
RuleFor(x => x.Timezone!).MaximumLength(100));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using FluentValidation;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Validators;
|
||||
|
||||
public class UpdateUserValidator : AbstractValidator<UpdateUserRequest>
|
||||
{
|
||||
public UpdateUserValidator()
|
||||
{
|
||||
When(x => x.DisplayName is not null, () =>
|
||||
RuleFor(x => x.DisplayName!).MaximumLength(100));
|
||||
When(x => x.Theme is not null, () =>
|
||||
RuleFor(x => x.Theme!).Must(t => t is "light" or "dark")
|
||||
.WithMessage("Theme must be 'light' or 'dark'"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Global application setting (key-value). Stored in DB and pushed to all agents
|
||||
/// in real-time via SignalR. Overridable per-agent via AgentSetting.
|
||||
/// </summary>
|
||||
public class AppSetting
|
||||
{
|
||||
public Guid Id { get; private set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>Unique setting key (e.g. "heartbeat.interval.seconds", "log.level", "ai.detection.enabled").</summary>
|
||||
public string Key { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Setting value as a JSON-serializable string.</summary>
|
||||
public string Value { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Human-readable description of what this setting controls.</summary>
|
||||
public string? Description { get; private set; }
|
||||
|
||||
/// <summary>Category for UI grouping (e.g. "Heartbeat", "Logging", "AI", "Recording").</summary>
|
||||
public string Category { get; private set; } = "General";
|
||||
|
||||
/// <summary>Value type hint for UI rendering ("string", "int", "bool", "double", "select").</summary>
|
||||
public string ValueType { get; private set; } = "string";
|
||||
|
||||
/// <summary>For select types, comma-separated allowed values.</summary>
|
||||
public string? AllowedValues { get; private set; }
|
||||
|
||||
public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
private AppSetting() { } // EF Core
|
||||
|
||||
public AppSetting(string key, string value, string category = "General", string? description = null)
|
||||
{
|
||||
Key = !string.IsNullOrWhiteSpace(key) ? key.Trim().ToLowerInvariant()
|
||||
: throw new ArgumentException("Key is required", nameof(key));
|
||||
Value = value ?? string.Empty;
|
||||
Category = category;
|
||||
Description = description;
|
||||
}
|
||||
|
||||
public void UpdateValue(string value)
|
||||
{
|
||||
Value = value ?? string.Empty;
|
||||
UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public void UpdateMetadata(string? description, string? category, string? valueType, string? allowedValues)
|
||||
{
|
||||
if (description is not null) Description = description;
|
||||
if (category is not null) Category = category;
|
||||
if (valueType is not null) ValueType = valueType;
|
||||
if (allowedValues is not null) AllowedValues = allowedValues;
|
||||
UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-agent setting override. Takes precedence over AppSetting for a specific agent.
|
||||
/// When created/updated, a SignalR notification is sent to the affected agent.
|
||||
/// </summary>
|
||||
public class AgentSetting
|
||||
{
|
||||
public Guid Id { get; private set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>Foreign key to the Agent this setting applies to.</summary>
|
||||
public Guid AgentId { get; private set; }
|
||||
|
||||
/// <summary>Setting key (same namespace as AppSetting keys).</summary>
|
||||
public string Key { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>Override value for this specific agent.</summary>
|
||||
public string Value { get; private set; } = string.Empty;
|
||||
|
||||
public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
// Navigation
|
||||
public Agent Agent { get; private set; } = null!;
|
||||
|
||||
private AgentSetting() { } // EF Core
|
||||
|
||||
public AgentSetting(Guid agentId, string key, string value)
|
||||
{
|
||||
AgentId = agentId;
|
||||
Key = !string.IsNullOrWhiteSpace(key) ? key.Trim().ToLowerInvariant()
|
||||
: throw new ArgumentException("Key is required", nameof(key));
|
||||
Value = value ?? string.Empty;
|
||||
}
|
||||
|
||||
public void UpdateValue(string value)
|
||||
{
|
||||
Value = value ?? string.Empty;
|
||||
UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
|
||||
public DbSet<UserSite> UserSites => Set<UserSite>();
|
||||
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
|
||||
public DbSet<AppSetting> AppSettings => Set<AppSetting>();
|
||||
public DbSet<AgentSetting> AgentSettings => Set<AgentSetting>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class AppSettingConfiguration : IEntityTypeConfiguration<AppSetting>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AppSetting> builder)
|
||||
{
|
||||
builder.ToTable("app_settings");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.HasIndex(x => x.Key).IsUnique();
|
||||
builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
|
||||
builder.Property(x => x.Value).IsRequired().HasColumnName("value");
|
||||
builder.Property(x => x.Description).HasMaxLength(500).HasColumnName("description");
|
||||
builder.Property(x => x.Category).IsRequired().HasMaxLength(100).HasColumnName("category");
|
||||
builder.Property(x => x.ValueType).IsRequired().HasMaxLength(50).HasColumnName("value_type");
|
||||
builder.Property(x => x.AllowedValues).HasMaxLength(2000).HasColumnName("allowed_values");
|
||||
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
|
||||
builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
|
||||
}
|
||||
}
|
||||
|
||||
public class AgentSettingConfiguration : IEntityTypeConfiguration<AgentSetting>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AgentSetting> builder)
|
||||
{
|
||||
builder.ToTable("agent_settings");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.HasIndex(x => new { x.AgentId, x.Key }).IsUnique();
|
||||
builder.Property(x => x.AgentId).IsRequired().HasColumnName("agent_id");
|
||||
builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
|
||||
builder.Property(x => x.Value).IsRequired().HasColumnName("value");
|
||||
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
|
||||
builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
|
||||
|
||||
builder.HasOne(x => x.Agent)
|
||||
.WithMany()
|
||||
.HasForeignKey(x => x.AgentId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,7 @@ public static class DependencyInjection
|
||||
services.AddScoped<ICameraService, CameraService>();
|
||||
services.AddScoped<IStatsService, StatsService>();
|
||||
services.AddScoped<IAuditLogService, AuditLogService>();
|
||||
services.AddScoped<ISettingService, SettingService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
+985
@@ -0,0 +1,985 @@
|
||||
// <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("20260718143003_AddAppSettings")]
|
||||
partial class AddAppSettings
|
||||
{
|
||||
/// <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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("ApiKeyPrefix")
|
||||
.HasMaxLength(8)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<bool>("HasGpu")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PublicIp")
|
||||
.HasMaxLength(45)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.IsUnicode(false)
|
||||
.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.AgentSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("agent_id");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("agent_settings", (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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("KeyPrefix")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.IsUnicode(false)
|
||||
.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.AppSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AllowedValues")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)")
|
||||
.HasColumnName("allowed_values");
|
||||
|
||||
b.Property<string>("Category")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("category");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.Property<string>("ValueType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("value_type");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("app_settings", (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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("MustChangePassword")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
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)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasMaxLength(45)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<string>("NewValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("OldValue")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ResourceId")
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("ResourceType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RtspUrl")
|
||||
.HasMaxLength(1000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("OnvifUsername")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("admin");
|
||||
|
||||
b.Property<string>("RtspPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("RtspUsername")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.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)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("Timezone")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.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.AgentSetting", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
|
||||
.WithMany()
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
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.AuditLog", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
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,78 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddAppSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "agent_settings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
agent_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
value = table.Column<string>(type: "text", nullable: false),
|
||||
created_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
updated_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_agent_settings", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_agent_settings_agents_agent_id",
|
||||
column: x => x.agent_id,
|
||||
principalTable: "agents",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "app_settings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||
value = table.Column<string>(type: "text", nullable: false),
|
||||
description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
|
||||
category = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
value_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
|
||||
allowed_values = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: true),
|
||||
created_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
updated_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_app_settings", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_agent_settings_agent_id_key",
|
||||
table: "agent_settings",
|
||||
columns: new[] { "agent_id", "key" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_app_settings_key",
|
||||
table: "app_settings",
|
||||
column: "key",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "agent_settings");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "app_settings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,10 +30,12 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.Property<string>("ApiKeyHash")
|
||||
.HasMaxLength(128)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("ApiKeyPrefix")
|
||||
.HasMaxLength(8)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<int>("CpuCores")
|
||||
@@ -50,6 +52,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("GpuType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<bool>("HasGpu")
|
||||
@@ -58,6 +61,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(255)");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
@@ -72,10 +76,12 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("PublicIp")
|
||||
.HasMaxLength(45)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
@@ -84,6 +90,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
@@ -94,6 +101,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
@@ -106,6 +114,43 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("agents", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("agent_id");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("agent_settings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -129,11 +174,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("KeyPrefix")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
@@ -180,6 +227,61 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AllowedValues")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)")
|
||||
.HasColumnName("allowed_values");
|
||||
|
||||
b.Property<string>("Category")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("category");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.Property<string>("ValueType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasColumnName("value_type");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("app_settings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -214,6 +316,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(10)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
@@ -251,6 +354,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Theme")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)")
|
||||
.HasDefaultValue("Auto");
|
||||
|
||||
@@ -282,10 +386,12 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Action")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasMaxLength(45)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(45)");
|
||||
|
||||
b.Property<string>("NewValue")
|
||||
@@ -296,11 +402,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.Property<string>("ResourceId")
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("ResourceType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
@@ -364,10 +472,12 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("RtspUrl")
|
||||
.HasMaxLength(1000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(1000)");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
@@ -376,6 +486,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
@@ -405,23 +516,27 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("OnvifPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("OnvifUsername")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("admin");
|
||||
|
||||
b.Property<string>("RtspPassword")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("RtspUsername")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
@@ -499,6 +614,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(50)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(50)")
|
||||
.HasDefaultValue("yolov8n");
|
||||
|
||||
@@ -538,12 +654,14 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.Property<string>("RegistrationTokenHash")
|
||||
.HasMaxLength(128)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("Timezone")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasDefaultValue("UTC");
|
||||
|
||||
@@ -694,6 +812,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Site");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
|
||||
.WithMany()
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Manages global application settings and per-agent setting overrides.
|
||||
/// </summary>
|
||||
public class SettingService : ISettingService
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly ILogger<SettingService> _logger;
|
||||
|
||||
public SettingService(AppDbContext db, ILogger<SettingService> logger)
|
||||
{
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// ────────────────────────────── Global Settings ──────────────────────────────
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<List<AppSettingDto>>> GetAllSettingsAsync(CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = await _db.AppSettings
|
||||
.OrderBy(s => s.Category)
|
||||
.ThenBy(s => s.Key)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return ServiceResult<List<AppSettingDto>>.Success(
|
||||
settings.Select(MapToDto).ToList());
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<List<AppSettingDto>>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to retrieve all app settings");
|
||||
return ServiceResult<List<AppSettingDto>>.Failure("An error occurred while retrieving settings");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<AppSettingDto>> GetSettingByKeyAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var setting = await _db.AppSettings
|
||||
.FirstOrDefaultAsync(s => s.Key == key, ct);
|
||||
|
||||
if (setting is null)
|
||||
{
|
||||
_logger.LogWarning("Setting '{Key}' not found", key);
|
||||
return ServiceResult<AppSettingDto>.NotFound($"Setting '{key}' not found");
|
||||
}
|
||||
|
||||
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to retrieve setting '{Key}'", key);
|
||||
return ServiceResult<AppSettingDto>.Failure("An error occurred while retrieving the setting");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<AppSettingDto>> CreateSettingAsync(CreateAppSettingRequest request, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = request.Key.Trim().ToLowerInvariant();
|
||||
|
||||
var exists = await _db.AppSettings.AnyAsync(s => s.Key == key, ct);
|
||||
if (exists)
|
||||
{
|
||||
_logger.LogWarning("Attempted to create duplicate setting '{Key}'", key);
|
||||
return ServiceResult<AppSettingDto>.Conflict($"Setting '{key}' already exists");
|
||||
}
|
||||
|
||||
var setting = new AppSetting(key, request.Value, request.Category, request.Description);
|
||||
// Apply optional metadata not covered by the constructor
|
||||
setting.UpdateMetadata(null, null, request.ValueType, request.AllowedValues);
|
||||
|
||||
_db.AppSettings.Add(setting);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogInformation("Created setting '{Key}' in category '{Category}'", key, request.Category);
|
||||
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to create setting '{Key}'", request.Key);
|
||||
return ServiceResult<AppSettingDto>.Failure("An error occurred while creating the setting");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<AppSettingDto>> UpdateSettingAsync(string key, UpdateAppSettingRequest request, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var setting = await _db.AppSettings
|
||||
.FirstOrDefaultAsync(s => s.Key == key, ct);
|
||||
|
||||
if (setting is null)
|
||||
{
|
||||
_logger.LogWarning("Attempted to update non-existent setting '{Key}'", key);
|
||||
return ServiceResult<AppSettingDto>.NotFound($"Setting '{key}' not found");
|
||||
}
|
||||
|
||||
setting.UpdateValue(request.Value);
|
||||
setting.UpdateMetadata(request.Description, request.Category, request.ValueType, request.AllowedValues);
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogInformation("Updated setting '{Key}'", key);
|
||||
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to update setting '{Key}'", key);
|
||||
return ServiceResult<AppSettingDto>.Failure("An error occurred while updating the setting");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult> DeleteSettingAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var setting = await _db.AppSettings
|
||||
.FirstOrDefaultAsync(s => s.Key == key, ct);
|
||||
|
||||
if (setting is null)
|
||||
{
|
||||
_logger.LogWarning("Attempted to delete non-existent setting '{Key}'", key);
|
||||
return ServiceResult.NotFound($"Setting '{key}' not found");
|
||||
}
|
||||
|
||||
_db.AppSettings.Remove(setting);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogInformation("Deleted setting '{Key}'", key);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to delete setting '{Key}'", key);
|
||||
return ServiceResult.Failure("An error occurred while deleting the setting");
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Agent-Specific Overrides ────────────────────────────
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<List<AgentSettingDto>>> GetAgentSettingsAsync(Guid agentId, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = await _db.AgentSettings
|
||||
.Where(s => s.AgentId == agentId)
|
||||
.OrderBy(s => s.Key)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return ServiceResult<List<AgentSettingDto>>.Success(
|
||||
settings.Select(MapToAgentDto).ToList());
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<List<AgentSettingDto>>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to retrieve settings for agent {AgentId}", agentId);
|
||||
return ServiceResult<List<AgentSettingDto>>.Failure("An error occurred while retrieving agent settings");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<AgentSettingDto>> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = request.Key.Trim().ToLowerInvariant();
|
||||
|
||||
var existing = await _db.AgentSettings
|
||||
.FirstOrDefaultAsync(s => s.AgentId == agentId && s.Key == key, ct);
|
||||
|
||||
if (existing is not null)
|
||||
{
|
||||
existing.UpdateValue(request.Value);
|
||||
_logger.LogInformation("Updated agent setting '{Key}' for agent {AgentId}", key, agentId);
|
||||
}
|
||||
else
|
||||
{
|
||||
existing = new AgentSetting(agentId, key, request.Value);
|
||||
_db.AgentSettings.Add(existing);
|
||||
_logger.LogInformation("Created agent setting '{Key}' for agent {AgentId}", key, agentId);
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<AgentSettingDto>.Success(MapToAgentDto(existing));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<AgentSettingDto>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to set agent setting '{Key}' for agent {AgentId}", request.Key, agentId);
|
||||
return ServiceResult<AgentSettingDto>.Failure("An error occurred while setting the agent setting");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult> RemoveAgentSettingAsync(Guid agentId, string key, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var setting = await _db.AgentSettings
|
||||
.FirstOrDefaultAsync(s => s.AgentId == agentId && s.Key == key, ct);
|
||||
|
||||
if (setting is null)
|
||||
{
|
||||
_logger.LogWarning("Attempted to remove non-existent agent setting '{Key}' for agent {AgentId}", key, agentId);
|
||||
return ServiceResult.NotFound($"Agent setting '{key}' not found for agent {agentId}");
|
||||
}
|
||||
|
||||
_db.AgentSettings.Remove(setting);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogInformation("Removed agent setting '{Key}' for agent {AgentId}", key, agentId);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to remove agent setting '{Key}' for agent {AgentId}", key, agentId);
|
||||
return ServiceResult.Failure("An error occurred while removing the agent setting");
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Effective Config (Merge) ────────────────────────────
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ServiceResult<Dictionary<string, string>>> GetEffectiveAgentConfigAsync(Guid agentId, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Load all global app settings as the base configuration
|
||||
var appSettings = await _db.AppSettings.ToListAsync(ct);
|
||||
var config = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var s in appSettings)
|
||||
{
|
||||
config[s.Key] = s.Value;
|
||||
}
|
||||
|
||||
// Load agent-specific overrides and overlay them
|
||||
var agentSettings = await _db.AgentSettings
|
||||
.Where(s => s.AgentId == agentId)
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var s in agentSettings)
|
||||
{
|
||||
config[s.Key] = s.Value;
|
||||
}
|
||||
|
||||
return ServiceResult<Dictionary<string, string>>.Success(config);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return ServiceResult<Dictionary<string, string>>.Failure("Operation was cancelled");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to compute effective config for agent {AgentId}", agentId);
|
||||
return ServiceResult<Dictionary<string, string>>.Failure("An error occurred while computing the effective configuration");
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Mapping Helpers ────────────────────────────
|
||||
|
||||
private static AppSettingDto MapToDto(AppSetting s) => new(
|
||||
s.Id,
|
||||
s.Key,
|
||||
s.Value,
|
||||
s.Description,
|
||||
s.Category,
|
||||
s.ValueType,
|
||||
s.AllowedValues,
|
||||
s.UpdatedAt);
|
||||
|
||||
private static AgentSettingDto MapToAgentDto(AgentSetting s) => new(
|
||||
s.Id,
|
||||
s.AgentId,
|
||||
s.Key,
|
||||
s.Value,
|
||||
s.UpdatedAt);
|
||||
}
|
||||
@@ -54,6 +54,9 @@
|
||||
<MudNavLink Href="/audit-logs" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.History" /> Journal d'audit
|
||||
</MudNavLink>
|
||||
<MudNavLink Href="/settings" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Settings" /> Configuration
|
||||
</MudNavLink>
|
||||
}
|
||||
|
||||
<MudDivider Class="my-4" />
|
||||
@@ -77,9 +80,9 @@
|
||||
@code {
|
||||
private bool _drawerOpen = true;
|
||||
|
||||
private void Logout()
|
||||
private async Task Logout()
|
||||
{
|
||||
AuthStateProvider.NotifyLogout();
|
||||
await AuthStateProvider.NotifyLogoutAsync();
|
||||
Navigation.NavigateTo("/login", true);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des agents.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadAgents" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_agents" Hover="true" Striped="true" Elevation="2">
|
||||
@@ -58,15 +67,24 @@ else
|
||||
|
||||
private IReadOnlyList<AgentItem>? _agents;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
protected override async Task OnInitializedAsync() => await LoadAgents();
|
||||
|
||||
private async Task LoadAgents()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetAgentsBySiteAsync(SiteId);
|
||||
_agents = result?.Items;
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement du journal d'audit.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadLogs" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_logs" Hover="true" Striped="true" Elevation="2" Dense="true">
|
||||
@@ -77,6 +86,7 @@ else
|
||||
@code {
|
||||
private IReadOnlyList<AuditLogItem>? _logs;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private int _page = 1;
|
||||
private int _totalPages = 1;
|
||||
private int _total;
|
||||
@@ -88,6 +98,7 @@ else
|
||||
private async Task LoadLogs()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetAuditLogsAsync(_filterResourceType, _filterAction, _page);
|
||||
@@ -98,7 +109,11 @@ else
|
||||
_totalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des caméras.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadCameras" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_cameras" Hover="true" Striped="true" Elevation="2">
|
||||
@@ -49,7 +58,7 @@ else
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error"
|
||||
OnClick="@(() => DeleteCamera(context.Id, context.Name))" />
|
||||
OnClick="@(() => ConfirmDeleteCamera(context.Id, context.Name))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
@@ -58,6 +67,22 @@ else
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@* ─── Confirm delete dialog ───────────────────────────────── *@
|
||||
@if (_confirmDeleteShow)
|
||||
{
|
||||
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
|
||||
<MudDialog @bind-Visible="_confirmDeleteShow">
|
||||
<TitleContent><MudText Typo="Typo.h6">Confirmer la suppression</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudText>Supprimer la caméra "@_confirmDeleteName" ? Cette action est irréversible.</MudText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteShow = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@ExecuteDeleteCamera">Supprimer</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@if (_showCreate)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
@@ -70,9 +95,9 @@ else
|
||||
<MudTextField @bind-Value="_newModel" Label="Modèle" Variant="Variant.Outlined" Class="mb-4" />
|
||||
<MudTextField @bind-Value="_newRtspUrl" Label="URL RTSP" Variant="Variant.Outlined" Class="mb-4"
|
||||
HelperText="Ex: rtsp://192.168.1.100:554/stream1" />
|
||||
@if (!string.IsNullOrEmpty(_error))
|
||||
@if (!string.IsNullOrEmpty(_dialogError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_error</MudAlert>
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_dialogError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
@@ -90,9 +115,10 @@ else
|
||||
|
||||
private IReadOnlyList<CameraItem>? _cameras;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private bool _showCreate;
|
||||
private bool _saving;
|
||||
private string _error = "";
|
||||
private string _dialogError = "";
|
||||
|
||||
private string _newName = "";
|
||||
private string? _newManufacturer;
|
||||
@@ -104,30 +130,52 @@ else
|
||||
private async Task LoadCameras()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetCamerasBySiteAsync(SiteId);
|
||||
_cameras = result?.Items;
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private bool _confirmDeleteShow;
|
||||
private Guid _confirmDeleteId;
|
||||
private string _confirmDeleteName = "";
|
||||
|
||||
private void ConfirmDeleteCamera(Guid id, string name)
|
||||
{
|
||||
_confirmDeleteId = id;
|
||||
_confirmDeleteName = name;
|
||||
_confirmDeleteShow = true;
|
||||
}
|
||||
|
||||
private async Task ExecuteDeleteCamera()
|
||||
{
|
||||
_confirmDeleteShow = false;
|
||||
await DeleteCamera(_confirmDeleteId, _confirmDeleteName);
|
||||
}
|
||||
|
||||
private async Task CreateCamera()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_newName)) { _error = "Le nom est requis"; return; }
|
||||
if (string.IsNullOrWhiteSpace(_newName)) { _dialogError = "Le nom est requis"; return; }
|
||||
_saving = true;
|
||||
_error = "";
|
||||
_dialogError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.CreateCameraAsync(SiteId, _newName, _newRtspUrl, _newManufacturer, _newModel);
|
||||
if (result is null) { _error = "Erreur lors de la création"; return; }
|
||||
if (result is null) { _dialogError = "Erreur lors de la création"; return; }
|
||||
_showCreate = false;
|
||||
ResetForm();
|
||||
Snackbar.Add("Caméra ajoutée", Severity.Success);
|
||||
await LoadCameras();
|
||||
}
|
||||
catch (Exception ex) { _error = $"Erreur : {ex.Message}"; }
|
||||
catch (Exception ex) { _dialogError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement du tableau de bord.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@(() => { _ = OnInitializedAsync(); })" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else if (_sites?.Count > 0)
|
||||
{
|
||||
<MudTable Items="@_sites" Hover="true" Striped="true" Elevation="1">
|
||||
@@ -85,9 +94,12 @@
|
||||
private int _activeSites;
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
// Load stats + sites in parallel (2 API calls instead of N*2+1)
|
||||
@@ -109,6 +121,7 @@
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
_errorMessage = "Email ou mot de passe invalide";
|
||||
return;
|
||||
}
|
||||
AuthStateProvider.NotifyLogin(result);
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
Snackbar.Add("Connexion réussie", Severity.Success);
|
||||
Navigation.NavigateTo(_returnUrl);
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
_errorMessage = "Erreur lors de l'inscription";
|
||||
return;
|
||||
}
|
||||
AuthStateProvider.NotifyLogin(result);
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
Snackbar.Add("Compte créé avec succès", Severity.Success);
|
||||
Navigation.NavigateTo("/dashboard");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
@page "/settings"
|
||||
@attribute [Authorize(Roles = "Admin")]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Settings" Class="mr-2" />
|
||||
Configuration
|
||||
</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)" Class="mb-4 mr-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Nouveau paramètre
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" OnClick="@ReloadAllConfig" Class="mb-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" /> Recharger tous les agents
|
||||
</MudButton>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement de la configuration.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadSettings" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else if (_settings is null || _settings.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Class="mb-4">
|
||||
<MudText>Aucun paramètre de configuration trouvé.</MudText>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var category in _groupedSettings)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Folder" Size="Size.Small" Class="mr-1" />
|
||||
@category.Key
|
||||
</MudText>
|
||||
|
||||
<MudTable Items="@category.Value" Hover="true" Striped="true" Elevation="2" Class="mb-4">
|
||||
<HeaderContent>
|
||||
<MudTh>Clé</MudTh>
|
||||
<MudTh>Valeur</MudTh>
|
||||
<MudTh>Type</MudTh>
|
||||
<MudTh>Description</MudTh>
|
||||
<MudTh>Mis à jour</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Clé">
|
||||
<MudText Typo="Typo.body2" Class="font-weight-bold">@context.Key</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Valeur">
|
||||
@switch (context.ValueType.ToLowerInvariant())
|
||||
{
|
||||
case "boolean":
|
||||
case "bool":
|
||||
<MudSwitch T="bool" @bind-Checked="_switches[context.Key]"
|
||||
Disabled="true" />
|
||||
break;
|
||||
case "number":
|
||||
case "int":
|
||||
case "integer":
|
||||
<MudText Typo="Typo.body2">@context.Value</MudText>
|
||||
break;
|
||||
case "select":
|
||||
case "dropdown":
|
||||
<MudText Typo="Typo.body2" Color="Color.Primary">@context.Value</MudText>
|
||||
break;
|
||||
default:
|
||||
<MudText Typo="Typo.body2" Style="max-width:300px;word-break:break-all;">@context.Value</MudText>
|
||||
break;
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Type">
|
||||
<MudText Typo="Typo.body2" Class="mud-chip mud-chip-text mud-chip-size-small"
|
||||
Style="@($"background:{GetTypeColor(context.ValueType)};color:#fff;padding:2px 8px;border-radius:12px;display:inline-block;")">
|
||||
@context.ValueType
|
||||
</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Description">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">
|
||||
@(context.Description ?? "—")
|
||||
</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Mis à jour">
|
||||
<MudText Typo="Typo.body2">@context.UpdatedAt.ToString("g")</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small"
|
||||
OnClick="@(() => OpenEdit(context))" Class="mr-1" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small"
|
||||
Color="Color.Error" OnClick="@(() => ConfirmDelete(context))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
<MudText Align="Align.Center" Class="py-4">Aucun paramètre dans cette catégorie</MudText>
|
||||
</NoRecordsContent>
|
||||
</MudTable>
|
||||
}
|
||||
}
|
||||
|
||||
@* ─── Dialog: Créer un paramètre ──────────────────────────────────── *@
|
||||
|
||||
@if (_showCreate)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">Nouveau paramètre</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudTextField @bind-Value="_createKey" Label="Clé *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_createValue" Label="Valeur *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_createDescription" Label="Description" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudTextField @bind-Value="_createCategory" Label="Catégorie" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" HelperText="Ex: General, Detection, Recording..." />
|
||||
<MudText Typo="Typo.body2" Class="mb-2">Type de valeur</MudText>
|
||||
<MudSelect @bind-Value="_createValueType" Label="Type" Variant="Variant.Outlined" Class="mb-4">
|
||||
<MudSelectItem Value="@("string")">string</MudSelectItem>
|
||||
<MudSelectItem Value="@("boolean")">boolean</MudSelectItem>
|
||||
<MudSelectItem Value="@("number")">number</MudSelectItem>
|
||||
<MudSelectItem Value="@("select")">select</MudSelectItem>
|
||||
</MudSelect>
|
||||
|
||||
@if (_createValueType == "select")
|
||||
{
|
||||
<MudTextField @bind-Value="_createAllowedValues" Label="Valeurs autorisées (séparées par des virgules)"
|
||||
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
|
||||
HelperText="Ex: valeur1,valeur2,valeur3" />
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(_createError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_createError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showCreate = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@CreateSetting" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Créer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Dialog: Modifier un paramètre ───────────────────────────────── *@
|
||||
|
||||
@if (_editSetting is not null && _showEdit)
|
||||
{
|
||||
<MudOverlay Visible="@_showEdit" OnClick="@(() => _showEdit = false)" />
|
||||
<MudDialog @bind-Visible="_showEdit">
|
||||
<TitleContent><MudText Typo="Typo.h6">Paramètre : @_editSetting.Key</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
@if (_editSetting.ValueType.ToLowerInvariant() is "boolean" or "bool")
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">Valeur</MudText>
|
||||
<MudSwitch T="bool" @bind-Checked="_editBoolValue" Color="Color.Primary" />
|
||||
}
|
||||
else if (_editSetting.ValueType.ToLowerInvariant() is "number" or "int" or "integer")
|
||||
{
|
||||
<MudTextField @bind-Value="_editStringValue" Label="Valeur *" Variant="Variant.Outlined"
|
||||
InputType="InputType.Number" Class="mb-4" Required="true" Immediate="true" />
|
||||
}
|
||||
else if (_editSetting.ValueType.ToLowerInvariant() is "select" or "dropdown"
|
||||
&& !string.IsNullOrEmpty(_editSetting.AllowedValues))
|
||||
{
|
||||
<MudText Typo="Typo.body2" Class="mb-2">Valeur</MudText>
|
||||
<MudSelect @bind-Value="_editStringValue" Label="Valeur" Variant="Variant.Outlined" Class="mb-4">
|
||||
@foreach (var opt in _editAllowedOptions)
|
||||
{
|
||||
<MudSelectItem Value="@opt">@opt</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTextField @bind-Value="_editStringValue" Label="Valeur *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
}
|
||||
|
||||
<MudTextField @bind-Value="_editDescription" Label="Description" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudTextField @bind-Value="_editCategory" Label="Catégorie" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudText Typo="Typo.body2" Class="mb-2">Type de valeur</MudText>
|
||||
<MudSelect @bind-Value="_editValueType" Label="Type" Variant="Variant.Outlined" Class="mb-4">
|
||||
<MudSelectItem Value="@("string")">string</MudSelectItem>
|
||||
<MudSelectItem Value="@("boolean")">boolean</MudSelectItem>
|
||||
<MudSelectItem Value="@("number")">number</MudSelectItem>
|
||||
<MudSelectItem Value="@("select")">select</MudSelectItem>
|
||||
</MudSelect>
|
||||
|
||||
@if (_editValueType == "select")
|
||||
{
|
||||
<MudTextField @bind-Value="_editAllowedValues" Label="Valeurs autorisées (séparées par des virgules)"
|
||||
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
|
||||
HelperText="Ex: valeur1,valeur2,valeur3" />
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(_editError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_editError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@CloseEdit">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@SaveEdit" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Enregistrer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Dialog: Confirmer la suppression ────────────────────────────── *@
|
||||
|
||||
@if (_deleteTarget is not null && _showDeleteConfirm)
|
||||
{
|
||||
<MudOverlay Visible="@_showDeleteConfirm" OnClick="@(() => _showDeleteConfirm = false)" />
|
||||
<MudDialog @bind-Visible="_showDeleteConfirm">
|
||||
<TitleContent><MudText Typo="Typo.h6">Confirmer la suppression</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudAlert Severity="Severity.Warning" Class="mb-4">
|
||||
Êtes-vous sûr de vouloir supprimer le paramètre <strong>@_deleteTarget.Key</strong> ?
|
||||
</MudAlert>
|
||||
@if (!string.IsNullOrEmpty(_deleteTarget.Description))
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">@_deleteTarget.Description</MudText>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_deleteError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mt-2">@_deleteError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showDeleteConfirm = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@DeleteSetting" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Supprimer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private List<AppSettingItem>? _settings;
|
||||
private Dictionary<string, List<AppSettingItem>> _groupedSettings = new();
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private bool _saving;
|
||||
|
||||
// Edit state
|
||||
private AppSettingItem? _editSetting;
|
||||
private bool _showEdit;
|
||||
private string _editStringValue = "";
|
||||
private bool _editBoolValue;
|
||||
private string _editDescription = "";
|
||||
private string _editCategory = "";
|
||||
private string _editValueType = "";
|
||||
private string _editAllowedValues = "";
|
||||
private string[] _editAllowedOptions = [];
|
||||
private string _editError = "";
|
||||
|
||||
// Create state
|
||||
private bool _showCreate;
|
||||
private string _createKey = "";
|
||||
private string _createValue = "";
|
||||
private string _createDescription = "";
|
||||
private string _createCategory = "General";
|
||||
private string _createValueType = "string";
|
||||
private string _createAllowedValues = "";
|
||||
private string _createError = "";
|
||||
|
||||
// Delete state
|
||||
private AppSettingItem? _deleteTarget;
|
||||
private bool _showDeleteConfirm;
|
||||
private string _deleteError = "";
|
||||
|
||||
// Track switch states for display
|
||||
private Dictionary<string, bool> _switches = new();
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadSettings();
|
||||
|
||||
private async Task LoadSettings()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
_settings = await Api.GetSettingsAsync();
|
||||
_switches.Clear();
|
||||
foreach (var s in _settings)
|
||||
{
|
||||
if (s.ValueType.ToLowerInvariant() is "boolean" or "bool")
|
||||
_switches[s.Key] = bool.TryParse(s.Value, out var b) && b;
|
||||
}
|
||||
_groupedSettings = _settings
|
||||
.GroupBy(s => string.IsNullOrEmpty(s.Category) ? "General" : s.Category)
|
||||
.OrderBy(g => g.Key)
|
||||
.ToDictionary(g => g.Key, g => g.ToList());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private string GetTypeColor(string valueType)
|
||||
{
|
||||
return valueType.ToLowerInvariant() switch
|
||||
{
|
||||
"boolean" or "bool" => "#4caf50",
|
||||
"number" or "int" or "integer" => "#2196f3",
|
||||
"select" or "dropdown" => "#ff9800",
|
||||
_ => "#607d8b"
|
||||
};
|
||||
}
|
||||
|
||||
private Color GetTypeChipColor(string valueType)
|
||||
{
|
||||
return valueType.ToLowerInvariant() switch
|
||||
{
|
||||
"boolean" or "bool" => Color.Success,
|
||||
"number" or "int" or "integer" => Color.Info,
|
||||
"select" or "dropdown" => Color.Warning,
|
||||
_ => Color.Default
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────
|
||||
|
||||
private async Task CreateSetting()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_createKey) || string.IsNullOrWhiteSpace(_createValue))
|
||||
{ _createError = "Les champs Clé et Valeur sont requis"; return; }
|
||||
_saving = true;
|
||||
_createError = "";
|
||||
try
|
||||
{
|
||||
var allowedValues = _createValueType == "select" && !string.IsNullOrWhiteSpace(_createAllowedValues)
|
||||
? _createAllowedValues
|
||||
: null;
|
||||
|
||||
var result = await Api.CreateSettingAsync(new CreateAppSettingRequest(
|
||||
_createKey.Trim(),
|
||||
_createValue.Trim(),
|
||||
string.IsNullOrWhiteSpace(_createCategory) ? "General" : _createCategory.Trim(),
|
||||
string.IsNullOrWhiteSpace(_createDescription) ? null : _createDescription.Trim(),
|
||||
_createValueType,
|
||||
allowedValues
|
||||
));
|
||||
|
||||
if (!result.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await result.Content.ReadAsStringAsync();
|
||||
_createError = $"Erreur : {result.StatusCode} — {body}";
|
||||
return;
|
||||
}
|
||||
|
||||
_showCreate = false;
|
||||
_createKey = ""; _createValue = ""; _createDescription = "";
|
||||
_createCategory = "General"; _createValueType = "string"; _createAllowedValues = "";
|
||||
Snackbar.Add("Paramètre créé avec succès", Severity.Success);
|
||||
await LoadSettings();
|
||||
}
|
||||
catch (Exception ex) { _createError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
// ─── Edit ─────────────────────────────────────────────────────────
|
||||
|
||||
private void OpenEdit(AppSettingItem setting)
|
||||
{
|
||||
_editSetting = setting;
|
||||
_editStringValue = setting.Value;
|
||||
_editBoolValue = bool.TryParse(setting.Value, out var b) && b;
|
||||
_editDescription = setting.Description ?? "";
|
||||
_editCategory = setting.Category;
|
||||
_editValueType = setting.ValueType;
|
||||
_editAllowedValues = setting.AllowedValues ?? "";
|
||||
_editAllowedOptions = (setting.AllowedValues ?? "")
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
_editError = "";
|
||||
_showEdit = true;
|
||||
}
|
||||
|
||||
private void CloseEdit()
|
||||
{
|
||||
_showEdit = false;
|
||||
_editSetting = null;
|
||||
}
|
||||
|
||||
private async Task SaveEdit()
|
||||
{
|
||||
if (_editSetting is null) return;
|
||||
_saving = true;
|
||||
_editError = "";
|
||||
try
|
||||
{
|
||||
var newValue = _editSetting.ValueType.ToLowerInvariant() is "boolean" or "bool"
|
||||
? _editBoolValue.ToString().ToLowerInvariant()
|
||||
: _editStringValue.Trim();
|
||||
|
||||
var allowedValues = _editValueType == "select" && !string.IsNullOrWhiteSpace(_editAllowedValues)
|
||||
? _editAllowedValues
|
||||
: null;
|
||||
|
||||
var result = await Api.UpdateSettingAsync(_editSetting.Key, new UpdateAppSettingRequest(
|
||||
newValue,
|
||||
string.IsNullOrWhiteSpace(_editDescription) ? null : _editDescription.Trim(),
|
||||
string.IsNullOrWhiteSpace(_editCategory) ? null : _editCategory.Trim(),
|
||||
_editValueType,
|
||||
allowedValues
|
||||
));
|
||||
|
||||
if (!result.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await result.Content.ReadAsStringAsync();
|
||||
_editError = $"Erreur : {result.StatusCode} — {body}";
|
||||
return;
|
||||
}
|
||||
|
||||
Snackbar.Add("Paramètre mis à jour", Severity.Success);
|
||||
CloseEdit();
|
||||
await LoadSettings();
|
||||
}
|
||||
catch (Exception ex) { _editError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────
|
||||
|
||||
private void ConfirmDelete(AppSettingItem setting)
|
||||
{
|
||||
_deleteTarget = setting;
|
||||
_deleteError = "";
|
||||
_showDeleteConfirm = true;
|
||||
}
|
||||
|
||||
private async Task DeleteSetting()
|
||||
{
|
||||
if (_deleteTarget is null) return;
|
||||
_saving = true;
|
||||
_deleteError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.DeleteSettingAsync(_deleteTarget.Key);
|
||||
if (!result.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await result.Content.ReadAsStringAsync();
|
||||
_deleteError = $"Erreur : {result.StatusCode} — {body}";
|
||||
return;
|
||||
}
|
||||
|
||||
_showDeleteConfirm = false;
|
||||
Snackbar.Add("Paramètre supprimé", Severity.Success);
|
||||
_deleteTarget = null;
|
||||
await LoadSettings();
|
||||
}
|
||||
catch (Exception ex) { _deleteError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
// ─── Reload ───────────────────────────────────────────────────────
|
||||
|
||||
private async Task ReloadAllConfig()
|
||||
{
|
||||
_saving = true;
|
||||
try
|
||||
{
|
||||
var result = await Api.ReloadAllConfigAsync();
|
||||
if (result.IsSuccessStatusCode)
|
||||
Snackbar.Add("Configuration rechargée sur tous les agents", Severity.Success);
|
||||
else
|
||||
Snackbar.Add($"Erreur lors du rechargement : {result.StatusCode}", Severity.Error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _saving = false; }
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des sites.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadSites" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_sites" Hover="true" Striped="true" Elevation="2">
|
||||
@@ -40,7 +49,7 @@ else
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ContentCopy" Size="Size.Small"
|
||||
OnClick="@(() => CopyToken(context.Id))" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error"
|
||||
OnClick="@(() => DeleteSite(context.Id, context.Name))" />
|
||||
OnClick="@(() => ConfirmDeleteSite(context.Id, context.Name))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
@@ -88,6 +97,22 @@ else
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Confirm delete dialog ───────────────────────────────── *@
|
||||
@if (_confirmDeleteShow)
|
||||
{
|
||||
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
|
||||
<MudDialog @bind-Visible="_confirmDeleteShow">
|
||||
<TitleContent><MudText Typo="Typo.h6">Confirmer la suppression</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudText>Supprimer le site "@_confirmDeleteName" ? Cette action est irréversible.</MudText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteShow = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@ExecuteDelete">Supprimer</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Token dialog ──────────────────────────────────────────── *@
|
||||
@if (_showTokenDialog)
|
||||
{
|
||||
@@ -133,6 +158,7 @@ else
|
||||
@code {
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private bool _showCreate;
|
||||
private bool _saving;
|
||||
private string _newName = "";
|
||||
@@ -154,15 +180,37 @@ else
|
||||
private async Task LoadSites()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetSitesAsync();
|
||||
_sites = result?.Items;
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private bool _confirmDeleteShow;
|
||||
private Guid _confirmDeleteId;
|
||||
private string _confirmDeleteName = "";
|
||||
|
||||
private void ConfirmDeleteSite(Guid id, string name)
|
||||
{
|
||||
_confirmDeleteId = id;
|
||||
_confirmDeleteName = name;
|
||||
_confirmDeleteShow = true;
|
||||
}
|
||||
|
||||
private async Task ExecuteDelete()
|
||||
{
|
||||
_confirmDeleteShow = false;
|
||||
await DeleteSite(_confirmDeleteId, _confirmDeleteName);
|
||||
}
|
||||
|
||||
private void CancelCreate()
|
||||
{
|
||||
_showCreate = false;
|
||||
|
||||
@@ -17,6 +17,15 @@
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des utilisateurs.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadUsers" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_users" Hover="true" Striped="true" Elevation="2">
|
||||
@@ -235,6 +244,7 @@ else
|
||||
@code {
|
||||
private IReadOnlyList<UserItem>? _users;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private int _page = 1;
|
||||
private int _totalPages = 1;
|
||||
private int _total;
|
||||
@@ -264,6 +274,7 @@ else
|
||||
private async Task LoadUsers()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetUsersAsync(_page);
|
||||
@@ -274,7 +285,11 @@ else
|
||||
_totalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ builder.Services.AddRazorComponents()
|
||||
// Auth for Blazor
|
||||
builder.Services.AddScoped<AuthenticationStateProvider, HeimdallAuthStateProvider>();
|
||||
builder.Services.AddAuthorizationCore();
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
builder.Services.AddMudServices(config =>
|
||||
{
|
||||
|
||||
@@ -231,6 +231,38 @@ public class HeimdallApiClient
|
||||
return await client.GetFromJsonAsync<PagedData<AgentItem>>(
|
||||
$"api/agents/by-site/{siteId}?page={page}&pageSize={pageSize}", Json);
|
||||
}
|
||||
|
||||
// ─── Settings ──────────────────────────────────────────────────
|
||||
|
||||
public async Task<List<AppSettingItem>> GetSettingsAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<AppSettingItem>>("api/settings") ?? [];
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> CreateSettingAsync(CreateAppSettingRequest request)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.PostAsJsonAsync("api/settings", request);
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> UpdateSettingAsync(string key, UpdateAppSettingRequest request)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.PutAsJsonAsync($"api/settings/{key}", request);
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> DeleteSettingAsync(string key)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.DeleteAsync($"api/settings/{key}");
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> ReloadAllConfigAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.PostAsync("api/settings/reload", null);
|
||||
}
|
||||
}
|
||||
|
||||
public class CameraItem
|
||||
@@ -284,3 +316,33 @@ public class AgentItem
|
||||
public string GpuType { get; set; } = "None";
|
||||
public DateTime CreatedAt { get; set; }
|
||||
}
|
||||
|
||||
// ─── Settings DTOs ────────────────────────────────────────────────
|
||||
|
||||
public record AppSettingItem(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("description")] string? Description,
|
||||
[property: JsonPropertyName("category")] string Category,
|
||||
[property: JsonPropertyName("valueType")] string ValueType,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues,
|
||||
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
|
||||
);
|
||||
|
||||
public record CreateAppSettingRequest(
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("category")] string Category = "General",
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("valueType")] string ValueType = "string",
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
);
|
||||
|
||||
public record UpdateAppSettingRequest(
|
||||
[property: JsonPropertyName("value")] string Value,
|
||||
[property: JsonPropertyName("description")] string? Description = null,
|
||||
[property: JsonPropertyName("category")] string? Category = null,
|
||||
[property: JsonPropertyName("valueType")] string? ValueType = null,
|
||||
[property: JsonPropertyName("allowedValues")] string? AllowedValues = null
|
||||
);
|
||||
@@ -1,58 +1,82 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
public class HeimdallAuthStateProvider : AuthenticationStateProvider
|
||||
{
|
||||
private readonly ProtectedLocalStorage _storage;
|
||||
private readonly AuthState _authState;
|
||||
|
||||
public HeimdallAuthStateProvider(AuthState authState)
|
||||
private const string StorageKey = "heimdall_auth";
|
||||
|
||||
public HeimdallAuthStateProvider(ProtectedLocalStorage storage, AuthState authState)
|
||||
{
|
||||
_storage = storage;
|
||||
_authState = authState;
|
||||
}
|
||||
|
||||
public override Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
if (!_authState.IsLoggedIn || _authState.User is null)
|
||||
try
|
||||
{
|
||||
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
var result = await _storage.GetAsync<AuthResponse>(StorageKey);
|
||||
if (!result.Success || result.Value is null)
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
var authResponse = result.Value;
|
||||
_authState.Login(authResponse);
|
||||
|
||||
return CreateAuthenticationState(authResponse);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task NotifyLoginAsync(AuthResponse response)
|
||||
{
|
||||
await _storage.SetAsync(StorageKey, response);
|
||||
_authState.Login(response);
|
||||
NotifyAuthenticationStateChanged(Task.FromResult(CreateAuthenticationState(response)));
|
||||
}
|
||||
|
||||
public async Task NotifyLogoutAsync()
|
||||
{
|
||||
await _storage.DeleteAsync(StorageKey);
|
||||
_authState.Logout();
|
||||
NotifyAuthenticationStateChanged(
|
||||
Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))));
|
||||
}
|
||||
|
||||
private static AuthenticationState CreateAuthenticationState(AuthResponse response)
|
||||
{
|
||||
if (response.User is null)
|
||||
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, _authState.User.Id.ToString()),
|
||||
new(ClaimTypes.Name, _authState.User.DisplayName),
|
||||
new(ClaimTypes.Email, _authState.User.Email),
|
||||
new(ClaimTypes.NameIdentifier, response.User.Id.ToString()),
|
||||
new(ClaimTypes.Name, response.User.DisplayName),
|
||||
new(ClaimTypes.Email, response.User.Email),
|
||||
new(ClaimTypes.AuthenticationMethod, "Bearer")
|
||||
};
|
||||
|
||||
if (_authState.User.Roles is not null)
|
||||
{
|
||||
foreach (var role in _authState.User.Roles)
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
claims.Add(new Claim("permission", role)); // Map role to permission for policies
|
||||
}
|
||||
}
|
||||
foreach (var role in response.User.Roles ?? [])
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, "HeimdallAuth");
|
||||
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
|
||||
}
|
||||
// Map roles → permissions via the AppPermissions dictionary (same as AuthService)
|
||||
var permissions = response.User.Roles?
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
.ToList() ?? [];
|
||||
|
||||
public void NotifyAuthStateChanged()
|
||||
{
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
foreach (var permission in permissions)
|
||||
claims.Add(new Claim("permission", permission));
|
||||
|
||||
public void NotifyLogin(AuthResponse response)
|
||||
{
|
||||
_authState.Login(response);
|
||||
NotifyAuthStateChanged();
|
||||
}
|
||||
|
||||
public void NotifyLogout()
|
||||
{
|
||||
_authState.Logout();
|
||||
NotifyAuthStateChanged();
|
||||
var identity = new ClaimsIdentity(claims, "Bearer");
|
||||
return new AuthenticationState(new ClaimsPrincipal(identity));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentValidation" Version="11.11.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="6.0.0" />
|
||||
<PackageReference Include="Shouldly" Version="4.3.0" />
|
||||
@@ -18,6 +19,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
<Using Include="Shouldly" />
|
||||
<Using Include="FluentValidation.TestHelper" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace Heimdall.Application.Tests;
|
||||
|
||||
public class PlaceholderTest
|
||||
{
|
||||
[Fact]
|
||||
public void Application_Layer_Is_Configured() =>
|
||||
Assert.True(true, "Application test project is configured correctly");
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class CreateAppSettingValidatorTests
|
||||
{
|
||||
private readonly CreateAppSettingValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "heartbeat.interval.seconds",
|
||||
Value: "30",
|
||||
Category: "Heartbeat",
|
||||
Description: "Heartbeat interval in seconds",
|
||||
ValueType: "int");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyKey_FailsValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "",
|
||||
Value: "30",
|
||||
Category: "General");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidKeyFormat_FailsValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "HEARTBEAT.Interval!", // uppercase + special char
|
||||
Value: "30",
|
||||
Category: "General");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidValueType_FailsValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "test.setting",
|
||||
Value: "value",
|
||||
Category: "General",
|
||||
ValueType: "invalid");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.ValueType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyCategory_FailsValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "test.setting",
|
||||
Value: "value",
|
||||
Category: "");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidKeyWithDotsAndHyphens_PassesValidation()
|
||||
{
|
||||
var request = new CreateAppSettingRequest(
|
||||
Key: "ai.detection.min-confidence",
|
||||
Value: "0.75",
|
||||
Category: "AI",
|
||||
ValueType: "double");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class CreateCameraValidatorTests
|
||||
{
|
||||
private readonly CreateCameraValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.NewGuid(),
|
||||
Name: "Front Door Camera",
|
||||
RtspUrl: "rtsp://192.168.1.100:554/stream1",
|
||||
Manufacturer: "Hikvision",
|
||||
Model: "DS-2CD2T47G2-L");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyName_FailsValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.NewGuid(),
|
||||
Name: "",
|
||||
RtspUrl: "rtsp://192.168.1.100:554/stream1",
|
||||
Manufacturer: null,
|
||||
Model: null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidRtspUrl_FailsValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.NewGuid(),
|
||||
Name: "Test Camera",
|
||||
RtspUrl: "not-a-valid-uri",
|
||||
Manufacturer: null,
|
||||
Model: null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.RtspUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyRtspUrl_FailsValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.NewGuid(),
|
||||
Name: "Test Camera",
|
||||
RtspUrl: "",
|
||||
Manufacturer: null,
|
||||
Model: null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.RtspUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptySiteId_FailsValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.Empty,
|
||||
Name: "Test Camera",
|
||||
RtspUrl: "rtsp://192.168.1.100:554/stream1",
|
||||
Manufacturer: null,
|
||||
Model: null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.SiteId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new CreateCameraRequest(
|
||||
SiteId: Guid.NewGuid(),
|
||||
Name: new string('x', 201),
|
||||
RtspUrl: "rtsp://192.168.1.100:554/stream1",
|
||||
Manufacturer: null,
|
||||
Model: null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class CreateSiteValidatorTests
|
||||
{
|
||||
private readonly CreateSiteValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_Minimal_PassesValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest("Main Office", null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_WithAllFields_PassesValidation()
|
||||
{
|
||||
// Some CI/container environments lack tzdata; use a fallback
|
||||
var tz = "Europe/Paris";
|
||||
try { TimeZoneInfo.FindSystemTimeZoneById(tz); }
|
||||
catch { tz = "UTC"; }
|
||||
|
||||
var request = new CreateSiteRequest(
|
||||
"Main Office",
|
||||
"123 Main St, Paris",
|
||||
tz);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyName_FailsValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest(string.Empty, null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest(new string('A', 201), null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddressExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest(
|
||||
"Main Office",
|
||||
new string('A', 501),
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Address);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidTimezone_FailsValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest(
|
||||
"Main Office",
|
||||
null,
|
||||
"Mars/Olympus");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Timezone);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidTimezone_WithSubregion_PassesValidation()
|
||||
{
|
||||
var tz = "America/Argentina/Buenos_Aires";
|
||||
try { TimeZoneInfo.FindSystemTimeZoneById(tz); }
|
||||
catch { return; } // skip if tzdata not available
|
||||
|
||||
var request = new CreateSiteRequest("Main Office", null, tz);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyTimezone_PassesValidation()
|
||||
{
|
||||
var request = new CreateSiteRequest(
|
||||
"Main Office",
|
||||
null,
|
||||
string.Empty);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class CreateUserValidatorTests
|
||||
{
|
||||
private readonly CreateUserValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "test@example.com",
|
||||
Password: "StrongP@ss123!",
|
||||
DisplayName: "Test User",
|
||||
Roles: new[] { "Supervisor" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidEmail_FailsValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "not-an-email",
|
||||
Password: "StrongP@ss123!",
|
||||
DisplayName: "Test User",
|
||||
Roles: new[] { "Viewer" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShortPassword_FailsValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "test@example.com",
|
||||
Password: "Short1!",
|
||||
DisplayName: "Test User",
|
||||
Roles: new[] { "Viewer" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyEmail_FailsValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "",
|
||||
Password: "StrongP@ss123!",
|
||||
DisplayName: "Test User",
|
||||
Roles: new[] { "Viewer" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyDisplayName_FailsValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "test@example.com",
|
||||
Password: "StrongP@ss123!",
|
||||
DisplayName: "",
|
||||
Roles: new[] { "Viewer" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MultipleRoles_PassesValidation()
|
||||
{
|
||||
var request = new CreateUserRequest(
|
||||
Email: "admin@example.com",
|
||||
Password: "StrongP@ss123!",
|
||||
DisplayName: "Multi Role User",
|
||||
Roles: new[] { "Admin", "Supervisor" });
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class LoginRequestValidatorTests
|
||||
{
|
||||
private readonly LoginRequestValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new LoginRequest("user@example.com", "my-password");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyEmail_FailsValidation()
|
||||
{
|
||||
var request = new LoginRequest(string.Empty, "password");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidEmail_FailsValidation()
|
||||
{
|
||||
var request = new LoginRequest("not-an-email", "password");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmailExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var localPart = new string('a', 250);
|
||||
var request = new LoginRequest($"{localPart}@example.com", "password");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyPassword_FailsValidation()
|
||||
{
|
||||
var request = new LoginRequest("user@example.com", string.Empty);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PasswordExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new LoginRequest("user@example.com", new string('P', 201));
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class RegisterAgentValidatorTests
|
||||
{
|
||||
private readonly RegisterAgentValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_WithAllFields_PassesValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
"reg-token-abc-123",
|
||||
"agent-01.example.com",
|
||||
"1.0.0",
|
||||
"192.168.1.10");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_NullPublicIp_PassesValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
"reg-token-abc-123",
|
||||
"agent-01.example.com",
|
||||
"1.0.0",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyToken_FailsValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
string.Empty,
|
||||
"agent-01.example.com",
|
||||
"1.0.0",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyHostname_FailsValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
"reg-token-abc-123",
|
||||
string.Empty,
|
||||
"1.0.0",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Hostname);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TokenExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
new string('T', 501),
|
||||
"agent-01.example.com",
|
||||
"1.0.0",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HostnameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
"reg-token-abc-123",
|
||||
new string('H', 256),
|
||||
"1.0.0",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Hostname);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VersionExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new RegisterAgentRequest(
|
||||
"reg-token-abc-123",
|
||||
"agent-01.example.com",
|
||||
new string('V', 51),
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Version);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class RegisterRequestValidatorTests
|
||||
{
|
||||
private readonly RegisterRequestValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
"StrongPassword123!",
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyEmail_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
string.Empty,
|
||||
"StrongPassword123!",
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidEmail_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"not-an-email",
|
||||
"StrongPassword123!",
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmailExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var localPart = new string('a', 250);
|
||||
var request = new RegisterRequest(
|
||||
$"{localPart}@example.com",
|
||||
"StrongPassword123!",
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyPassword_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
string.Empty,
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PasswordShorterThan12Chars_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
"Short1!",
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PasswordExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
new string('P', 201),
|
||||
"John Doe");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyDisplayName_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
"StrongPassword123!",
|
||||
string.Empty);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisplayNameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new RegisterRequest(
|
||||
"user@example.com",
|
||||
"StrongPassword123!",
|
||||
new string('A', 201));
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.DisplayName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class SetAgentSettingValidatorTests
|
||||
{
|
||||
private readonly SetAgentSettingValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new SetAgentSettingRequest("theme", "dark");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyKey_FailsValidation()
|
||||
{
|
||||
var request = new SetAgentSettingRequest(string.Empty, "value");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KeyExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new SetAgentSettingRequest(new string('K', 201), "value");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NullValue_FailsValidation()
|
||||
{
|
||||
var request = new SetAgentSettingRequest("valid.key", null!);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class UpdateAppSettingValidatorTests
|
||||
{
|
||||
private readonly UpdateAppSettingValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_AllFields_PassesValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(
|
||||
"new-value",
|
||||
"Updated description",
|
||||
"General",
|
||||
"string",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_MinimalFields_PassesValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest("new-value");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyValue_FailsValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(string.Empty);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NullValue_FailsValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(null!);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CategoryExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(
|
||||
"value",
|
||||
null,
|
||||
new string('A', 101),
|
||||
null,
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidValueType_FailsValidation()
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(
|
||||
"value",
|
||||
null,
|
||||
null,
|
||||
"json",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.ValueType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllValidValueTypes_PassValidation()
|
||||
{
|
||||
var valueTypes = new[] { "string", "int", "bool", "double", "select" };
|
||||
|
||||
foreach (var valueType in valueTypes)
|
||||
{
|
||||
var request = new UpdateAppSettingRequest(
|
||||
"value",
|
||||
null,
|
||||
null,
|
||||
valueType,
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
result.IsValid.ShouldBeTrue($"ValueType '{valueType}' should be valid");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class UpdateCameraValidatorTests
|
||||
{
|
||||
private readonly UpdateCameraValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_PassesValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
"Front Gate Camera",
|
||||
"rtsp://192.168.1.100/stream1",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_NullRtspUrl_PassesValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
"Front Gate Camera",
|
||||
null,
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.RtspUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyName_FailsValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
string.Empty,
|
||||
"rtsp://192.168.1.100/stream1",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NullName_FailsValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
null!,
|
||||
"rtsp://192.168.1.100/stream1",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
new string('A', 201),
|
||||
"rtsp://192.168.1.100/stream1",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyRtspUrl_FailsValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
"Front Gate Camera",
|
||||
string.Empty,
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.RtspUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidRtspUrl_FailsValidation()
|
||||
{
|
||||
var request = new UpdateCameraRequest(
|
||||
"Front Gate Camera",
|
||||
"not-a-valid-url",
|
||||
null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.RtspUrl);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class UpdateSiteValidatorTests
|
||||
{
|
||||
private readonly UpdateSiteValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_AllFields_PassesValidation()
|
||||
{
|
||||
var request = new UpdateSiteRequest("Main Office", "123 Main St", "Europe/Paris");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_NullFields_PassesValidation()
|
||||
{
|
||||
var request = new UpdateSiteRequest(null!, null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateSiteRequest(new string('A', 201), null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddressExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateSiteRequest("Valid Name", new string('A', 501), null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Address);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TimezoneExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateSiteRequest("Valid Name", null, new string('A', 101));
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Timezone);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using FluentValidation.TestHelper;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Validators;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Validators;
|
||||
|
||||
public class UpdateUserValidatorTests
|
||||
{
|
||||
private readonly UpdateUserValidator _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_AllFields_PassesValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest("John Doe", "dark", "en");
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_NullDisplayName_PassesValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest(null!, "light", null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidRequest_NullTheme_PassesValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest("John Doe", null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisplayNameExceedsMaxLength_FailsValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest(new string('A', 101), null, null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidTheme_FailsValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest(null!, "blue", null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeFalse();
|
||||
result.ShouldHaveValidationErrorFor(x => x.Theme);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidTheme_Light_PassesValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest(null!, "light", null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidTheme_Dark_PassesValidation()
|
||||
{
|
||||
var request = new UpdateUserRequest(null!, "dark", null);
|
||||
|
||||
var result = _sut.TestValidate(request);
|
||||
|
||||
result.IsValid.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Integration tests for SettingsController (api/settings).
|
||||
///
|
||||
/// NOTE: Rate limit is 10 auth req/min so we cache admin + viewer tokens
|
||||
/// statically (xUnit creates a new class instance per test).
|
||||
/// </summary>
|
||||
public class SettingsControllerTests : IClassFixture<HeimdallWebApplicationFactory>
|
||||
{
|
||||
private readonly HeimdallWebApplicationFactory _factory;
|
||||
private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
private static string? _adminToken;
|
||||
private static string? _viewerToken;
|
||||
private static readonly object TokenLock = new();
|
||||
|
||||
public SettingsControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory;
|
||||
|
||||
/// <summary>Get a shared admin-authenticated HttpClient (lazy, cached token).</summary>
|
||||
private async Task<HttpClient> GetAdminClientAsync()
|
||||
{
|
||||
var token = _adminToken;
|
||||
if (token is null)
|
||||
{
|
||||
token = await RegisterAdminAsync();
|
||||
lock (TokenLock) { _adminToken ??= token; }
|
||||
token = _adminToken!;
|
||||
}
|
||||
|
||||
var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>Get a shared viewer-authenticated HttpClient (lazy, cached token).</summary>
|
||||
private async Task<HttpClient> GetViewerClientAsync()
|
||||
{
|
||||
var token = _viewerToken;
|
||||
if (token is null)
|
||||
{
|
||||
token = await RegisterViewerAsync();
|
||||
lock (TokenLock) { _viewerToken ??= token; }
|
||||
token = _viewerToken!;
|
||||
}
|
||||
|
||||
var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
return client;
|
||||
}
|
||||
|
||||
private async Task<string> RegisterAdminAsync()
|
||||
{
|
||||
var email = $"admin-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register-admin", new
|
||||
{
|
||||
email,
|
||||
password = "AdminPwd123!",
|
||||
displayName = "Settings Admin"
|
||||
});
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
return content.GetProperty("accessToken").GetString()!;
|
||||
}
|
||||
|
||||
private async Task<string> RegisterViewerAsync()
|
||||
{
|
||||
var email = $"viewer-{Guid.NewGuid()}@heimdall.test";
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "ViewerPwd123!",
|
||||
displayName = "Settings Viewer"
|
||||
});
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
return content.GetProperty("accessToken").GetString()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a site + agent and return the agent ID.
|
||||
/// </summary>
|
||||
private async Task<Guid> CreateAgentAsync()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = $"SettingsTest_{Guid.NewGuid():N}",
|
||||
timezone = "UTC"
|
||||
});
|
||||
var siteContent = await siteResponse.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
var siteId = siteContent.GetProperty("id").GetGuid();
|
||||
|
||||
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
|
||||
var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
var token = tokenContent.GetProperty("token").GetString()!;
|
||||
|
||||
var agentResponse = await admin.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token,
|
||||
hostname = $"settings-agent-{Guid.NewGuid():N}",
|
||||
version = "1.0.0-test"
|
||||
});
|
||||
var agentContent = await agentResponse.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
return agentContent.GetProperty("agentId").GetGuid();
|
||||
}
|
||||
|
||||
// ──────────────────────────── AUTH ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task ListAll_WithoutAuth_ReturnsUnauthorized()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("api/settings");
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListAll_WithNonAdminUser_ReturnsForbidden()
|
||||
{
|
||||
var client = await GetViewerClientAsync();
|
||||
|
||||
var response = await client.GetAsync("api/settings");
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSetting_WithoutAuth_ReturnsUnauthorized()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key = "test.setting.unauth",
|
||||
value = "test",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSetting_WithNonAdminUser_ReturnsForbidden()
|
||||
{
|
||||
var client = await GetViewerClientAsync();
|
||||
|
||||
var response = await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key = $"test.setting.forbid.{Guid.NewGuid()}",
|
||||
value = "test",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
}
|
||||
|
||||
// ──────────────────────────── GLOBAL SETTINGS CRUD ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSetting_WithAdmin_ReturnsOk()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key = $"create.setting.{Guid.NewGuid()}",
|
||||
value = "test-value",
|
||||
category = "Testing",
|
||||
description = "Test setting created by integration test"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.GetProperty("key").GetString().ShouldNotBeNullOrEmpty();
|
||||
content.GetProperty("value").GetString().ShouldBe("test-value");
|
||||
content.GetProperty("category").GetString().ShouldBe("Testing");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSetting_DuplicateKey_ReturnsConflict()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
var key = $"dup.setting.{Guid.NewGuid()}";
|
||||
|
||||
var first = await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "first-value",
|
||||
category = "Testing"
|
||||
});
|
||||
first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var second = await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "second-value",
|
||||
category = "Testing"
|
||||
});
|
||||
second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListAll_WithAdmin_ReturnsAllSettings()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var key1 = $"list.test.1.{Guid.NewGuid()}";
|
||||
var key2 = $"list.test.2.{Guid.NewGuid()}";
|
||||
|
||||
await client.PostAsJsonAsync("api/settings", new { key = key1, value = "v1", category = "Testing" });
|
||||
await client.PostAsJsonAsync("api/settings", new { key = key2, value = "v2", category = "Testing" });
|
||||
|
||||
var response = await client.GetAsync("api/settings");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
var settings = content.EnumerateArray().ToList();
|
||||
|
||||
settings.Any(s => s.GetProperty("key").GetString() == key1).ShouldBeTrue();
|
||||
settings.Any(s => s.GetProperty("key").GetString() == key2).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByKey_ExistingKey_ReturnsSetting()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
var key = $"get.by.key.{Guid.NewGuid()}";
|
||||
|
||||
await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "get-value",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
var response = await client.GetAsync($"api/settings/{key}");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.GetProperty("key").GetString().ShouldBe(key);
|
||||
content.GetProperty("value").GetString().ShouldBe("get-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByKey_NonExistentKey_ReturnsNotFound()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.GetAsync("api/settings/nonexistent.setting.key");
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSetting_ExistingKey_ReturnsUpdatedValue()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
var key = $"update.setting.{Guid.NewGuid()}";
|
||||
|
||||
await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "original-value",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
var response = await client.PutAsJsonAsync($"api/settings/{key}", new
|
||||
{
|
||||
value = "updated-value",
|
||||
description = "Updated description"
|
||||
});
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.GetProperty("key").GetString().ShouldBe(key);
|
||||
content.GetProperty("value").GetString().ShouldBe("updated-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSetting_NonExistentKey_ReturnsNotFound()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.PutAsJsonAsync("api/settings/nonexistent.update.key", new
|
||||
{
|
||||
value = "updated-value"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSetting_ExistingKey_ReturnsNoContent()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
var key = $"delete.setting.{Guid.NewGuid()}";
|
||||
|
||||
await client.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "to-delete",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
var response = await client.DeleteAsync($"api/settings/{key}");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSetting_NonExistentKey_ReturnsNotFound()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.DeleteAsync("api/settings/nonexistent.delete.key");
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
// ──────────────────────────── AGENT EFFECTIVE CONFIG ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectiveConfig_WithGlobalSettings_ReturnsDictionary()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
var key = $"eff.config.{Guid.NewGuid()}";
|
||||
|
||||
await admin.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "eff-value",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
var response = await admin.GetAsync($"api/settings/agent/{agentId}");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.TryGetProperty(key, out var val).ShouldBeTrue();
|
||||
val.GetString().ShouldBe("eff-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectiveConfig_NonExistentAgent_ReturnsEmptyDictionary()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.GetAsync($"api/settings/agent/{Guid.NewGuid()}");
|
||||
|
||||
// The service returns global defaults (empty if none exist), not 404.
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.ValueKind.ShouldBe(System.Text.Json.JsonValueKind.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAgentOverride_WithValidRequest_ReturnsOverride()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
var key = $"override.set.{Guid.NewGuid()}";
|
||||
|
||||
await admin.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "global-value",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
var response = await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new
|
||||
{
|
||||
key,
|
||||
value = "override-value"
|
||||
});
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.GetProperty("key").GetString().ShouldBe(key);
|
||||
content.GetProperty("value").GetString().ShouldBe("override-value");
|
||||
content.GetProperty("agentId").GetGuid().ShouldBe(agentId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectiveConfig_WithOverride_ReturnsOverrideValue()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
var key = $"eff.override.{Guid.NewGuid()}";
|
||||
|
||||
await admin.PostAsJsonAsync("api/settings", new
|
||||
{
|
||||
key,
|
||||
value = "global-value",
|
||||
category = "Testing"
|
||||
});
|
||||
|
||||
await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new
|
||||
{
|
||||
key,
|
||||
value = "override-value"
|
||||
});
|
||||
|
||||
var response = await admin.GetAsync($"api/settings/agent/{agentId}");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
content.TryGetProperty(key, out var val).ShouldBeTrue();
|
||||
val.GetString().ShouldBe("override-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListAgentOverrides_WithOverrides_ReturnsOverrideList()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
var key1 = $"override.list.1.{Guid.NewGuid()}";
|
||||
var key2 = $"override.list.2.{Guid.NewGuid()}";
|
||||
|
||||
await admin.PostAsJsonAsync("api/settings", new { key = key1, value = "global1", category = "Testing" });
|
||||
await admin.PostAsJsonAsync("api/settings", new { key = key2, value = "global2", category = "Testing" });
|
||||
|
||||
await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key = key1, value = "override1" });
|
||||
await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key = key2, value = "override2" });
|
||||
|
||||
var response = await admin.GetAsync($"api/settings/agent/{agentId}/overrides");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var content = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
var overrides = content.EnumerateArray().ToList();
|
||||
|
||||
overrides.Count.ShouldBe(2);
|
||||
overrides.Any(o => o.GetProperty("key").GetString() == key1).ShouldBeTrue();
|
||||
overrides.Any(o => o.GetProperty("key").GetString() == key2).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveAgentOverride_ExistingOverride_ReturnsNoContent()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
var key = $"override.remove.{Guid.NewGuid()}";
|
||||
|
||||
await admin.PostAsJsonAsync("api/settings", new { key, value = "global", category = "Testing" });
|
||||
await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key, value = "override" });
|
||||
|
||||
var deleteResponse = await admin.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}");
|
||||
deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent);
|
||||
|
||||
var configResponse = await admin.GetAsync($"api/settings/agent/{agentId}");
|
||||
var configContent = await configResponse.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
|
||||
configContent.TryGetProperty(key, out var val).ShouldBeTrue();
|
||||
val.GetString().ShouldBe("global");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveAgentOverride_NonExistentOverride_ReturnsNotFound()
|
||||
{
|
||||
var admin = await GetAdminClientAsync();
|
||||
var agentId = await CreateAgentAsync();
|
||||
|
||||
var response = await admin.DeleteAsync($"api/settings/agent/{agentId}/overrides/nonexistent.override");
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
// ──────────────────────────── RELOAD ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task ReloadAllAgents_WithAdmin_ReturnsAccepted()
|
||||
{
|
||||
var client = await GetAdminClientAsync();
|
||||
|
||||
var response = await client.PostAsync("api/settings/reload", null);
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Accepted);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user