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:
@@ -0,0 +1,61 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WorkClub.Api.Middleware;
|
||||
|
||||
public class TenantValidationMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public TenantValidationMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (!context.User.Identity?.IsAuthenticated ?? true)
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantIdHeader) ||
|
||||
string.IsNullOrWhiteSpace(tenantIdHeader))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsJsonAsync(new { error = "X-Tenant-Id header is required" });
|
||||
return;
|
||||
}
|
||||
|
||||
var requestedTenantId = tenantIdHeader.ToString();
|
||||
var clubsClaim = context.User.FindFirst("clubs")?.Value;
|
||||
|
||||
if (string.IsNullOrEmpty(clubsClaim))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = "User does not have clubs claim" });
|
||||
return;
|
||||
}
|
||||
|
||||
Dictionary<string, string>? clubsDict;
|
||||
try
|
||||
{
|
||||
clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = "Invalid clubs claim format" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (clubsDict == null || !clubsDict.ContainsKey(requestedTenantId))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = $"User is not a member of tenant {requestedTenantId}" });
|
||||
return;
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
@@ -51,8 +51,16 @@ builder.Services.AddAuthorizationBuilder()
|
||||
builder.Services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
||||
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddNpgSql(builder.Configuration.GetConnectionString("DefaultConnection")!);
|
||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
|
||||
if (!string.IsNullOrEmpty(connectionString))
|
||||
{
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddNpgSql(connectionString);
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.Services.AddHealthChecks();
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" 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="Microsoft.EntityFrameworkCore.Relational" Version="10.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Finbuckle.MultiTenant" Version="8.2.0" />
|
||||
<PackageReference Include="Finbuckle.MultiTenant" Version="10.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -16,5 +16,5 @@ public class Shift : ITenantEntity
|
||||
public required Guid CreatedById { get; set; }
|
||||
public required DateTimeOffset CreatedAt { get; set; }
|
||||
public required DateTimeOffset UpdatedAt { get; set; }
|
||||
public byte[]? RowVersion { get; set; }
|
||||
public uint RowVersion { get; set; }
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ public class WorkItem : ITenantEntity
|
||||
public DateTimeOffset? DueDate { get; set; }
|
||||
public required DateTimeOffset CreatedAt { get; set; }
|
||||
public required DateTimeOffset UpdatedAt { get; set; }
|
||||
public byte[]? RowVersion { get; set; }
|
||||
public uint RowVersion { get; set; }
|
||||
|
||||
public bool CanTransitionTo(WorkItemStatus newStatus) => (Status, newStatus) switch
|
||||
{
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
285
backend/WorkClub.Infrastructure/Migrations/20260303132952_InitialCreate.Designer.cs
generated
Normal file
285
backend/WorkClub.Infrastructure/Migrations/20260303132952_InitialCreate.Designer.cs
generated
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
58
backend/WorkClub.Infrastructure/Services/TenantProvider.cs
Normal file
58
backend/WorkClub.Infrastructure/Services/TenantProvider.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
138
backend/WorkClub.Tests.Integration/Data/MigrationTests.cs
Normal file
138
backend/WorkClub.Tests.Integration/Data/MigrationTests.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using Dapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
using Testcontainers.PostgreSql;
|
||||
using WorkClub.Infrastructure.Data;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Data;
|
||||
|
||||
public class MigrationTests : IAsyncLifetime
|
||||
{
|
||||
private PostgreSqlContainer? _container;
|
||||
private string? _connectionString;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_container = new PostgreSqlBuilder()
|
||||
.WithImage("postgres:16-alpine")
|
||||
.Build();
|
||||
|
||||
await _container.StartAsync();
|
||||
_connectionString = _container.GetConnectionString();
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (_container != null)
|
||||
{
|
||||
await _container.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Migration_AppliesSuccessfully_CreatesAllTables()
|
||||
{
|
||||
// Arrange
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseNpgsql(_connectionString)
|
||||
.Options;
|
||||
|
||||
// Act
|
||||
await using var context = new AppDbContext(options);
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
// Assert - verify all expected tables exist
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
var tables = (await connection.QueryAsync<string>(
|
||||
@"SELECT table_name
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public'
|
||||
ORDER BY table_name")).ToList();
|
||||
|
||||
Assert.Contains("clubs", tables);
|
||||
Assert.Contains("members", tables);
|
||||
Assert.Contains("work_items", tables);
|
||||
Assert.Contains("shifts", tables);
|
||||
Assert.Contains("shift_signups", tables);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Migration_CreatesCorrectIndexes()
|
||||
{
|
||||
// Arrange
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseNpgsql(_connectionString)
|
||||
.Options;
|
||||
|
||||
// Act
|
||||
await using var context = new AppDbContext(options);
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
// Assert - verify critical indexes exist
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
var indexes = (await connection.QueryAsync<string>(
|
||||
@"SELECT indexname
|
||||
FROM pg_indexes
|
||||
WHERE schemaname = 'public'
|
||||
ORDER BY indexname")).ToList();
|
||||
|
||||
// TenantId indexes
|
||||
Assert.Contains(indexes, i => i.Contains("tenant_id"));
|
||||
|
||||
// ClubId indexes
|
||||
Assert.Contains(indexes, i => i.Contains("club_id"));
|
||||
|
||||
// Status indexes for WorkItem
|
||||
Assert.Contains(indexes, i => i.Contains("status"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Migration_EnablesRowLevelSecurity()
|
||||
{
|
||||
// Arrange
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseNpgsql(_connectionString)
|
||||
.Options;
|
||||
|
||||
// Act
|
||||
await using var context = new AppDbContext(options);
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
// Assert - verify RLS is enabled on tenant tables
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
var rlsEnabled = await connection.QueryAsync<(string TableName, bool RlsEnabled)>(
|
||||
@"SELECT relname AS TableName, relrowsecurity AS RlsEnabled
|
||||
FROM pg_class
|
||||
WHERE relnamespace = 'public'::regnamespace
|
||||
AND relname IN ('clubs', 'members', 'work_items', 'shifts', 'shift_signups')");
|
||||
|
||||
foreach (var (tableName, enabled) in rlsEnabled)
|
||||
{
|
||||
Assert.True(enabled, $"RLS should be enabled on {tableName}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Migration_CreatesTenantIsolationPolicy()
|
||||
{
|
||||
// Arrange
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseNpgsql(_connectionString)
|
||||
.Options;
|
||||
|
||||
// Act
|
||||
await using var context = new AppDbContext(options);
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
// Assert - verify tenant_isolation policies exist
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
var policies = (await connection.QueryAsync<string>(
|
||||
@"SELECT policyname
|
||||
FROM pg_policies
|
||||
WHERE schemaname = 'public'
|
||||
AND policyname = 'tenant_isolation'")).ToList();
|
||||
|
||||
// Should have tenant_isolation policy on all tenant tables
|
||||
Assert.True(policies.Count >= 5, "Should have at least 5 tenant_isolation policies");
|
||||
}
|
||||
}
|
||||
197
backend/WorkClub.Tests.Integration/Data/RlsTests.cs
Normal file
197
backend/WorkClub.Tests.Integration/Data/RlsTests.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
using Dapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
using Testcontainers.PostgreSql;
|
||||
using WorkClub.Domain.Entities;
|
||||
using WorkClub.Infrastructure.Data;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Data;
|
||||
|
||||
public class RlsTests : IAsyncLifetime
|
||||
{
|
||||
private PostgreSqlContainer? _container;
|
||||
private string? _connectionString;
|
||||
private string? _adminConnectionString;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_container = new PostgreSqlBuilder()
|
||||
.WithImage("postgres:16-alpine")
|
||||
.WithDatabase("workclub")
|
||||
.WithUsername("app_user")
|
||||
.WithPassword("apppass")
|
||||
.Build();
|
||||
|
||||
await _container.StartAsync();
|
||||
_connectionString = _container.GetConnectionString();
|
||||
|
||||
_adminConnectionString = _connectionString.Replace("app_user", "app_admin")
|
||||
.Replace("apppass", "adminpass");
|
||||
|
||||
await using var adminConn = new NpgsqlConnection(_adminConnectionString);
|
||||
await adminConn.ExecuteAsync("CREATE ROLE app_admin WITH LOGIN PASSWORD 'adminpass' SUPERUSER");
|
||||
await adminConn.ExecuteAsync("GRANT ALL PRIVILEGES ON DATABASE workclub TO app_admin");
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (_container != null)
|
||||
{
|
||||
await _container.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_BlocksAccess_WithoutTenantContext()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
var clubs = (await connection.QueryAsync<Club>(
|
||||
"SELECT * FROM clubs")).ToList();
|
||||
|
||||
Assert.Empty(clubs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_AllowsAccess_WithCorrectTenantContext()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-1'");
|
||||
|
||||
var clubs = (await connection.QueryAsync<Club>(
|
||||
"SELECT * FROM clubs WHERE tenant_id = 'tenant-1'")).ToList();
|
||||
|
||||
Assert.NotEmpty(clubs);
|
||||
Assert.All(clubs, c => Assert.Equal("tenant-1", c.TenantId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_IsolatesData_AcrossTenants()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-1'");
|
||||
var tenant1Clubs = (await connection.QueryAsync<Club>(
|
||||
"SELECT * FROM clubs")).ToList();
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-2'");
|
||||
var tenant2Clubs = (await connection.QueryAsync<Club>(
|
||||
"SELECT * FROM clubs")).ToList();
|
||||
|
||||
Assert.NotEmpty(tenant1Clubs);
|
||||
Assert.NotEmpty(tenant2Clubs);
|
||||
Assert.All(tenant1Clubs, c => Assert.Equal("tenant-1", c.TenantId));
|
||||
Assert.All(tenant2Clubs, c => Assert.Equal("tenant-2", c.TenantId));
|
||||
|
||||
var tenant1Ids = tenant1Clubs.Select(c => c.Id).ToHashSet();
|
||||
var tenant2Ids = tenant2Clubs.Select(c => c.Id).ToHashSet();
|
||||
Assert.Empty(tenant1Ids.Intersect(tenant2Ids));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_CountsCorrectly_PerTenant()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-1'");
|
||||
var tenant1Count = await connection.ExecuteScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM work_items");
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-2'");
|
||||
var tenant2Count = await connection.ExecuteScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM work_items");
|
||||
|
||||
Assert.Equal(5, tenant1Count);
|
||||
Assert.Equal(3, tenant2Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_AllowsBypass_ForAdminRole()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_adminConnectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
var allClubs = (await connection.QueryAsync<Club>(
|
||||
"SELECT * FROM clubs")).ToList();
|
||||
|
||||
Assert.True(allClubs.Count >= 2);
|
||||
Assert.Contains(allClubs, c => c.TenantId == "tenant-1");
|
||||
Assert.Contains(allClubs, c => c.TenantId == "tenant-2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RLS_HandlesShiftSignups_WithSubquery()
|
||||
{
|
||||
await SeedTestDataAsync();
|
||||
|
||||
await using var connection = new NpgsqlConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await connection.ExecuteAsync("SET LOCAL app.current_tenant_id = 'tenant-1'");
|
||||
var signups = (await connection.QueryAsync<ShiftSignup>(
|
||||
"SELECT * FROM shift_signups")).ToList();
|
||||
|
||||
Assert.NotEmpty(signups);
|
||||
Assert.All(signups, s => Assert.Equal("tenant-1", s.TenantId));
|
||||
}
|
||||
|
||||
private async Task SeedTestDataAsync()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseNpgsql(_connectionString)
|
||||
.Options;
|
||||
|
||||
await using var context = new AppDbContext(options);
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
await using var adminConn = new NpgsqlConnection(_adminConnectionString);
|
||||
await adminConn.OpenAsync();
|
||||
|
||||
var club1Id = Guid.NewGuid();
|
||||
var club2Id = Guid.NewGuid();
|
||||
|
||||
await adminConn.ExecuteAsync(@"
|
||||
INSERT INTO clubs (id, tenant_id, name, sport_type, created_at, updated_at)
|
||||
VALUES (@Id1, 'tenant-1', 'Club 1', 0, NOW(), NOW()),
|
||||
(@Id2, 'tenant-2', 'Club 2', 1, NOW(), NOW())",
|
||||
new { Id1 = club1Id, Id2 = club2Id });
|
||||
|
||||
await adminConn.ExecuteAsync(@"
|
||||
INSERT INTO work_items (id, tenant_id, title, status, created_by_id, club_id, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), 'tenant-1', 'Task ' || i, 0, gen_random_uuid(), @ClubId, NOW(), NOW()
|
||||
FROM generate_series(1, 5) i",
|
||||
new { ClubId = club1Id });
|
||||
|
||||
await adminConn.ExecuteAsync(@"
|
||||
INSERT INTO work_items (id, tenant_id, title, status, created_by_id, club_id, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), 'tenant-2', 'Task ' || i, 0, gen_random_uuid(), @ClubId, NOW(), NOW()
|
||||
FROM generate_series(1, 3) i",
|
||||
new { ClubId = club2Id });
|
||||
|
||||
var shift1Id = Guid.NewGuid();
|
||||
await adminConn.ExecuteAsync(@"
|
||||
INSERT INTO shifts (id, tenant_id, title, start_time, end_time, club_id, created_by_id, created_at, updated_at)
|
||||
VALUES (@Id, 'tenant-1', 'Shift 1', NOW(), NOW() + interval '2 hours', @ClubId, gen_random_uuid(), NOW(), NOW())",
|
||||
new { Id = shift1Id, ClubId = club1Id });
|
||||
|
||||
await adminConn.ExecuteAsync(@"
|
||||
INSERT INTO shift_signups (id, tenant_id, shift_id, member_id, signed_up_at)
|
||||
VALUES (gen_random_uuid(), 'tenant-1', @ShiftId, gen_random_uuid(), NOW())",
|
||||
new { ShiftId = shift1Id });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Testcontainers.PostgreSql;
|
||||
using WorkClub.Infrastructure.Data;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
|
||||
{
|
||||
private readonly PostgreSqlContainer _postgresContainer = new PostgreSqlBuilder()
|
||||
.WithImage("postgres:16-alpine")
|
||||
.WithDatabase("workclub_test")
|
||||
.WithUsername("test")
|
||||
.WithPassword("test")
|
||||
.Build();
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
// Start container (async wait)
|
||||
_postgresContainer.StartAsync().GetAwaiter().GetResult();
|
||||
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// Override connection string for tests
|
||||
config.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:DefaultConnection"] = _postgresContainer.GetConnectionString()
|
||||
});
|
||||
});
|
||||
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Remove existing DbContext registration
|
||||
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
|
||||
if (descriptor != null)
|
||||
{
|
||||
services.Remove(descriptor);
|
||||
}
|
||||
|
||||
// Add Testcontainers DbContext
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseNpgsql(_postgresContainer.GetConnectionString()));
|
||||
|
||||
// Replace authentication with TestAuthHandler
|
||||
services.RemoveAll<IAuthenticationSchemeProvider>();
|
||||
services.AddAuthentication(defaultScheme: "Test")
|
||||
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
|
||||
|
||||
// Build service provider and ensure database created
|
||||
var sp = services.BuildServiceProvider();
|
||||
using var scope = sp.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
db.Database.EnsureCreated();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Test");
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _postgresContainer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
[CollectionDefinition("Database collection")]
|
||||
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
|
||||
{
|
||||
}
|
||||
|
||||
public class DatabaseFixture : IAsyncLifetime
|
||||
{
|
||||
public Task InitializeAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisposeAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory<Program>>, IAsyncLifetime
|
||||
{
|
||||
protected readonly HttpClient Client;
|
||||
protected readonly CustomWebApplicationFactory<Program> Factory;
|
||||
|
||||
protected IntegrationTestBase(CustomWebApplicationFactory<Program> factory)
|
||||
{
|
||||
Factory = factory;
|
||||
Client = factory.CreateClient();
|
||||
}
|
||||
|
||||
protected void AuthenticateAs(string email, Dictionary<string, string> clubs)
|
||||
{
|
||||
var clubsJson = JsonSerializer.Serialize(clubs);
|
||||
Client.DefaultRequestHeaders.Remove("X-Test-Clubs");
|
||||
Client.DefaultRequestHeaders.Add("X-Test-Clubs", clubsJson);
|
||||
|
||||
Client.DefaultRequestHeaders.Remove("X-Test-Email");
|
||||
Client.DefaultRequestHeaders.Add("X-Test-Email", email);
|
||||
}
|
||||
|
||||
protected void SetTenant(string tenantId)
|
||||
{
|
||||
Client.DefaultRequestHeaders.Remove("X-Tenant-Id");
|
||||
Client.DefaultRequestHeaders.Add("X-Tenant-Id", tenantId);
|
||||
}
|
||||
|
||||
public virtual Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
public virtual Task DisposeAsync() => Task.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
public TestAuthHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
}
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var clubsClaim = Context.Request.Headers["X-Test-Clubs"].ToString();
|
||||
var emailClaim = Context.Request.Headers["X-Test-Email"].ToString();
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, "test-user"),
|
||||
new Claim(ClaimTypes.Email, string.IsNullOrEmpty(emailClaim) ? "test@test.com" : emailClaim),
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(clubsClaim))
|
||||
{
|
||||
claims.Add(new Claim("clubs", clubsClaim));
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(claims, "Test");
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, "Test");
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Xunit;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Middleware;
|
||||
|
||||
public class TenantValidationTests : IClassFixture<CustomWebApplicationFactory>
|
||||
{
|
||||
private readonly CustomWebApplicationFactory _factory;
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public TenantValidationTests(CustomWebApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
_client = factory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Request_WithValidTenantId_Returns200()
|
||||
{
|
||||
// Arrange: Create JWT with clubs claim containing club-1
|
||||
var clubs = new Dictionary<string, string>
|
||||
{
|
||||
{ "club-1", "admin" }
|
||||
};
|
||||
var token = CreateTestJwt(clubs);
|
||||
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
_client.DefaultRequestHeaders.Add("X-Tenant-Id", "club-1");
|
||||
|
||||
// Act: Make request to test endpoint
|
||||
var response = await _client.GetAsync("/api/test");
|
||||
|
||||
// Assert: Request should succeed
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Request_WithNonMemberTenantId_Returns403()
|
||||
{
|
||||
// Arrange: Create JWT with clubs claim (only club-1, not club-2)
|
||||
var clubs = new Dictionary<string, string>
|
||||
{
|
||||
{ "club-1", "admin" }
|
||||
};
|
||||
var token = CreateTestJwt(clubs);
|
||||
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
_client.DefaultRequestHeaders.Add("X-Tenant-Id", "club-2"); // User not member of club-2
|
||||
|
||||
// Act
|
||||
var response = await _client.GetAsync("/api/test");
|
||||
|
||||
// Assert: Cross-tenant access should be denied
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Request_WithoutTenantIdHeader_Returns400()
|
||||
{
|
||||
// Arrange: Create valid JWT but no X-Tenant-Id header
|
||||
var clubs = new Dictionary<string, string>
|
||||
{
|
||||
{ "club-1", "admin" }
|
||||
};
|
||||
var token = CreateTestJwt(clubs);
|
||||
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
// No X-Tenant-Id header
|
||||
|
||||
// Act
|
||||
var response = await _client.GetAsync("/api/test");
|
||||
|
||||
// Assert: Missing header should return bad request
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Request_WithoutAuthentication_Returns401()
|
||||
{
|
||||
// Arrange: No authorization header
|
||||
_client.DefaultRequestHeaders.Add("X-Tenant-Id", "club-1");
|
||||
|
||||
// Act
|
||||
var response = await _client.GetAsync("/api/test");
|
||||
|
||||
// Assert: Unauthenticated request should be denied
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
private static string CreateTestJwt(Dictionary<string, string> clubs)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test-secret-key-for-jwt-signing-must-be-at-least-32-chars"));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, "test-user-id"),
|
||||
new Claim(ClaimTypes.Name, "test@test.com"),
|
||||
new Claim("clubs", JsonSerializer.Serialize(clubs)) // JSON object claim
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: "test-issuer",
|
||||
audience: "test-audience",
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddHours(1),
|
||||
signingCredentials: creds
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Custom WebApplicationFactory for integration testing with test authentication.
|
||||
/// </summary>
|
||||
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.AddAuthentication("TestScheme")
|
||||
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("TestScheme", options => { });
|
||||
|
||||
services.AddAuthorization();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Testing");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test authentication handler that validates JWT tokens without Keycloak.
|
||||
/// </summary>
|
||||
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
public TestAuthHandler(
|
||||
Microsoft.Extensions.Options.IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
Microsoft.Extensions.Logging.ILoggerFactory logger,
|
||||
System.Text.Encodings.Web.UrlEncoder encoder)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
}
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var authHeader = Request.Headers.Authorization.ToString();
|
||||
|
||||
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||||
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test-secret-key-for-jwt-signing-must-be-at-least-32-chars"));
|
||||
|
||||
var validationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = "test-issuer",
|
||||
ValidAudience = "test-audience",
|
||||
IssuerSigningKey = key
|
||||
};
|
||||
|
||||
var principal = handler.ValidateToken(token, validationParameters, out _);
|
||||
var ticket = new AuthenticationTicket(principal, "TestScheme");
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.Fail(ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
18
backend/WorkClub.Tests.Integration/SmokeTests.cs
Normal file
18
backend/WorkClub.Tests.Integration/SmokeTests.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System.Net;
|
||||
using WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
namespace WorkClub.Tests.Integration;
|
||||
|
||||
public class SmokeTests : IntegrationTestBase
|
||||
{
|
||||
public SmokeTests(CustomWebApplicationFactory<Program> factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HealthCheck_ReturnsOk()
|
||||
{
|
||||
var response = await Client.GetAsync("/health/live");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Dapper" Version="2.1.66" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" Version="3.7.0" />
|
||||
|
||||
Reference in New Issue
Block a user