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:
WorkClub Automation
2026-03-03 14:32:21 +01:00
parent b9edbb8a65
commit 28964c6767
35 changed files with 4006 additions and 5 deletions

View 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);
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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);
}
}
}
}
}

View File

@@ -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;
}
}
}
}

View File

@@ -0,0 +1,285 @@
// <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 WorkClub.Infrastructure.Data;
#nullable disable
namespace WorkClub.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260303132952_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkClub.Domain.Entities.Club", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("SportType")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_clubs_tenant_id");
b.ToTable("clubs", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.Member", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("ExternalUserId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("Role")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_members_club_id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_members_tenant_id");
b.HasIndex("TenantId", "ExternalUserId")
.HasDatabaseName("ix_members_tenant_external_user");
b.ToTable("members", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.Shift", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("Capacity")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1);
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CreatedById")
.HasColumnType("uuid");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset>("EndTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("Location")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<uint>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.Property<DateTimeOffset>("StartTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_shifts_club_id");
b.HasIndex("StartTime")
.HasDatabaseName("ix_shifts_start_time");
b.HasIndex("TenantId")
.HasDatabaseName("ix_shifts_tenant_id");
b.ToTable("shifts", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.ShiftSignup", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("MemberId")
.HasColumnType("uuid");
b.Property<Guid>("ShiftId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("SignedUpAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.HasKey("Id");
b.HasIndex("ShiftId")
.HasDatabaseName("ix_shift_signups_shift_id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_shift_signups_tenant_id");
b.HasIndex("ShiftId", "MemberId")
.IsUnique()
.HasDatabaseName("ix_shift_signups_shift_member");
b.ToTable("shift_signups", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.WorkItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("AssigneeId")
.HasColumnType("uuid");
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CreatedById")
.HasColumnType("uuid");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<uint>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssigneeId")
.HasDatabaseName("ix_work_items_assignee_id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_work_items_club_id");
b.HasIndex("Status")
.HasDatabaseName("ix_work_items_status");
b.HasIndex("TenantId")
.HasDatabaseName("ix_work_items_tenant_id");
b.ToTable("work_items", (string)null);
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,201 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WorkClub.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "clubs",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TenantId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
SportType = table.Column<int>(type: "integer", nullable: false),
Description = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: true),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_clubs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "members",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TenantId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
ExternalUserId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
DisplayName = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Email = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Role = table.Column<int>(type: "integer", nullable: false),
ClubId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_members", x => x.Id);
});
migrationBuilder.CreateTable(
name: "shift_signups",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TenantId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
ShiftId = table.Column<Guid>(type: "uuid", nullable: false),
MemberId = table.Column<Guid>(type: "uuid", nullable: false),
SignedUpAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_shift_signups", x => x.Id);
});
migrationBuilder.CreateTable(
name: "shifts",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TenantId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Title = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: true),
Location = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
StartTime = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
EndTime = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Capacity = table.Column<int>(type: "integer", nullable: false, defaultValue: 1),
ClubId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedById = table.Column<Guid>(type: "uuid", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
xmin = table.Column<uint>(type: "xid", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_shifts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "work_items",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
TenantId = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Title = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: true),
Status = table.Column<int>(type: "integer", nullable: false),
AssigneeId = table.Column<Guid>(type: "uuid", nullable: true),
CreatedById = table.Column<Guid>(type: "uuid", nullable: false),
ClubId = table.Column<Guid>(type: "uuid", nullable: false),
DueDate = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
xmin = table.Column<uint>(type: "xid", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_work_items", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "ix_clubs_tenant_id",
table: "clubs",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "ix_members_club_id",
table: "members",
column: "ClubId");
migrationBuilder.CreateIndex(
name: "ix_members_tenant_external_user",
table: "members",
columns: new[] { "TenantId", "ExternalUserId" });
migrationBuilder.CreateIndex(
name: "ix_members_tenant_id",
table: "members",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "ix_shift_signups_shift_id",
table: "shift_signups",
column: "ShiftId");
migrationBuilder.CreateIndex(
name: "ix_shift_signups_shift_member",
table: "shift_signups",
columns: new[] { "ShiftId", "MemberId" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_shift_signups_tenant_id",
table: "shift_signups",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "ix_shifts_club_id",
table: "shifts",
column: "ClubId");
migrationBuilder.CreateIndex(
name: "ix_shifts_start_time",
table: "shifts",
column: "StartTime");
migrationBuilder.CreateIndex(
name: "ix_shifts_tenant_id",
table: "shifts",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "ix_work_items_assignee_id",
table: "work_items",
column: "AssigneeId");
migrationBuilder.CreateIndex(
name: "ix_work_items_club_id",
table: "work_items",
column: "ClubId");
migrationBuilder.CreateIndex(
name: "ix_work_items_status",
table: "work_items",
column: "Status");
migrationBuilder.CreateIndex(
name: "ix_work_items_tenant_id",
table: "work_items",
column: "TenantId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "clubs");
migrationBuilder.DropTable(
name: "members");
migrationBuilder.DropTable(
name: "shift_signups");
migrationBuilder.DropTable(
name: "shifts");
migrationBuilder.DropTable(
name: "work_items");
}
}
}

View File

@@ -0,0 +1,282 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WorkClub.Infrastructure.Data;
#nullable disable
namespace WorkClub.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("WorkClub.Domain.Entities.Club", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("SportType")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_clubs_tenant_id");
b.ToTable("clubs", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.Member", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("ExternalUserId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("Role")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_members_club_id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_members_tenant_id");
b.HasIndex("TenantId", "ExternalUserId")
.HasDatabaseName("ix_members_tenant_external_user");
b.ToTable("members", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.Shift", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("Capacity")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1);
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CreatedById")
.HasColumnType("uuid");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset>("EndTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("Location")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<uint>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.Property<DateTimeOffset>("StartTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_shifts_club_id");
b.HasIndex("StartTime")
.HasDatabaseName("ix_shifts_start_time");
b.HasIndex("TenantId")
.HasDatabaseName("ix_shifts_tenant_id");
b.ToTable("shifts", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.ShiftSignup", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("MemberId")
.HasColumnType("uuid");
b.Property<Guid>("ShiftId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("SignedUpAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.HasKey("Id");
b.HasIndex("ShiftId")
.HasDatabaseName("ix_shift_signups_shift_id");
b.HasIndex("TenantId")
.HasDatabaseName("ix_shift_signups_tenant_id");
b.HasIndex("ShiftId", "MemberId")
.IsUnique()
.HasDatabaseName("ix_shift_signups_shift_member");
b.ToTable("shift_signups", (string)null);
});
modelBuilder.Entity("WorkClub.Domain.Entities.WorkItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("AssigneeId")
.HasColumnType("uuid");
b.Property<Guid>("ClubId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("CreatedById")
.HasColumnType("uuid");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<uint>("RowVersion")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("xid")
.HasColumnName("xmin");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<string>("TenantId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssigneeId")
.HasDatabaseName("ix_work_items_assignee_id");
b.HasIndex("ClubId")
.HasDatabaseName("ix_work_items_club_id");
b.HasIndex("Status")
.HasDatabaseName("ix_work_items_status");
b.HasIndex("TenantId")
.HasDatabaseName("ix_work_items_tenant_id");
b.ToTable("work_items", (string)null);
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,53 @@
-- Enable Row-Level Security on all tenant-scoped tables
ALTER TABLE clubs ENABLE ROW LEVEL SECURITY;
ALTER TABLE members ENABLE ROW LEVEL SECURITY;
ALTER TABLE work_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE shifts ENABLE ROW LEVEL SECURITY;
ALTER TABLE shift_signups ENABLE ROW LEVEL SECURITY;
-- Create tenant_isolation policies for tables with direct tenant_id column
CREATE POLICY tenant_isolation ON clubs
FOR ALL
USING ("TenantId" = current_setting('app.current_tenant_id', true)::text);
CREATE POLICY tenant_isolation ON members
FOR ALL
USING ("TenantId" = current_setting('app.current_tenant_id', true)::text);
CREATE POLICY tenant_isolation ON work_items
FOR ALL
USING ("TenantId" = current_setting('app.current_tenant_id', true)::text);
CREATE POLICY tenant_isolation ON shifts
FOR ALL
USING ("TenantId" = current_setting('app.current_tenant_id', true)::text);
-- Special policy for shift_signups (no direct tenant_id, uses subquery via shifts)
CREATE POLICY tenant_isolation ON shift_signups
FOR ALL
USING ("ShiftId" IN (SELECT "Id" FROM shifts WHERE "TenantId" = current_setting('app.current_tenant_id', true)::text));
-- Create bypass_rls_policy for app_admin role
CREATE POLICY bypass_rls_policy ON clubs
FOR ALL TO app_admin
USING (true);
CREATE POLICY bypass_rls_policy ON members
FOR ALL TO app_admin
USING (true);
CREATE POLICY bypass_rls_policy ON work_items
FOR ALL TO app_admin
USING (true);
CREATE POLICY bypass_rls_policy ON shifts
FOR ALL TO app_admin
USING (true);
CREATE POLICY bypass_rls_policy ON shift_signups
FOR ALL TO app_admin
USING (true);

View File

@@ -0,0 +1,58 @@
using System.Security.Claims;
using System.Text.Json;
using Finbuckle.MultiTenant;
using Finbuckle.MultiTenant.Abstractions;
using Microsoft.AspNetCore.Http;
using WorkClub.Application.Interfaces;
namespace WorkClub.Infrastructure.Services;
public class TenantProvider : ITenantProvider
{
private readonly IMultiTenantContextAccessor<TenantInfo> _multiTenantContextAccessor;
private readonly IHttpContextAccessor _httpContextAccessor;
public TenantProvider(
IMultiTenantContextAccessor<TenantInfo> multiTenantContextAccessor,
IHttpContextAccessor httpContextAccessor)
{
_multiTenantContextAccessor = multiTenantContextAccessor;
_httpContextAccessor = httpContextAccessor;
}
public string GetTenantId()
{
var tenantInfo = _multiTenantContextAccessor.MultiTenantContext?.TenantInfo;
if (tenantInfo == null || string.IsNullOrEmpty(tenantInfo.Identifier))
{
throw new InvalidOperationException("Tenant context is not available");
}
return tenantInfo.Identifier;
}
public string GetUserRole()
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext?.User == null)
{
throw new InvalidOperationException("User context is not available");
}
var tenantId = GetTenantId();
var clubsClaim = httpContext.User.FindFirst("clubs")?.Value;
if (string.IsNullOrEmpty(clubsClaim))
{
throw new InvalidOperationException("User does not have clubs claim");
}
var clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
if (clubsDict == null || !clubsDict.TryGetValue(tenantId, out var role))
{
throw new InvalidOperationException($"User is not a member of tenant {tenantId}");
}
return role;
}
}

View File

@@ -2,9 +2,16 @@
<ItemGroup>
<ProjectReference Include="..\WorkClub.Domain\WorkClub.Domain.csproj" />
<ProjectReference Include="..\WorkClub.Application\WorkClub.Application.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Finbuckle.MultiTenant" Version="10.0.3" />
<PackageReference Include="Finbuckle.MultiTenant.AspNetCore" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
</ItemGroup>
@@ -14,4 +21,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>