Implement owned Profile schema and atomic authorized lifecycle
This commit is contained in:
1 parent
523cfbf42e
commit
bfe6ebf5af
24 files changed
+3056
-3
No files matched your search
@@ -0,0 +1,22 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp")]
|
||||
namespace HealthApp.Contracts;
|
||||
// Only the API/access assembly issues this request-local capability after policy checks.
|
||||
public sealed class AuthorizedPatientContext
|
||||
{
|
||||
internal AuthorizedPatientContext(Guid patientId, bool canWrite){PatientId=patientId;CanWrite=canWrite;}
|
||||
public Guid PatientId {get;}
|
||||
public bool CanWrite {get;}
|
||||
public void RequireWrite(){if(!CanWrite)throw new UnauthorizedAccessException("Read-only scope.");}
|
||||
}
|
||||
public interface ProfileQueries
|
||||
{
|
||||
Task<Guid?> ResolveAccountAsync(string accountId,CancellationToken ct);
|
||||
Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
}
|
||||
public interface ProfileCommands
|
||||
{
|
||||
Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest request,CancellationToken ct);
|
||||
Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest request,CancellationToken ct);
|
||||
}
|
||||
public sealed class ProfileAlreadyExistsException : Exception;
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record CreatePatientRequest
|
||||
{
|
||||
[Required]
|
||||
public string? Name { get; init; }
|
||||
|
||||
[Required]
|
||||
public DateOnly? DateOfBirth { get; init; }
|
||||
|
||||
public string? ContactInfo { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record UpdatePatientRequest
|
||||
{
|
||||
[Required]
|
||||
public string? Name { get; init; }
|
||||
|
||||
public string? ContactInfo { get; init; }
|
||||
}
|
||||
@@ -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" /><PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3"/><PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
namespace HealthApp.Infrastructure;
|
||||
// Coordinates mechanics only; it has no health table/query or access-policy knowledge.
|
||||
public sealed class RequestTransaction(NpgsqlDataSource source) : IAsyncDisposable
|
||||
{
|
||||
public NpgsqlConnection? Connection {get;private set;}
|
||||
public NpgsqlTransaction? Transaction {get;private set;}
|
||||
public bool Active=>Transaction is not null;
|
||||
public async Task BeginAsync(bool write,CancellationToken ct)
|
||||
{
|
||||
if(Active)return;
|
||||
Connection=await source.OpenConnectionAsync(ct);
|
||||
Transaction=await Connection.BeginTransactionAsync(write?IsolationLevel.ReadCommitted:IsolationLevel.RepeatableRead,ct);
|
||||
}
|
||||
public async Task EnlistAsync(DbContext context,CancellationToken ct)
|
||||
{
|
||||
if(Transaction is null || Connection is null)throw new InvalidOperationException("No request transaction.");
|
||||
if(context.Database.GetDbConnection()!=Connection)context.Database.SetDbConnection(Connection,false);
|
||||
await context.Database.UseTransactionAsync(Transaction,ct);
|
||||
}
|
||||
public async Task FinishAsync(CancellationToken ct)
|
||||
{
|
||||
if(Transaction is null)return;
|
||||
await Transaction.CommitAsync(ct);await Transaction.DisposeAsync();Transaction=null;
|
||||
await Connection!.DisposeAsync();Connection=null;
|
||||
}
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if(Transaction is not null)await Transaction.DisposeAsync();
|
||||
if(Connection is not null)await Connection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Security.Claims;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api/patients")]
|
||||
public sealed class PatientController(ProfileQueries queries,ProfileCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
[HttpPost,Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Create(CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
try{var p=await commands.CreateAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,r,ct);await tx.FinishAsync(ct);return Created($"/api/patients/{p.PatientId}",p);}
|
||||
catch(ProfileAlreadyExistsException){return Conflict(new{title="A profile already exists for this account."});}
|
||||
}
|
||||
[HttpGet("me"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Me(CancellationToken ct)
|
||||
{
|
||||
var id=await queries.ResolveAccountAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,ct);if(id is null)return NotFound();
|
||||
var scope=await access.AuthorizeAsync(User,id.Value,false,ct);var p=await queries.GetAsync(scope!,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);
|
||||
}
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid patientId,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return NotFound();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
[HttpPut("{patientId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Update(Guid patientId,UpdatePatientRequest r,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return NotFound();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
}
|
||||
@@ -1,4 +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>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -1,4 +1,7 @@
|
||||
using HealthApp.Guidance;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Profile;
|
||||
using Npgsql;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
@@ -14,6 +17,14 @@ public class Program
|
||||
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||
builder.Services.AddSingleton<GuidanceQueries>();
|
||||
builder.Services.AddSingleton(sp=> {
|
||||
var c=sp.GetRequiredService<IConfiguration>();
|
||||
var text=c.GetConnectionString("HealthDatabase");
|
||||
if(string.IsNullOrWhiteSpace(text))throw new InvalidOperationException("HealthDatabase connection is required.");
|
||||
var options=new NpgsqlConnectionStringBuilder(text){Pooling=true,MaxPoolSize=c.GetValue("Resources:MaxPoolSize",32)};
|
||||
return NpgsqlDataSource.Create(options.ConnectionString);
|
||||
});
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddScoped<AccessPolicy>();
|
||||
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"];
|
||||
@@ -37,7 +48,15 @@ public class Program
|
||||
if(!ctx.Request.Path.StartsWithSegments("/api/measurement-guidance"))ctx.Response.Headers.CacheControl="no-store";
|
||||
await next(ctx);
|
||||
});
|
||||
app.UseAuthentication();app.UseAuthorization();app.MapControllers();
|
||||
app.UseAuthentication();app.UseAuthorization();
|
||||
app.Use(async(ctx,next)=> {
|
||||
if(ctx.GetEndpoint()?.Metadata.GetMetadata<Microsoft.AspNetCore.Authorization.IAllowAnonymous>() is not null || ctx.Request.Path.StartsWithSegments("/api/professionals")){await next(ctx);return;}
|
||||
if(ctx.User.Identity?.IsAuthenticated!=true){await next(ctx);return;}
|
||||
if(ctx.User.IsInRole("HealthcareProfessional") && ctx.Request.Method!="GET"){ctx.Response.StatusCode=403;return;}
|
||||
var tx=ctx.RequestServices.GetRequiredService<RequestTransaction>();
|
||||
try{await tx.BeginAsync(ctx.Request.Method!="GET",ctx.RequestAborted);await next(ctx);}
|
||||
catch(NpgsqlException){if(ctx.Response.HasStarted)ctx.Abort();else {ctx.Response.Clear();await Results.Problem(statusCode:503,title:"Health data dependency is unavailable.").ExecuteAsync(ctx);}}
|
||||
});app.MapControllers();
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Security.Claims;
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Security;
|
||||
public sealed class AccessPolicy(ProfileQueries profiles,ProfessionalAssignments assignments)
|
||||
{
|
||||
public async Task<AuthorizedPatientContext?> AuthorizeAsync(ClaimsPrincipal user,Guid actualPatient,bool write,CancellationToken ct)
|
||||
{
|
||||
var account=user.FindFirstValue(ClaimTypes.NameIdentifier)!;
|
||||
bool allowed=user.IsInRole("HealthcareProfessional") ? !write&&assignments.IsAssigned(account,actualPatient) : user.IsInRole("Patient")&&await profiles.ResolveAccountAsync(account,ct)==actualPatient;
|
||||
return allowed?new AuthorizedPatientContext(actualPatient,write):null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace HealthApp.Profile.Domain;
|
||||
|
||||
internal sealed class Patient
|
||||
{
|
||||
public string? AccountId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public DateOnly DateOfBirth { get; set; }
|
||||
public string? ContactInfo { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE SCHEMA IF NOT EXISTS profile;
|
||||
CREATE TABLE IF NOT EXISTS profile.schema_version(version integer PRIMARY KEY);
|
||||
CREATE TABLE IF NOT EXISTS profile.patient (
|
||||
patient_id uuid PRIMARY KEY, account_id text NOT NULL, name varchar NOT NULL,
|
||||
date_of_birth date NOT NULL,contact_info varchar,created_at timestamp without time zone NOT NULL,updated_at timestamp without time zone NOT NULL);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "IX_patient_account_id" ON profile.patient(account_id);
|
||||
INSERT INTO profile.schema_version VALUES(1) ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HealthApp.Profile.Domain;
|
||||
|
||||
namespace HealthApp.Profile.Persistence;
|
||||
|
||||
internal sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<Patient> Patients => Set<Patient>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var patient = modelBuilder.Entity<Patient>();
|
||||
patient.ToTable("patient", "profile");
|
||||
patient.HasKey(p => p.PatientId);
|
||||
patient.Property(p => p.AccountId).HasColumnName("account_id").IsRequired();
|
||||
patient.HasIndex(p => p.AccountId).IsUnique();
|
||||
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
|
||||
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
|
||||
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
|
||||
patient.Property(p => p.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
|
||||
patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||
patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||
}
|
||||
}
|
||||
@@ -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" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Profile.Domain;
|
||||
using HealthApp.Profile.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
namespace HealthApp.Profile;
|
||||
internal sealed class ProfileFacade(PatientDbContext db,RequestTransaction tx) : ProfileQueries,ProfileCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveAccountAsync(string id,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);return await db.Patients.AsNoTracking().Where(p=>p.AccountId==id).Select(p=>(Guid?)p.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);var p=await db.Patients.AsNoTracking().SingleOrDefaultAsync(p=>p.PatientId==scope.PatientId,ct);return p is null?null:Dto(p);}
|
||||
public async Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId);Validator.ValidateObject(r,new ValidationContext(r),true);
|
||||
await tx.EnlistAsync(db,ct);if(await db.Patients.AnyAsync(p=>p.AccountId==trustedAccountId,ct))throw new ProfileAlreadyExistsException();
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var p=new Patient{PatientId=Guid.NewGuid(),AccountId=trustedAccountId,Name=r.Name!,DateOfBirth=r.DateOfBirth!.Value,ContactInfo=r.ContactInfo,CreatedAt=now,UpdatedAt=now};db.Patients.Add(p);
|
||||
try{await db.SaveChangesAsync(ct);}catch(DbUpdateException e) when(e.InnerException is PostgresException {SqlState:"23505",ConstraintName:"IX_patient_account_id"}){throw new ProfileAlreadyExistsException();}
|
||||
return Dto(p);
|
||||
}
|
||||
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(r,new ValidationContext(r),true);await tx.EnlistAsync(db,ct);
|
||||
var p=await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
|
||||
if(p is null)return null;p.Name=r.Name!;p.ContactInfo=r.ContactInfo;p.UpdatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);await db.SaveChangesAsync(ct);return Dto(p);
|
||||
}
|
||||
private static PatientDto Dto(Patient p)=>new(p.PatientId,p.Name,p.DateOfBirth,p.ContactInfo);
|
||||
}
|
||||
public static class ProfileModule
|
||||
{
|
||||
public static IServiceCollection AddProfile(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped(sp=>new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>();services.AddScoped<ProfileQueries>(sp=>sp.GetRequiredService<ProfileFacade>());services.AddScoped<ProfileCommands>(sp=>sp.GetRequiredService<ProfileFacade>());return services;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user