Establish single host with preserved login and public guidance

This commit is contained in:
Steffen committed 2026-10-14 11:28:10 +02:00
1 parent cee98e7035
commit 523cfbf42e
20 files changed
+1784

No files matched your search

@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /></ItemGroup>
</Project>
@@ -0,0 +1,39 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using HealthApp.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace HealthApp.Controllers;
[ApiController]
[Route("api/authentication")]
public sealed class AuthenticationController(PrototypeAccounts accounts,
IOptionsMonitor<BearerTokenOptions> options) : ControllerBase
{
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
var account = accounts.Verify(request.AccountId, request.Password);
if (account is null) return Unauthorized(new { title = "Invalid credentials." });
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, account.AccountId),
new Claim(ClaimTypes.Role, account.Role)
}, "Bearer"));
var settings = options.Get("Bearer");
var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration);
// Use the framework's ticket protector and bearer validation. No refresh endpoint/token.
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { ExpiresUtc = expiry }, "Bearer");
Response.Headers.CacheControl = "no-store";
Response.Headers.Pragma = "no-cache";
return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer",
expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role });
}
public sealed record LoginRequest([Required] string AccountId, [Required] string Password);
}
@@ -0,0 +1,14 @@
using HealthApp.Guidance;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace HealthApp.Controllers;
[ApiController, AllowAnonymous, Route("api/measurement-guidance")]
public sealed class MeasurementGuidanceController(GuidanceQueries guidance) : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
{
try { return Ok(guidance.Get(setting, activityCondition)); }
catch (ArgumentException e) { return Problem(statusCode:400, title:e.Message); }
}
}
@@ -0,0 +1,17 @@
using System.Security.Claims;
using HealthApp.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace HealthApp.Controllers;
[ApiController]
[Authorize(Policy = "HealthcareProfessional")]
[Route("api/professionals/me/patients")]
public sealed class ProfessionalController(ProfessionalAssignments assignments) : ControllerBase
{
[HttpGet]
public IActionResult GetAssignedPatients() =>
Ok(assignments.GetPatients(User.FindFirstValue(ClaimTypes.NameIdentifier)!)
.Select(patientId => new { patientId }));
}
+4
View File
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /></ItemGroup>
</Project>
+43
View File
@@ -0,0 +1,43 @@
using HealthApp.Guidance;
using HealthApp.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Authentication.BearerToken;
namespace HealthApp;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<PrototypeAccounts>();
builder.Services.AddSingleton<ProfessionalAssignments>();
builder.Services.AddSingleton<GuidanceQueries>();
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((o,c,l)=> {
var keys=c["Authentication:KeyDirectory"];
if(string.IsNullOrWhiteSpace(keys)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
o.XmlRepository=new Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository(new DirectoryInfo(keys),l);
});
builder.Services.AddAuthentication("Bearer").AddBearerToken("Bearer",o=>o.BearerTokenExpiration=TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes",30)));
builder.Services.AddAuthorization(o=> {
o.FallbackPolicy=new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
foreach(var role in new[]{"Patient","HealthcareProfessional"}) o.AddPolicy(role,p=>p.RequireRole(role).RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
});
var app=builder.Build();
var lifetime=app.Configuration.GetValue("Authentication:TokenLifetimeMinutes",30);
if(lifetime is <=0 or >1440)throw new InvalidOperationException("Invalid token lifetime.");
if(string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))throw new InvalidOperationException("Authentication:KeyDirectory is required.");
_=app.Services.GetRequiredService<PrototypeAccounts>();
_=app.Services.GetRequiredService<ProfessionalAssignments>();
app.UseExceptionHandler();
app.Use(async(ctx,next)=> {
if(!app.Environment.IsDevelopment() && !ctx.Request.IsHttps){ctx.Response.StatusCode=400;return;}
if(!ctx.Request.Path.StartsWithSegments("/api/measurement-guidance"))ctx.Response.Headers.CacheControl="no-store";
await next(ctx);
});
app.UseAuthentication();app.UseAuthorization();app.MapControllers();
await app.RunAsync();
}
}
@@ -0,0 +1,24 @@
namespace HealthApp.Security;
// Application access data, separate from credentials and token contents.
public sealed class ProfessionalAssignments
{
private readonly Dictionary<string, Guid[]> assignments;
public ProfessionalAssignments(IConfiguration configuration)
{
assignments = configuration.GetSection("Access:ProfessionalAssignments")
.Get<Dictionary<string, Guid[]>>() ?? new(StringComparer.Ordinal);
foreach (var accountId in assignments.Keys.ToArray())
{
if (string.IsNullOrWhiteSpace(accountId) || assignments[accountId].Any(id => id == Guid.Empty))
throw new InvalidOperationException("Professional assignments require an account identifier and nonempty patient identifiers.");
assignments[accountId] = assignments[accountId].Distinct().Order().ToArray();
}
}
public IReadOnlyList<Guid> GetPatients(string accountId) =>
assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty<Guid>();
public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId);
}
@@ -0,0 +1,39 @@
using Microsoft.AspNetCore.Identity;
namespace HealthApp.Security;
public sealed class PrototypeAccount
{
public string AccountId { get; set; } = "";
public string Role { get; set; } = "Patient";
public string PasswordHash { get; set; } = "";
}
public sealed class PrototypeAccounts
{
private readonly Dictionary<string, PrototypeAccount> accounts;
private readonly PasswordHasher<PrototypeAccount> hasher = new();
private readonly PrototypeAccount dummy = new() { AccountId = "invalid" };
public PrototypeAccounts(IConfiguration configuration)
{
var configured = configuration.GetSection("Authentication:Accounts").Get<PrototypeAccount[]>() ?? [];
if (configured.Length == 0 || configured.Any(a => string.IsNullOrWhiteSpace(a.AccountId) || a.AccountId.Length > 128 || a.AccountId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_')) || string.IsNullOrWhiteSpace(a.PasswordHash)
|| a.Role is not ("Patient" or "HealthcareProfessional")))
throw new InvalidOperationException("Authentication accounts require an identifier, password hash and supported role.");
accounts = configured.ToDictionary(a => a.AccountId, StringComparer.Ordinal);
dummy.PasswordHash = hasher.HashPassword(dummy, Guid.NewGuid().ToString());
}
public PrototypeAccount? Verify(string accountId, string password)
{
var known = accounts.TryGetValue(accountId, out var account);
account ??= dummy;
try
{
var result = hasher.VerifyHashedPassword(account, account.PasswordHash, password);
return known && result != PasswordVerificationResult.Failed ? account : null;
}
catch (FormatException) { return null; }
}
}
+4
View File
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /></ItemGroup>
</Project>
+56
View File
@@ -0,0 +1,56 @@
namespace HealthApp.Guidance;
// Content preserved from the pinned baseline; no new clinical review is implied.
public sealed class GuidanceQueries
{
public object Get(string? setting, string? activityCondition)
{
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
var requestedActivity = string.IsNullOrWhiteSpace(activityCondition) ? "Unknown" : activityCondition.Trim();
if (!new[] { "Home", "Clinic", "Other", "Unknown" }.Contains(requestedSetting, StringComparer.OrdinalIgnoreCase))
throw new ArgumentException("Unsupported measurement setting.");
if (!new[] { "AtRest", "DuringActivity", "AfterActivity", "Unknown" }.Contains(requestedActivity, StringComparer.OrdinalIgnoreCase))
throw new ArgumentException("Unsupported activity condition.");
var available = requestedSetting.Equals("Home", StringComparison.OrdinalIgnoreCase)
|| requestedSetting.Equals("Unknown", StringComparison.OrdinalIgnoreCase);
return new
{
available,
requestedSetting,
requestedActivityCondition = requestedActivity,
applicableSetting = available ? "Home" : null,
applicableActivityCondition = available ? "AtRest" : null,
reviewedOn = available ? "2026-10-04" : null,
explanation = available
? "These instructions apply to resting home self-measurement, not a clinical measurement protocol. Unknown conditions remain unknown; requesting guidance does not record a setting or certify compliance."
: "Verified guidance is unavailable for the requested setting. Home instructions have not been substituted for clinical or other-setting instructions.",
steps = available ? new[]
{
new GuidanceStep(1, "Equipment", "Use a validated upper-arm device with a cuff suited to your arm. Follow its instructions for placement and maintenance; incorrect cuff size can distort readings."),
new GuidanceStep(2, "Preparation", "Choose a quiet place. Avoid smoking for 30 minutes beforehand and rest seated for five minutes."),
new GuidanceStep(3, "Position", "Sit with back and arm supported and legs uncrossed. Put the cuff on bare skin, clear of tight clothing, and keep the arm relaxed and still during measurement."),
new GuidanceStep(4, "Measure", "Use the device as instructed. Reproduce your setting, posture and preparation when possible to help later comparisons."),
new GuidanceStep(5, "Planned monitoring", "The cited Danish home protocol uses three readings in the morning before breakfast and three in the evening before dinner, over three consecutive days. This planned series differs from saving one observation; follow individually supplied clinical instructions."),
new GuidanceStep(6, "Record", "Save actual blood-pressure values in mmHg, device-reported pulse in beats/minute, and measurement time. Record setting, activity and preparation where known, including departures from routine. Do not discard, change or invent values to fit guidance.")
} : Array.Empty<GuidanceStep>(),
pulseExplanation = available
? "Rest and activity affect the context of pulse readings. One device-reported pulse value does not assess rhythm regularity."
: null,
activityExplanation = available
? "During-activity and after-activity measurements differ from resting measurements. Record the actual conditions; do not relabel them as resting. Such observations remain valid to record."
: null,
limitations = available
? "Guidance does not guarantee accuracy or replace device or individual clinical instructions. It does not recommend medication changes. Viewing or declining it does not save or alter observations, certify a procedure, or prevent a valid submission."
: null,
sources = available ? new[]
{
new GuidanceSource("Sundhed.dk — Højt blodtryk", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/", "2024-09-25"),
new GuidanceSource("Sundhed.dk — Blodtryksmåling", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/undersoegelser-og-proever/kliniske-procedurer/hjertekar/blodtryksmaaling/", "2025-03-13")
} : Array.Empty<GuidanceSource>()
};
}
private sealed record GuidanceStep(int Order, string Topic, string Instruction);
private sealed record GuidanceSource(string Title, string Url, string UpdatedOn);
}