Files
HealthAppRepository/src/ApiGateway/Security/PatientAccessMiddleware.cs
T

93 lines
4.9 KiB
C#

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,
ProfessionalAssignments assignments)
{
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 patientRoute = segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out _);
var allowed = context.Request.Method == "GET" && patientRoute && (service switch
{
"Observation" => segments.Length == 3,
"Insights" => segments.Length == 4 && segments[3] == "observations",
"HealthOverview" => segments.Length == 3 ||
(segments.Length == 4 && segments[3] == "insights") ||
(segments.Length == 5 && segments[3] == "observations" && segments[4] == "latest"),
_ => false
});
if (!allowed) { context.Response.StatusCode = 403; return; }
await next(context);
return;
}
var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded;
if (professional)
{
if (context.Request.Method != "GET") { context.Response.StatusCode = 403; return; }
if (route.Equals("/api/professionals/me/patients", StringComparison.OrdinalIgnoreCase))
{
await next(context);
return;
}
}
else if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded)
{ context.Response.StatusCode = 403; return; }
if (!professional &&
((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)!;
Guid? patientId = null;
if (!professional)
{
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));
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; }
var permitted = professional ? assignments.IsAssigned(accountId, requestedPatient) : requestedPatient == patientId;
if (!permitted) { 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); }
}
}