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

@@ -5,17 +5,21 @@ namespace PatientProfileService.Application;
public sealed class PatientApplicationService(PatientRepository repository)
{
public Task<Patient> CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken)
public async Task<Patient> CreatePatientAsync(CreatePatientRequest request, string accountId, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
ArgumentException.ThrowIfNullOrWhiteSpace(accountId);
if (await repository.FindByAccountIdAsync(accountId, cancellationToken) is not null)
throw new ProfileAlreadyExistsException();
if (request.DateOfBirth is null)
throw new ArgumentException("A date of birth is required.", nameof(request));
// The documented TIMESTAMP columns store UTC without a time-zone component.
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
return repository.SaveAsync(new Patient
return await repository.SaveAsync(new Patient
{
PatientId = Guid.NewGuid(),
AccountId = accountId,
Name = request.Name,
DateOfBirth = request.DateOfBirth.Value,
ContactInfo = request.ContactInfo,
@@ -24,6 +28,9 @@ public sealed class PatientApplicationService(PatientRepository repository)
}, cancellationToken);
}
public Task<Patient?> GetByAccountAsync(string accountId, CancellationToken cancellationToken) =>
repository.FindByAccountIdAsync(accountId, cancellationToken);
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(patientId, cancellationToken);
@@ -4,6 +4,7 @@ namespace PatientProfileService.Application;
public interface PatientRepository
{
Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken);
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
@@ -0,0 +1,5 @@
namespace PatientProfileService.Application;
public sealed class ProfileAlreadyExistsException : Exception
{
}
@@ -12,8 +12,24 @@ public sealed class PatientController(PatientApplicationService service) : Contr
[HttpPost]
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
{
var patient = await service.CreatePatientAsync(request, cancellationToken);
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
var accountId = Request.Headers["X-Account-Id"].ToString();
if (string.IsNullOrWhiteSpace(accountId)) return BadRequest();
try
{
var patient = await service.CreatePatientAsync(request, accountId, cancellationToken);
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
}
catch (ProfileAlreadyExistsException)
{
return Conflict(new { title = "A profile already exists for this account." });
}
}
[HttpGet("by-account/{accountId}")]
public async Task<ActionResult<PatientDto>> GetByAccount(string accountId, CancellationToken cancellationToken)
{
var patient = await service.GetByAccountAsync(accountId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpGet("{patientId:guid}")]
@@ -2,6 +2,7 @@ namespace PatientProfileService.Domain;
public sealed class Patient
{
public string? AccountId { get; set; }
public Guid PatientId { get; set; }
public string Name { get; set; } = "";
public DateOnly DateOfBirth { get; set; }
@@ -0,0 +1,69 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
[Migration("20261005082209_AccountProfileAssociation")]
partial class AccountProfileAssociation
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("AccountId")
.HasColumnType("text")
.HasColumnName("account_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
/// <inheritdoc />
public partial class AccountProfileAssociation : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "account_id",
table: "patient",
type: "text",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_patient_account_id",
table: "patient",
column: "account_id",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_patient_account_id",
table: "patient");
migrationBuilder.DropColumn(
name: "account_id",
table: "patient");
}
}
}
@@ -28,6 +28,10 @@ namespace PatientProfileService.Persistence.Migrations
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("AccountId")
.HasColumnType("text")
.HasColumnName("account_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
@@ -51,6 +55,9 @@ namespace PatientProfileService.Persistence.Migrations
b.HasKey("PatientId");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
@@ -12,6 +12,8 @@ public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options)
var patient = modelBuilder.Entity<Patient>();
patient.ToTable("patient");
patient.HasKey(p => p.PatientId);
patient.Property(p => p.AccountId).HasColumnName("account_id");
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");
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Npgsql;
using PatientProfileService.Application;
using PatientProfileService.Domain;
@@ -9,10 +10,17 @@ public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepositor
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
{
db.Patients.Add(patient);
await db.SaveChangesAsync(cancellationToken);
try { await db.SaveChangesAsync(cancellationToken); }
catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" })
{
throw new ProfileAlreadyExistsException();
}
return patient;
}
public Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.AccountId == accountId, cancellationToken);
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
+13
View File
@@ -1,3 +1,5 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Application;
using PatientProfileService.Persistence;
@@ -27,7 +29,18 @@ public class Program
return;
}
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
{ context.Response.StatusCode = 401; return; }
await next(context);
});
app.MapControllers();
await app.RunAsync();
}