Auto stash before merge of "main" and "origin/main"

This commit is contained in:
Janus C. H. Knudsen 2025-02-02 23:13:17 +01:00
parent 21d7128e74
commit 521190475d
41 changed files with 991 additions and 1150 deletions

View file

@ -1,25 +1,66 @@
using Insight.Database;
using Database.Common;
using Insight.Database;
using System;
using System.Data;
using System.Threading.Tasks;
namespace Database.Tenants
namespace Database.IdentitySystem
{
public class DbSetup
{
private readonly IDbConnection _db;
readonly IDbConnection _db;
IDbTransaction _transaction = null;
string _schema;
public DbSetup(IDbConnection db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
/// <summary>
/// Creates the system tables in the specified schema within a transaction.
/// </summary>
/// <param name="schema">The schema name where the tables will be created.</param>
public async Task CreateSystem(string schema)
{
_schema = schema;
if (!Validations.IsValidSchemaName(schema))
throw new ArgumentException("Invalid schema name", nameof(schema));
using (_transaction = _db.BeginTransaction())
{
try
{
await CreateUsersTable().ConfigureAwait(false);
await CreateTenantsTable().ConfigureAwait(false);
await CreateUserTenantsTable().ConfigureAwait(false);
await SetupRLS().ConfigureAwait(false);
_transaction.Commit();
}
catch (Exception ex)
{
_transaction.Rollback();
throw new InvalidOperationException("Failed to create system tables.", ex);
}
}
}
private async Task ExecuteSqlAsync(string sql)
{
if (string.IsNullOrEmpty(sql))
throw new ArgumentNullException(nameof(sql));
await _db.ExecuteAsync(sql).ConfigureAwait(false);
}
/// <summary>
/// Creates the users table in the ptmain schema.
/// </summary>
public void CreateUsersTable()
public async Task CreateUsersTable()
{
ExecuteInTransaction(@"
var sql = @"
CREATE TABLE IF NOT EXISTS ptmain.users (
id SERIAL PRIMARY KEY,
email VARCHAR(256) NOT NULL UNIQUE,
@ -32,85 +73,75 @@ namespace Database.Tenants
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_login_at TIMESTAMPTZ NULL
);");
);";
await ExecuteSqlAsync(sql).ConfigureAwait(false);
}
/// <summary>
/// Creates the tenants table in the ptmain schema.
/// </summary>
public void CreateTenantsTable()
public async Task CreateTenantsTable()
{
ExecuteInTransaction(@"
var sql = @"
CREATE TABLE IF NOT EXISTS ptmain.tenants (
id SERIAL PRIMARY KEY,
connection_string VARCHAR(500) NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_by INTEGER NOT NULL REFERENCES ptmain.users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);");
);";
await ExecuteSqlAsync(sql).ConfigureAwait(false);
}
/// <summary>
/// Creates the user_tenants table in the ptmain schema.
/// </summary>
public void CreateUserTenantsTable()
public async Task CreateUserTenantsTable()
{
ExecuteInTransaction(@"
var sql = @"
CREATE TABLE IF NOT EXISTS ptmain.user_tenants (
user_id INTEGER NOT NULL REFERENCES ptmain.users(id),
tenant_id INTEGER NOT NULL REFERENCES ptmain.tenants(id),
pin_code VARCHAR(10) NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, tenant_id)
);");
);";
await ExecuteSqlAsync(sql).ConfigureAwait(false);
}
/// <summary>
/// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
/// </summary>
public void SetupRLS()
public async Task SetupRLS()
{
ExecuteInTransaction(
"ALTER TABLE ptmain.tenants ENABLE ROW LEVEL SECURITY;",
"ALTER TABLE ptmain.user_tenants ENABLE ROW LEVEL SECURITY;",
"DROP POLICY IF EXISTS tenant_access ON ptmain.tenants;",
@"
CREATE POLICY tenant_access ON ptmain.tenants
USING (id IN (
SELECT tenant_id
FROM ptmain.user_tenants
WHERE user_id = current_setting('app.user_id', TRUE)::INTEGER
));",
"DROP POLICY IF EXISTS user_tenant_access ON ptmain.user_tenants;",
@"
CREATE POLICY user_tenant_access ON ptmain.user_tenants
USING (user_id = current_setting('app.user_id', TRUE)::INTEGER);"
);
}
/// <summary>
/// Executes one or more SQL commands within a transaction.
/// </summary>
/// <param name="sqlCommands">The SQL commands to execute.</param>
private void ExecuteInTransaction(params string[] sqlCommands)
{
if (_db.State != ConnectionState.Open)
_db.Open();
using var transaction = _db.BeginTransaction();
try
{
foreach (var sql in sqlCommands)
var sql = new[]
{
_db.Execute(sql, transaction: transaction);
}
transaction.Commit();
}
catch (Exception ex)
"ALTER TABLE ptmain.tenants ENABLE ROW LEVEL SECURITY;",
"ALTER TABLE ptmain.user_tenants ENABLE ROW LEVEL SECURITY;",
"DROP POLICY IF EXISTS tenant_access ON ptmain.tenants;",
@"CREATE POLICY tenant_access ON ptmain.tenants
USING (id IN (
SELECT tenant_id
FROM ptmain.user_tenants
WHERE user_id = current_setting('app.user_id', TRUE)::INTEGER
));",
"DROP POLICY IF EXISTS user_tenant_access ON ptmain.user_tenants;",
@"CREATE POLICY user_tenant_access ON ptmain.user_tenants
USING (user_id = current_setting('app.user_id', TRUE)::INTEGER);"
};
foreach (var statement in sql)
{
transaction.Rollback();
throw new InvalidOperationException("Failed to execute SQL commands in transaction.", ex);
await ExecuteSqlAsync(statement).ConfigureAwait(false);
}
}
}
}