Conforming all these db calls

This commit is contained in:
Janus C. H. Knudsen 2025-02-06 23:46:55 +01:00
parent 5ca874abe9
commit 05d6977a76
17 changed files with 337 additions and 414 deletions

View file

@ -1,67 +1,67 @@
using Insight.Database;
using System.Data;
namespace Database.IdentitySystem
namespace Database.Core
{
public interface IDbSetup
{
void CreateSystem(string schema = null);
}
public interface IDbSetup
{
void CreateSystem(string schema = null);
}
/// <summary>
/// This is by purpose not async await
/// </summary>
public class DbSetup : IDbSetup
{
readonly IDbConnection _db;
IDbTransaction _transaction = null;
string _schema;
/// <summary>
/// This is by purpose not async await
/// </summary>
public class SetupIdentitySystem : IDbSetup
{
readonly IDbConnection _db;
IDbTransaction _transaction = null;
string _schema;
public DbSetup(IDbConnection db)
{
_db = db;
}
public SetupIdentitySystem(IDbConnection db)
{
_db = 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 void CreateSystem(string schema = null)
{
/// <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 void CreateSystem(string schema = null)
{
using (_transaction = _db.BeginTransaction())
{
try
{
CreateUsersTable();
CreateTenantsTable();
CreateUserTenantsTable();
SetupRLS();
using (_transaction = _db.BeginTransaction())
{
try
{
CreateUsersTable();
CreateTenantsTable();
CreateUserTenantsTable();
SetupRLS();
_transaction.Commit();
}
catch (Exception ex)
{
_transaction.Rollback();
throw new InvalidOperationException("Failed to create system tables.", ex);
}
}
}
private void ExecuteSql(string sql)
{
if (string.IsNullOrEmpty(sql))
throw new ArgumentNullException(nameof(sql));
_transaction.Commit();
}
catch (Exception ex)
{
_transaction.Rollback();
throw new InvalidOperationException("Failed to create system tables.", ex);
}
}
}
private void ExecuteSql(string sql)
{
if (string.IsNullOrEmpty(sql))
throw new ArgumentNullException(nameof(sql));
_db.ExecuteSql(sql);
}
_db.ExecuteSql(sql);
}
/// <summary>
/// Creates the users table
/// </summary>
public void CreateUsersTable()
{
var sql = @"
/// <summary>
/// Creates the users table
/// </summary>
public void CreateUsersTable()
{
var sql = @"
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(256) NOT NULL UNIQUE,
@ -76,16 +76,16 @@ namespace Database.IdentitySystem
last_login_at TIMESTAMPTZ NULL
);";
ExecuteSql(sql);
ExecuteSql(sql);
}
}
/// <summary>
/// Creates the tenants table
/// </summary>
public void CreateTenantsTable()
{
var sql = @"
/// <summary>
/// Creates the tenants table
/// </summary>
public void CreateTenantsTable()
{
var sql = @"
CREATE TABLE IF NOT EXISTS tenants (
id SERIAL PRIMARY KEY,
connection_string VARCHAR(500) NOT NULL,
@ -94,16 +94,16 @@ namespace Database.IdentitySystem
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);";
ExecuteSql(sql);
ExecuteSql(sql);
}
}
/// <summary>
/// Creates the user_tenants table
/// </summary>
public void CreateUserTenantsTable()
{
var sql = @"
/// <summary>
/// Creates the user_tenants table
/// </summary>
public void CreateUserTenantsTable()
{
var sql = @"
CREATE TABLE IF NOT EXISTS user_tenants (
user_id INTEGER NOT NULL REFERENCES users(id),
tenant_id INTEGER NOT NULL REFERENCES tenants(id),
@ -112,37 +112,37 @@ namespace Database.IdentitySystem
PRIMARY KEY (user_id, tenant_id)
);";
ExecuteSql(sql);
ExecuteSql(sql);
}
}
/// <summary>
/// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
/// </summary>
public void SetupRLS()
{
var sql = new[]
{
"ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;",
"ALTER TABLE user_tenants ENABLE ROW LEVEL SECURITY;",
"DROP POLICY IF EXISTS tenant_access ON tenants;",
@"CREATE POLICY tenant_access ON tenants
/// <summary>
/// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
/// </summary>
public void SetupRLS()
{
var sql = new[]
{
"ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;",
"ALTER TABLE user_tenants ENABLE ROW LEVEL SECURITY;",
"DROP POLICY IF EXISTS tenant_access ON tenants;",
@"CREATE POLICY tenant_access ON tenants
USING (id IN (
SELECT tenant_id
FROM user_tenants
WHERE user_id = current_setting('app.user_id', TRUE)::INTEGER
));",
"DROP POLICY IF EXISTS user_tenant_access ON user_tenants;",
@"CREATE POLICY user_tenant_access ON user_tenants
"DROP POLICY IF EXISTS user_tenant_access ON user_tenants;",
@"CREATE POLICY user_tenant_access ON user_tenants
USING (user_id = current_setting('app.user_id', TRUE)::INTEGER);"
};
};
foreach (var statement in sql)
{
ExecuteSql(statement);
}
}
foreach (var statement in sql)
{
ExecuteSql(statement);
}
}
}
}
}

View file

@ -1,62 +0,0 @@
using System;
using System.Data;
using System.Text.RegularExpressions;
using Insight.Database;
namespace Database.Core
{
public class SetupUser
{
private readonly IDbConnection _db;
public SetupUser(IDbConnection db)
{
_db = db;
}
public async Task CreateTenantInDatabase(string schema, string user, string password)
{
if (!Regex.IsMatch(schema, "^[a-zA-Z0-9_]+$"))
throw new ArgumentException("Invalid schema name");
await CreateUser(user, password);
await CreateSchema(schema);
await GrantSchemaRights(schema, user);
await CreateNavigationLinkTemplatesTable(schema);
await CreateNavigationLinkTemplateTranslationsTable(schema);
}
private async Task CreateSchema(string schema)
{
var sql = $"CREATE SCHEMA IF NOT EXISTS {schema}";
await _db.ExecuteAsync(sql);
}
private async Task CreateUser(string user, string password)
{
var sql = $"CREATE USER {user} WITH PASSWORD '{password}';";
await _db.ExecuteAsync(sql);
}
private async Task GrantSchemaRights(string schema, string user)
{
var sql = $"GRANT USAGE ON SCHEMA {schema} TO {user};";
await _db.ExecuteAsync(sql);
var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {schema} " +
$"GRANT ALL PRIVILEGES ON TABLES TO {user};";
await _db.ExecuteAsync(sql1);
var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {schema} TO {user};";
await _db.ExecuteAsync(sql2);
}
}
}

View file

@ -2,7 +2,7 @@
using Insight.Database;
using System.Data;
namespace Database.IdentitySystem
namespace Database.Core
{
public class UserService
{