Files
Heimdall/src/Heimdall.Web/Controllers/EventsController.cs
T
Arnaud Dartois 22ebcaf73a fix(web): 401 au premier rendu — cookie propagé aux appels API internes (Fixes #23)
Symptôme : après F5 sur une page authentifiée, les appels API des pages
(api/stats, api/agents…) renvoyaient 401 jusqu'à la connexion du circuit
Blazor. Cause : au rendu initial, AuthState est peuplé depuis le cookie
(AccessToken null → pas de Bearer) et le HttpClient serveur n'envoie pas
le cookie navigateur ; les contrôleurs n'acceptaient que JwtBearer.

Correctif :
- SameOriginHttpMessageHandler : propage le cookie d'authentification du
  HttpContext courant vers la requête interne quand aucun Bearer n'est
  posé (le Bearer du circuit prend le relais ensuite).
- Contrôleurs API humains : AuthenticationSchemes = 'JwtBearer,Cookies'
  (77 occurrences) — le cookie porte les mêmes claims de rôle/permission
  que le JWT.
- Vérifié en réel : F5 /dashboard → plus de snackbar 401, console propre,
  api/agents validé et 200 côté serveur. 182 tests Web verts.
2026-08-11 08:32:41 +02:00

119 lines
5.2 KiB
C#

using Heimdall.Application.DTOs;
using Heimdall.Application.Events.Commands.CreateEvent;
using Heimdall.Application.Events.Commands.AttachSnapshot;
using Heimdall.Application.Events.Commands.DeleteEvent;
using Heimdall.Application.Events.Queries.GetEvent;
using Heimdall.Application.Events.Queries.GetEvents;
using Heimdall.Application.Events.Queries.GetRecentByCamera;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
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 IMediator _mediator;
public EventsController(IMediator mediator) => _mediator = mediator;
/// <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 command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt);
var result = await _mediator.Send(command, 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,Cookies", 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 _mediator.Send(new GetEventQuery(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,Cookies", 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] string? q,
[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 result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q), ct);
return Ok(result.Data);
}
/// <summary>Get recent events for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", 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 _mediator.Send(new GetRecentByCameraQuery(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 _mediator.Send(new AttachSnapshotCommand(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,Cookies", 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 _mediator.Send(new DeleteEventCommand(id), ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}