Implement US-13 patient authentication and persistent ownership

This commit is contained in:
Steffen committed 2026-10-05 11:10:22 +02:00
1 parent ebf50827d6
commit 0ce9b2b168
36 files changed
+1203 -28

No files matched your search

@@ -0,0 +1,67 @@
using System.Net;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
namespace ApiGateway.Security;
public sealed class PatientAccessMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization)
{
if (context.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null)
{
await next(context);
return;
}
if (context.User.Identity?.IsAuthenticated != true) { context.Response.StatusCode = 401; return; }
var route = context.Request.Path.Value ?? "";
var segments = route.Trim('/').Split('/');
if (context.User.IsInRole("Service"))
{
var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var allowed = context.Request.Method == "GET" && segments.Length == (service == "Observation" ? 3 : 4)
&& segments[0] == "api" && segments[1] == "patients" && Guid.TryParse(segments[2], out _)
&& (service == "Observation" || segments[3] == "observations");
if (!allowed) { context.Response.StatusCode = 403; return; }
await next(context);
return;
}
// US-14's professional access is implemented separately; deny by default meanwhile.
if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded) { context.Response.StatusCode = 403; return; }
if ((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST")
|| (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET"))
{
await next(context);
return;
}
try
{
var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync(
"api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted);
if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
ownResponse.EnsureSuccessStatusCode();
using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted));
var patientId = own.RootElement.GetProperty("patientId").GetGuid();
Guid requestedPatient;
if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out requestedPatient)) { }
else if (segments.Length == 3 && segments[0] == "api" && segments[1] == "observations"
&& Guid.TryParse(segments[2], out var observationId))
{
using var response = await clients.CreateClient("Observation").GetAsync($"api/observations/{observationId}", context.RequestAborted);
if (response.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
response.EnsureSuccessStatusCode();
using var observation = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.RequestAborted));
requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid();
}
else { context.Response.StatusCode = 404; return; }
if (requestedPatient != patientId) { context.Response.StatusCode = 404; return; }
await next(context);
}
catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); }
catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested)
{ await Results.Problem(statusCode: 504, title: "Ownership lookup timed out.").ExecuteAsync(context); }
}
}