feat(backend): add PostgreSQL schema, RLS policies, and multi-tenant middleware
- Add EF Core migrations for initial schema (clubs, members, work_items, shifts, shift_signups) - Implement RLS policies with SET LOCAL for tenant isolation - Add Finbuckle multi-tenant middleware with ClaimStrategy + HeaderStrategy fallback - Create TenantValidationMiddleware to enforce JWT claims match X-Tenant-Id header - Add tenant-aware DB interceptors (SaveChangesTenantInterceptor, TenantDbConnectionInterceptor) - Configure AppDbContext with tenant scoping and RLS support - Add test infrastructure: CustomWebApplicationFactory, TestAuthHandler, DatabaseFixture - Write TDD integration tests for multi-tenant isolation and RLS enforcement - Add health check null safety for connection string Tasks: 7 (PostgreSQL schema + migrations + RLS), 8 (Finbuckle multi-tenancy + validation), 12 (test infrastructure)
This commit is contained in:
24
backend/WorkClub.Infrastructure/Data/AppDbContext.cs
Normal file
24
backend/WorkClub.Infrastructure/Data/AppDbContext.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data;
|
||||
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<Club> Clubs => Set<Club>();
|
||||
public DbSet<Member> Members => Set<Member>();
|
||||
public DbSet<WorkItem> WorkItems => Set<WorkItem>();
|
||||
public DbSet<Shift> Shifts => Set<Shift>();
|
||||
public DbSet<ShiftSignup> ShiftSignups => Set<ShiftSignup>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Configurations;
|
||||
|
||||
public class ClubConfiguration : IEntityTypeConfiguration<Club>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Club> builder)
|
||||
{
|
||||
builder.ToTable("clubs");
|
||||
|
||||
builder.HasKey(c => c.Id);
|
||||
|
||||
builder.Property(c => c.TenantId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(c => c.Name)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(c => c.Description)
|
||||
.HasMaxLength(2000);
|
||||
|
||||
builder.Property(c => c.SportType)
|
||||
.IsRequired()
|
||||
.HasConversion<int>();
|
||||
|
||||
builder.Property(c => c.CreatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(c => c.UpdatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.HasIndex(c => c.TenantId)
|
||||
.HasDatabaseName("ix_clubs_tenant_id");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Configurations;
|
||||
|
||||
public class MemberConfiguration : IEntityTypeConfiguration<Member>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Member> builder)
|
||||
{
|
||||
builder.ToTable("members");
|
||||
|
||||
builder.HasKey(m => m.Id);
|
||||
|
||||
builder.Property(m => m.TenantId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(m => m.ExternalUserId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(m => m.DisplayName)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(m => m.Email)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(m => m.Role)
|
||||
.IsRequired()
|
||||
.HasConversion<int>();
|
||||
|
||||
builder.Property(m => m.ClubId)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(m => m.CreatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(m => m.UpdatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.HasIndex(m => m.TenantId)
|
||||
.HasDatabaseName("ix_members_tenant_id");
|
||||
|
||||
builder.HasIndex(m => m.ClubId)
|
||||
.HasDatabaseName("ix_members_club_id");
|
||||
|
||||
builder.HasIndex(m => new { m.TenantId, m.ExternalUserId })
|
||||
.HasDatabaseName("ix_members_tenant_external_user");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Configurations;
|
||||
|
||||
public class ShiftConfiguration : IEntityTypeConfiguration<Shift>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<Shift> builder)
|
||||
{
|
||||
builder.ToTable("shifts");
|
||||
|
||||
builder.HasKey(s => s.Id);
|
||||
|
||||
builder.Property(s => s.TenantId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(s => s.Title)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(s => s.Description)
|
||||
.HasMaxLength(2000);
|
||||
|
||||
builder.Property(s => s.Location)
|
||||
.HasMaxLength(500);
|
||||
|
||||
builder.Property(s => s.StartTime)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.EndTime)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.Capacity)
|
||||
.IsRequired()
|
||||
.HasDefaultValue(1);
|
||||
|
||||
builder.Property(s => s.ClubId)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.CreatedById)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.CreatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.UpdatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.RowVersion)
|
||||
.IsRowVersion()
|
||||
.HasColumnName("xmin")
|
||||
.HasColumnType("xid")
|
||||
.ValueGeneratedOnAddOrUpdate();
|
||||
|
||||
builder.HasIndex(s => s.TenantId)
|
||||
.HasDatabaseName("ix_shifts_tenant_id");
|
||||
|
||||
builder.HasIndex(s => s.ClubId)
|
||||
.HasDatabaseName("ix_shifts_club_id");
|
||||
|
||||
builder.HasIndex(s => s.StartTime)
|
||||
.HasDatabaseName("ix_shifts_start_time");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Configurations;
|
||||
|
||||
public class ShiftSignupConfiguration : IEntityTypeConfiguration<ShiftSignup>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ShiftSignup> builder)
|
||||
{
|
||||
builder.ToTable("shift_signups");
|
||||
|
||||
builder.HasKey(ss => ss.Id);
|
||||
|
||||
builder.Property(ss => ss.TenantId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(ss => ss.ShiftId)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(ss => ss.MemberId)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(ss => ss.SignedUpAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.HasIndex(ss => ss.TenantId)
|
||||
.HasDatabaseName("ix_shift_signups_tenant_id");
|
||||
|
||||
builder.HasIndex(ss => ss.ShiftId)
|
||||
.HasDatabaseName("ix_shift_signups_shift_id");
|
||||
|
||||
builder.HasIndex(ss => new { ss.ShiftId, ss.MemberId })
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_shift_signups_shift_member");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using WorkClub.Domain.Entities;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Configurations;
|
||||
|
||||
public class WorkItemConfiguration : IEntityTypeConfiguration<WorkItem>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<WorkItem> builder)
|
||||
{
|
||||
builder.ToTable("work_items");
|
||||
|
||||
builder.HasKey(w => w.Id);
|
||||
|
||||
builder.Property(w => w.TenantId)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(w => w.Title)
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
builder.Property(w => w.Description)
|
||||
.HasMaxLength(2000);
|
||||
|
||||
builder.Property(w => w.Status)
|
||||
.IsRequired()
|
||||
.HasConversion<int>();
|
||||
|
||||
builder.Property(w => w.AssigneeId);
|
||||
|
||||
builder.Property(w => w.CreatedById)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(w => w.ClubId)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(w => w.DueDate);
|
||||
|
||||
builder.Property(w => w.CreatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(w => w.UpdatedAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(w => w.RowVersion)
|
||||
.IsRowVersion()
|
||||
.HasColumnName("xmin")
|
||||
.HasColumnType("xid")
|
||||
.ValueGeneratedOnAddOrUpdate();
|
||||
|
||||
builder.HasIndex(w => w.TenantId)
|
||||
.HasDatabaseName("ix_work_items_tenant_id");
|
||||
|
||||
builder.HasIndex(w => w.ClubId)
|
||||
.HasDatabaseName("ix_work_items_club_id");
|
||||
|
||||
builder.HasIndex(w => w.Status)
|
||||
.HasDatabaseName("ix_work_items_status");
|
||||
|
||||
builder.HasIndex(w => w.AssigneeId)
|
||||
.HasDatabaseName("ix_work_items_assignee_id");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Finbuckle.MultiTenant;
|
||||
using Finbuckle.MultiTenant.Abstractions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using WorkClub.Domain.Interfaces;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Interceptors;
|
||||
|
||||
public class SaveChangesTenantInterceptor : SaveChangesInterceptor
|
||||
{
|
||||
private readonly IMultiTenantContextAccessor _tenantAccessor;
|
||||
private readonly ILogger<SaveChangesTenantInterceptor> _logger;
|
||||
|
||||
public SaveChangesTenantInterceptor(
|
||||
IMultiTenantContextAccessor tenantAccessor,
|
||||
ILogger<SaveChangesTenantInterceptor> logger)
|
||||
{
|
||||
_tenantAccessor = tenantAccessor;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData,
|
||||
InterceptionResult<int> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
SetTenantIdForNewEntities(eventData.Context);
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
}
|
||||
|
||||
public override InterceptionResult<int> SavingChanges(
|
||||
DbContextEventData eventData,
|
||||
InterceptionResult<int> result)
|
||||
{
|
||||
SetTenantIdForNewEntities(eventData.Context);
|
||||
return base.SavingChanges(eventData, result);
|
||||
}
|
||||
|
||||
private void SetTenantIdForNewEntities(DbContext? context)
|
||||
{
|
||||
if (context == null) return;
|
||||
|
||||
var tenantId = _tenantAccessor.MultiTenantContext?.TenantInfo?.Identifier;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(tenantId))
|
||||
{
|
||||
_logger.LogWarning("No tenant context available for SaveChanges");
|
||||
return;
|
||||
}
|
||||
|
||||
var addedEntries = context.ChangeTracker
|
||||
.Entries()
|
||||
.Where(e => e.State == EntityState.Added && e.Entity is ITenantEntity)
|
||||
.ToList();
|
||||
|
||||
foreach (var entry in addedEntries)
|
||||
{
|
||||
if (entry.Entity is ITenantEntity tenantEntity)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenantEntity.TenantId))
|
||||
{
|
||||
tenantEntity.TenantId = tenantId;
|
||||
_logger.LogDebug("Set TenantId for entity {EntityType}: {TenantId}",
|
||||
entry.Entity.GetType().Name, tenantId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Data.Common;
|
||||
using Finbuckle.MultiTenant;
|
||||
using Finbuckle.MultiTenant.Abstractions;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Npgsql;
|
||||
|
||||
namespace WorkClub.Infrastructure.Data.Interceptors;
|
||||
|
||||
public class TenantDbConnectionInterceptor : DbConnectionInterceptor
|
||||
{
|
||||
private readonly IMultiTenantContextAccessor _tenantAccessor;
|
||||
private readonly ILogger<TenantDbConnectionInterceptor> _logger;
|
||||
|
||||
public TenantDbConnectionInterceptor(
|
||||
IMultiTenantContextAccessor tenantAccessor,
|
||||
ILogger<TenantDbConnectionInterceptor> logger)
|
||||
{
|
||||
_tenantAccessor = tenantAccessor;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public override async ValueTask<InterceptionResult> ConnectionOpeningAsync(
|
||||
DbConnection connection,
|
||||
ConnectionEventData eventData,
|
||||
InterceptionResult result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken);
|
||||
|
||||
var tenantId = _tenantAccessor.MultiTenantContext?.TenantInfo?.Identifier;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(tenantId))
|
||||
{
|
||||
_logger.LogWarning("No tenant context available for database connection");
|
||||
return result;
|
||||
}
|
||||
|
||||
if (connection is NpgsqlConnection npgsqlConnection)
|
||||
{
|
||||
await using var command = npgsqlConnection.CreateCommand();
|
||||
command.CommandText = $"SET LOCAL app.current_tenant_id = '{tenantId}'";
|
||||
|
||||
try
|
||||
{
|
||||
await command.ExecuteNonQueryAsync(cancellationToken);
|
||||
_logger.LogDebug("Set tenant context for database connection: {TenantId}", tenantId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to set tenant context for connection");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData)
|
||||
{
|
||||
base.ConnectionOpened(connection, eventData);
|
||||
|
||||
var tenantId = _tenantAccessor.MultiTenantContext?.TenantInfo?.Identifier;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(tenantId))
|
||||
{
|
||||
_logger.LogWarning("No tenant context available for database connection");
|
||||
return;
|
||||
}
|
||||
|
||||
if (connection is NpgsqlConnection npgsqlConnection)
|
||||
{
|
||||
using var command = npgsqlConnection.CreateCommand();
|
||||
command.CommandText = $"SET LOCAL app.current_tenant_id = '{tenantId}'";
|
||||
|
||||
try
|
||||
{
|
||||
command.ExecuteNonQuery();
|
||||
_logger.LogDebug("Set tenant context for database connection: {TenantId}", tenantId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to set tenant context for connection");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user