feat(api+web): merge REST API and Blazor UI into single process

Previously the API (heimdall-central) and Blazor UI (heimdall-web) ran as
separate containers with the Blazor Server making internal HTTP calls to
the API. This caused the Blazor circuit to disconnect when the API was
unreachable (network error → "Une erreur réseau est survenue").

Now both serve from the same .NET process on the same port:
- All 16 API controllers, ExceptionFilter, and SignalR hubs integrated
  into Heimdall.Web
- JWT auth, CORS, rate limiting configured in the unified Program.cs
- Dockerfile.central entrypoint runs web/Heimdall.Web.dll
- docker-compose simplified: heimdall-central service removed
- CI publishes heimdall-web image instead of heimdall-central

Also fixes timezone validation on Alpine/tzdata-less environments
and enables FluentValidation auto-validation in the API project.
This commit is contained in:
Arnaud Dartois committed 2026-07-20 10:30:01 +00:00
1 parent 892ca88de8
commit 562aabdfc8
30 files changed
+1969 -99

No files matched your search

@@ -0,0 +1,91 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/agents")]
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly IAgentService _agentService;
public AgentsController(IAgentService agentService) => _agentService = agentService;
/// <summary>Register an agent using a site registration token.</summary>
[AllowAnonymous]
[HttpPost("register")]
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Register(
[FromBody] RegisterAgentRequest request, CancellationToken ct)
{
// Extract API key from header (may be empty for registration)
var apiKey = Request.Headers.Authorization.FirstOrDefault()
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
var result = await _agentService.RegisterAsync(request, apiKey, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Send heartbeat from agent (API Key auth).</summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpPost("{id:guid}/heartbeat")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Heartbeat(
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
{
var result = await _agentService.HeartbeatAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get agent details (JWT auth).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _agentService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List agents for a site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>List all agents across all sites.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListAll(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _agentService.ListAllAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -0,0 +1,127 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera-to-agent assignment management.
/// Controls how cameras are distributed across agents in a site,
/// with support for manual assignment, strategy-based balancing,
/// and failover.
/// </summary>
[ApiController]
[Route("api/assignments")]
[EnableRateLimiting("Api")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class AssignmentsController : ControllerBase
{
private readonly ICameraAssignmentService _assignmentService;
public AssignmentsController(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
/// <summary>Assign a single camera to a specific agent.</summary>
[HttpPost]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AssignCamera([FromBody] AssignRequest request, CancellationToken ct)
{
var result = await _assignmentService.AssignCameraAsync(
request.CameraId, request.AgentId, request.Reason ?? "manual", ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Assign all cameras in a site using a strategy.</summary>
[HttpPost("site/{siteId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default)
{
if (!Enum.TryParse<AssignmentStrategy>(strategy, true, out var parsed))
return BadRequest(new { error = $"Invalid strategy: {strategy}. Valid: RoundRobin, GpuPriority, LeastCameras" });
var result = await _assignmentService.AssignSiteCamerasAsync(siteId, parsed, ct);
var assignedCount = result.Data;
return result.IsSuccess
? Ok(new AssignmentResult(assignedCount))
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Trigger failover for an offline agent — reassign its cameras.</summary>
[HttpPost("failover/{agentId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> FailoverAgent(Guid agentId, CancellationToken ct)
{
var result = await _assignmentService.FailoverAgentAsync(agentId, ct);
return result.IsSuccess
? Ok(new FailoverResult(result.Data?.Count ?? 0))
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Get the active assignment for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}")]
[ProducesResponseType(typeof(AssignmentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetCameraAssignment(Guid cameraId, CancellationToken ct)
{
var assignment = await _assignmentService.GetActiveAssignmentAsync(cameraId, ct);
if (assignment is null)
return NotFound(new { error = "Camera not assigned" });
return Ok(new AssignmentResponse(
assignment.CameraId,
assignment.AgentId,
assignment.Agent.Name,
assignment.Reason,
assignment.AssignedAt));
}
/// <summary>Get all active assignments (workload) for an agent.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("agent/{agentId:guid}")]
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAgentAssignments(Guid agentId, CancellationToken ct)
{
var assignments = await _assignmentService.GetAgentAssignmentsAsync(agentId, ct);
return Ok(assignments.Select(a => new AssignmentResponse(
a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList());
}
/// <summary>Get assignment history for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}/history")]
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetCameraHistory(Guid cameraId, CancellationToken ct)
{
var history = await _assignmentService.GetCameraHistoryAsync(cameraId, ct);
return Ok(history.Select(a => new AssignmentResponse(
a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList());
}
/// <summary>Release a camera from its current agent.</summary>
[HttpDelete("camera/{cameraId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ReleaseCamera(Guid cameraId, CancellationToken ct)
{
var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -0,0 +1,36 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/audit-logs")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[EnableRateLimiting("Api")]
public class AuditLogsController : ControllerBase
{
private readonly IAuditLogService _auditLogService;
public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService;
/// <summary>List audit log entries with optional filtering.</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<AuditLogResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> List(
[FromQuery] string? resourceType,
[FromQuery] string? action,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
{
var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -0,0 +1,128 @@
using System.Security.Claims;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/auth")]
[EnableRateLimiting("Auth")]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
private readonly IWebHostEnvironment _env;
public AuthController(IAuthService authService, IWebHostEnvironment env)
{
_authService = authService;
_env = env;
}
/// <summary>Register a new user.</summary>
[AllowAnonymous]
[HttpPost("register")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken ct)
{
var result = await _authService.RegisterAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Authenticate a user.</summary>
[AllowAnonymous]
[HttpPost("login")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
{
var result = await _authService.LoginAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Verify a 2FA code.</summary>
[AllowAnonymous]
[HttpPost("2fa/verify")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
{
var result = await _authService.Verify2faAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Refresh an authentication token.</summary>
[AllowAnonymous]
[HttpPost("refresh")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct)
{
var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Change the current user's password.</summary>
[Authorize]
[HttpPost("change-password")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> ChangePassword(
[FromBody] ChangePasswordRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _authService.ChangePasswordAsync(
userId, request.CurrentPassword, request.NewPassword, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).</summary>
[AllowAnonymous]
[HttpPost("register-admin")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
{
if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment())
return NotFound();
var result = await _authService.RegisterAdminAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Logout — revoke the current refresh token.</summary>
[Authorize]
[HttpPost("logout")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> Logout([FromBody] LogoutRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
await _authService.LogoutAsync(userId, request.RefreshToken, ct);
return Ok();
}
}
@@ -0,0 +1,86 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/cameras")]
[EnableRateLimiting("Api")]
public class CamerasController : ControllerBase
{
private readonly ICameraService _cameraService;
public CamerasController(ICameraService cameraService) => _cameraService = cameraService;
/// <summary>Create a new camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a camera by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _cameraService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List cameras by site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<CameraResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Update a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _cameraService.DeleteAsync(id, ct);
return result.IsSuccess
? NoContent()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -0,0 +1,152 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera discovery endpoints.
/// Provides network probing, camera database search, stream URL building,
/// stream testing, and discovery confirmation.
/// </summary>
[ApiController]
[Route("api/discovery")]
[EnableRateLimiting("Api")]
public class DiscoveryController : ControllerBase
{
private readonly ICameraDiscoveryService _discoveryService;
public DiscoveryController(ICameraDiscoveryService discoveryService)
{
_discoveryService = discoveryService;
}
/// <summary>Probe a single IP address for camera services.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("probe")]
[ProducesResponseType(typeof(ProbeResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ProbeIp([FromBody] ProbeRequest request, CancellationToken ct)
{
var result = await _discoveryService.ProbeIpAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Scan a subnet for camera devices.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("scan")]
[ProducesResponseType(typeof(IReadOnlyList<ProbeResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ScanSubnet([FromBody] ScanRequest request, CancellationToken ct)
{
var result = await _discoveryService.ScanSubnetAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Search the built-in camera database by brand, model, or preset.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("search")]
[ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> SearchDatabase([FromQuery] string? q, CancellationToken ct)
{
var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct);
return Ok(result.Data);
}
/// <summary>Build stream URLs from camera database entries.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpPost("build-urls")]
[ProducesResponseType(typeof(StreamBuildResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> BuildStreamUrls([FromBody] StreamBuildRequest request, CancellationToken ct)
{
var result = await _discoveryService.BuildStreamUrlsAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Test stream URLs. Returns a session ID for polling.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("test-streams")]
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> TestStreams([FromBody] StreamTestRequest request, CancellationToken ct)
{
var result = await _discoveryService.TestStreamsAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Poll a stream test session for updated results.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("test/{sessionId:guid}")]
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetTestSession(Guid sessionId, CancellationToken ct)
{
var result = await _discoveryService.GetTestSessionAsync(sessionId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Get a screenshot from a stream test session.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("test/{sessionId:guid}/screenshot/{index}")]
[ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetScreenshot(Guid sessionId, int index, CancellationToken ct)
{
var screenshot = await _discoveryService.GetScreenshotAsync(sessionId, index, ct);
if (screenshot is null)
return NotFound(new { error = "Screenshot not available" });
return File(screenshot, "image/jpeg");
}
/// <summary>Cancel a running stream test session.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("test/{sessionId:guid}/cancel")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> CancelTestSession(Guid sessionId, CancellationToken ct)
{
var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Check if a camera already exists for this IP/MAC (anti-duplication).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpPost("check")]
[ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct)
{
var result = await _discoveryService.CheckDuplicateAsync(request, ct);
return Ok(result.Data);
}
/// <summary>Confirm a discovery result and create a Camera entity.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("confirm")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ConfirmDiscovery([FromBody] ConfirmDiscoveryRequest request, CancellationToken ct)
{
var result = await _discoveryService.ConfirmDiscoveryAsync(request, ct);
if (result.IsSuccess)
return Ok(result.Data);
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -0,0 +1,111 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera detection events — motion, person, vehicle, face recognition, etc.
/// Agents POST events as they detect them; users GET filtered views.
/// </summary>
[ApiController]
[Route("api/events")]
[EnableRateLimiting("Api")]
public class EventsController : ControllerBase
{
private readonly ICameraEventService _eventService;
public EventsController(ICameraEventService eventService) => _eventService = eventService;
/// <summary>Record a new detection event (called by agents).</summary>
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPost]
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCameraEventRequest request, CancellationToken ct)
{
var result = await _eventService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a single event by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _eventService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Query events with filters. Supports pagination.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<CameraEventResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> Query(
[FromQuery] Guid? cameraId,
[FromQuery] Guid? siteId,
[FromQuery] string? type,
[FromQuery] DateTime? from,
[FromQuery] DateTime? to,
[FromQuery] double? minConfidence,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
CancellationToken ct = default)
{
EventType? parsedType = null;
if (type is not null && Enum.TryParse<EventType>(type, true, out var t))
parsedType = t;
var filter = new CameraEventFilterRequest(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize);
var result = await _eventService.QueryAsync(filter, ct);
return Ok(result.Data);
}
/// <summary>Get recent events for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}")]
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
{
var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct);
return Ok(result.Data);
}
/// <summary>Attach a snapshot URL to an event (called by agents after upload).</summary>
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/snapshot")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct)
{
var result = await _eventService.AttachSnapshotAsync(id, request.SnapshotUrl, request.ThumbUrl, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Delete an event.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _eventService.DeleteAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -0,0 +1,123 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// CRUD management for user groups and their members (Admin only).
/// </summary>
[ApiController]
[Route("api/groups")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class GroupsController : ControllerBase
{
private readonly IGroupService _groupService;
public GroupsController(IGroupService groupService) => _groupService = groupService;
/// <summary>List all groups (Admin only).</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<GroupResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _groupService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get a group by ID.</summary>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _groupService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Create a new group (Admin only).</summary>
[HttpPost]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateGroupRequest request, CancellationToken ct)
{
var result = await _groupService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update a group (Admin only).</summary>
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateGroupRequest request, CancellationToken ct)
{
var result = await _groupService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a group (soft-delete, Admin only).</summary>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _groupService.DeleteAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Add a user to a group (Admin only).</summary>
[HttpPost("{groupId:guid}/users/{userId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AddUser(Guid groupId, Guid userId, CancellationToken ct)
{
var result = await _groupService.AddUserAsync(groupId, userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Remove a user from a group (Admin only).</summary>
[HttpDelete("{groupId:guid}/users/{userId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> RemoveUser(Guid groupId, Guid userId, CancellationToken ct)
{
var result = await _groupService.RemoveUserAsync(groupId, userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get all members of a group (Admin only).</summary>
[HttpGet("{groupId:guid}/users")]
[ProducesResponseType(typeof(IReadOnlyList<GroupMemberResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetMembers(Guid groupId, CancellationToken ct)
{
var result = await _groupService.GetMembersAsync(groupId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Heimdall.Api.Controllers;
[ApiController]
public class HealthController : ControllerBase
{
/// <summary>
/// Liveness probe — always returns OK if the process is running.
/// </summary>
[HttpGet("/healthz")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
/// <summary>
/// Readiness probe — checks if the database is reachable.
/// Uses ASP.NET Core health checks infrastructure.
/// </summary>
[HttpGet("/readyz")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
public async Task<IActionResult> Readiness(
[FromServices] HealthCheckService healthCheckService,
CancellationToken ct)
{
var report = await healthCheckService.CheckHealthAsync(
_ => true, ct);
return report.Status == HealthStatus.Healthy
? Ok(new { status = "healthy", timestamp = DateTime.UtcNow })
: StatusCode(503, new { status = "unhealthy", errors = report.Entries });
}
}
@@ -0,0 +1,76 @@
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>Response DTO for a single permission with its display name and category.</summary>
public record PermissionInfo(string Name, string DisplayName, string Category);
/// <summary>Response DTO for a list of permissions.</summary>
public record PermissionsListResponse(IReadOnlyList<PermissionInfo> Permissions);
[ApiController]
[Route("api/permissions")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class PermissionsController : ControllerBase
{
private static readonly Dictionary<string, string> CategoryMap = new()
{
["Site."] = "Sites",
["Camera."] = "Caméras",
["Event."] = "Événements",
["Person."] = "Personnes",
["Admin."] = "Administration",
};
private static readonly Dictionary<string, string> DisplayNames = new()
{
[AppPermissions.SiteRead] = "Lecture des sites",
[AppPermissions.SiteWrite] = "Écriture des sites",
[AppPermissions.SiteDelete] = "Suppression des sites",
[AppPermissions.CameraRead] = "Lecture des caméras",
[AppPermissions.CameraWrite] = "Écriture des caméras",
[AppPermissions.CameraLive] = "Visionnage en direct",
[AppPermissions.CameraRecord] = "Enregistrement",
[AppPermissions.CameraSnapshot] = "Captures d'écran",
[AppPermissions.EventRead] = "Lecture des événements",
[AppPermissions.PersonRead] = "Lecture des personnes",
[AppPermissions.PersonWrite] = "Écriture des personnes",
[AppPermissions.AdminManage] = "Gestion de l'administration",
[AppPermissions.AdminUsers] = "Gestion des utilisateurs",
[AppPermissions.AdminApiKeys] = "Gestion des clés API",
[AppPermissions.AdminJobs] = "Gestion des tâches",
};
/// <summary>Returns all available permissions grouped by category.</summary>
[HttpGet]
[ProducesResponseType(typeof(PermissionsListResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult List()
{
var allPermissions = AppPermissions.RolePermissions.Values
.SelectMany(p => p)
.Distinct()
.OrderBy(p => p)
.Select(p => new PermissionInfo(
p,
DisplayNames.GetValueOrDefault(p, p),
GetCategory(p)))
.ToList();
return Ok(new PermissionsListResponse(allPermissions));
}
private static string GetCategory(string permission)
{
foreach (var (prefix, category) in CategoryMap)
{
if (permission.StartsWith(prefix, StringComparison.Ordinal))
return category;
}
return "Autres";
}
}
@@ -0,0 +1,82 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/persons")]
[EnableRateLimiting("Api")]
public class PersonsController : ControllerBase
{
private readonly IPersonService _personService;
public PersonsController(IPersonService personService) => _personService = personService;
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreatePersonRequest request, CancellationToken ct)
{
var result = await _personService.CreateAsync(request, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdatePersonRequest request, CancellationToken ct)
{
var result = await _personService.UpdateAsync(id, request, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _personService.GetByIdAsync(id, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet]
public async Task<IActionResult> GetAll([FromQuery] string? category, CancellationToken ct)
{
var result = await _personService.GetAllAsync(category, ct);
return Ok(result.Data);
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _personService.DeleteAsync(id, ct);
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPost("{personId:guid}/faces")]
public async Task<IActionResult> RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct)
{
var result = await _personService.RegisterFaceAsync(request with { PersonId = personId }, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet("{personId:guid}/faces")]
public async Task<IActionResult> GetFaces(Guid personId, CancellationToken ct)
{
var result = await _personService.GetFacesAsync(personId, ct);
return Ok(result.Data);
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpDelete("faces/{faceId:guid}")]
public async Task<IActionResult> DeleteFace(Guid faceId, CancellationToken ct)
{
var result = await _personService.DeleteFaceAsync(faceId, ct);
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -0,0 +1,45 @@
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>Response DTO for a role with its permissions.</summary>
public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
/// <summary>Response DTO for a list of roles.</summary>
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
[ApiController]
[Route("api/roles")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class RolesController : ControllerBase
{
/// <summary>Returns all roles with their associated permissions.</summary>
[HttpGet]
[ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult List()
{
var roles = AppPermissions.RolePermissions
.Select(kvp => new RoleResponse(kvp.Key, kvp.Value))
.ToList();
return Ok(new RolesListResponse(roles));
}
/// <summary>Returns a single role with its permissions.</summary>
[HttpGet("{name}")]
[ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult GetByName(string name)
{
if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions))
return NotFound(new { error = $"Role '{name}' not found" });
return Ok(new RoleResponse(name, permissions));
}
}
@@ -0,0 +1,225 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/settings")]
[Authorize]
[EnableRateLimiting("Api")]
public class SettingsController : ControllerBase
{
private readonly ISettingService _settingService;
private readonly IConfigBroadcastService _broadcast;
private readonly ILogger<SettingsController> _logger;
public SettingsController(
ISettingService settingService,
IConfigBroadcastService broadcast,
ILogger<SettingsController> logger)
{
_settingService = settingService;
_broadcast = broadcast;
_logger = logger;
}
/// <summary>List all global settings (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet]
[ProducesResponseType(typeof(List<AppSettingDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> ListAll(CancellationToken ct)
{
var result = await _settingService.GetAllSettingsAsync(ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
// Redact sensitive values before returning to client
var redacted = result.Data!.Select(s => s with
{
Value = RedactValue(s.ValueType, s.Value, s.Key)
}).ToList();
return Ok(redacted);
}
/// <summary>Get a global setting by key (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("{key}")]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetByKey(string key, CancellationToken ct)
{
var result = await _settingService.GetSettingByKeyAsync(key, ct);
if (!result.IsSuccess)
return NotFound(new { error = result.Error });
// Redact sensitive values before returning to client
var redacted = result.Data! with
{
Value = RedactValue(result.Data.ValueType, result.Data.Value, result.Data.Key)
};
return Ok(redacted);
}
/// <summary>Create a new global setting (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPost]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Create(
[FromBody] CreateAppSettingRequest request, CancellationToken ct)
{
var result = await _settingService.CreateSettingAsync(request, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
_logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
return Ok(result.Data);
}
/// <summary>Update a global setting (Admin only). Broadcasts the change to all agents.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPut("{key}")]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
{
var result = await _settingService.UpdateSettingAsync(key, request, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
_logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
return Ok(result.Data);
}
/// <summary>Delete a global setting (Admin only). Broadcasts the change to all agents.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpDelete("{key}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(string key, CancellationToken ct)
{
var result = await _settingService.DeleteSettingAsync(key, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
await _broadcast.NotifyAllAgentsReload(ct);
_logger.LogInformation("Deleted global setting {Key}", key);
return NoContent();
}
/// <summary>
/// Get the effective configuration for an agent: global defaults merged with
/// per-agent overrides (Agent or Admin only).
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("agent/{agentId:guid}")]
[ProducesResponseType(typeof(Dictionary<string, string>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
{
var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("agent/{agentId:guid}/overrides")]
[ProducesResponseType(typeof(List<AgentSettingDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ListAgentOverrides(Guid agentId, CancellationToken ct)
{
var result = await _settingService.GetAgentSettingsAsync(agentId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>
/// Set (create or update) a per-agent setting override (Admin only).
/// Broadcasts the change to the affected agent in real-time.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPut("agent/{agentId:guid}/overrides")]
[ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> SetAgentOverride(
Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct)
{
var result = await _settingService.SetAgentSettingAsync(agentId, request, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct);
_logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}",
agentId, result.Data.Key, RedactValue(null, result.Data.Value, result.Data.Key));
return Ok(result.Data);
}
/// <summary>
/// Remove a per-agent setting override (Admin only).
/// Broadcasts a reload notification to the affected agent.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpDelete("agent/{agentId:guid}/overrides/{key}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> RemoveAgentOverride(Guid agentId, string key, CancellationToken ct)
{
var result = await _settingService.RemoveAgentSettingAsync(agentId, key, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct);
_logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key);
return NoContent();
}
/// <summary>
/// Broadcast a "ConfigReload" signal to all connected agents so they
/// re-fetch their full configuration (Admin only).
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPost("reload")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> ReloadAllAgents(CancellationToken ct)
{
await _broadcast.NotifyAllAgentsReload(ct);
_logger.LogInformation("Broadcast ConfigReload to all agents");
return Accepted(new { message = "Config reload broadcast to all connected agents" });
}
private static string RedactValue(string? valueType, string value, string? key = null)
{
if (valueType is not null && valueType.Contains("password", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (valueType is not null && valueType.Contains("token", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("password", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("token", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("secret", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
return value;
}
}
@@ -0,0 +1,108 @@
using System.Security.Claims;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/sites")]
[EnableRateLimiting("Api")]
public class SitesController : ControllerBase
{
private readonly ISiteService _siteService;
public SitesController(ISiteService siteService) => _siteService = siteService;
/// <summary>Create a new site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost]
[ProducesResponseType(typeof(SiteWithTokenResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(
[FromBody] CreateSiteRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized(new { error = "Invalid user identity" });
var result = await _siteService.CreateAsync(request, userId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>List all sites.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<SiteResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _siteService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get a site by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _siteService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Update a site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
{
var result = await _siteService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _siteService.DeleteAsync(id, ct);
return result.IsSuccess
? NoContent()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Generate a new agent registration token (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost("{id:guid}/tokens")]
[ProducesResponseType(typeof(RegistrationTokenResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GenerateToken(Guid id, CancellationToken ct)
{
var result = await _siteService.GenerateTokenAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -0,0 +1,44 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/stats")]
[EnableRateLimiting("Api")]
public class StatsController : ControllerBase
{
private readonly IStatsService _statsService;
public StatsController(IStatsService statsService) => _statsService = statsService;
/// <summary>Get system-wide statistics.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetStats(CancellationToken ct)
{
var result = await _statsService.GetStatsAsync(ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(new { data = result.Data, timestamp = DateTime.UtcNow });
}
/// <summary>Get agent-specific KPIs for the dashboard.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("agent-stats")]
[ProducesResponseType(typeof(List<AgentStatItem>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetAgentStats(CancellationToken ct)
{
var result = await _statsService.GetAgentStatsAsync(ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -0,0 +1,197 @@
using System.Security.Claims;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/users")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[EnableRateLimiting("Api")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService) => _userService = userService;
/// <summary>List all users (Admin only).</summary>
[HttpGet]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(PagedResult<UserResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _userService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get the current user's profile.</summary>
[HttpGet("me")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetMyProfile(CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _userService.GetByIdAsync(userId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Update the current user's own profile.</summary>
[HttpPut("me")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> UpdateMyProfile(
[FromBody] UpdateUserRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _userService.UpdateAsync(userId, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a user by ID (Admin only).</summary>
[HttpGet("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _userService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Create a new user (Admin only).</summary>
[HttpPost]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
{
var result = await _userService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update a user (Admin only).</summary>
[HttpPut("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct)
{
var result = await _userService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Assign roles to a user (Admin only).</summary>
[HttpPut("{id:guid}/roles")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignRoles(
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
{
var result = await _userService.AssignRolesAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Assign sites to a user (Admin only).</summary>
[HttpPut("{id:guid}/sites")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignSites(
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
{
var result = await _userService.AssignSitesAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Reset a user's password (Admin only).</summary>
[HttpPost("{id:guid}/reset-password")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
{
var result = await _userService.ResetPasswordAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a user account (Admin only). Self-deletion is forbidden.
/// Cannot delete the last administrator.</summary>
[HttpDelete("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var currentUserId))
return Unauthorized();
var result = await _userService.DeleteAsync(id, currentUserId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Lock a user account (Admin only).</summary>
[HttpPost("{id:guid}/lock")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
{
var result = await _userService.LockAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Unlock a user account (Admin only).</summary>
[HttpPost("{id:guid}/unlock")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
{
var result = await _userService.UnlockAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}