Files
Heimdall/src/Heimdall.Web/Controllers/NotificationsController.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

102 lines
4.4 KiB
C#

using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Commands.MarkAllAsRead;
using Heimdall.Application.Notifications.Commands.MarkAsRead;
using Heimdall.Application.Notifications.Commands.UpdateConfig;
using Heimdall.Application.Notifications.Queries.GetConfig;
using Heimdall.Application.Notifications.Queries.GetNotifications;
using Heimdall.Application.Notifications.Queries.GetUnreadCount;
using Heimdall.Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using System.Security.Claims;
namespace Heimdall.Web.Controllers;
/// <summary>
/// In-app notifications for users — list, mark read, configure notification preferences.
/// </summary>
[ApiController]
[Route("api/notifications")]
[EnableRateLimiting("Api")]
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
public class NotificationsController : ControllerBase
{
private readonly IMediator _mediator;
public NotificationsController(IMediator mediator) => _mediator = mediator;
private Guid GetUserId() =>
Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
/// <summary>List notifications for the current user.</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<NotificationDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetNotifications(
[FromQuery] bool? isRead,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
{
var result = await _mediator.Send(new GetNotificationsQuery(GetUserId(), isRead, page, pageSize), ct);
return Ok(result);
}
/// <summary>Get unread notification count.</summary>
[HttpGet("unread-count")]
[ProducesResponseType(typeof(UnreadCountDto), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUnreadCount(CancellationToken ct = default)
{
var result = await _mediator.Send(new GetUnreadCountQuery(GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Mark a single notification as read.</summary>
[HttpPost("{id:guid}/read")]
[ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> MarkAsRead(Guid id, CancellationToken ct = default)
{
var result = await _mediator.Send(new MarkAsReadCommand(id, GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Mark all notifications as read.</summary>
[HttpPost("mark-all-read")]
[ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> MarkAllAsRead(CancellationToken ct = default)
{
var result = await _mediator.Send(new MarkAllAsReadCommand(GetUserId()), ct);
return Ok(result.Data);
}
/// <summary>Get notification configuration for the current user.</summary>
[HttpGet("config")]
[ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)]
public async Task<IActionResult> GetConfig(CancellationToken ct = default)
{
var result = await _mediator.Send(new GetNotificationConfigQuery(GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update notification configuration for the current user.</summary>
[HttpPut("config")]
[ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)]
public async Task<IActionResult> UpdateConfig([FromBody] UpdateNotificationConfigRequest request, CancellationToken ct = default)
{
var command = new UpdateNotificationConfigCommand(
GetUserId(),
request.EmailEnabled,
request.EmailAddress,
request.NtfyEnabled,
request.NtfyUrl,
request.Language,
request.DailyDigest,
request.WeeklyDigest,
request.SubscribedEvents);
var result = await _mediator.Send(command, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}