Setup db automation
This commit is contained in:
parent
1540f9f655
commit
72544d62e2
12 changed files with 473 additions and 337 deletions
148
Database/Core/SetupIdentitySystem.cs
Normal file
148
Database/Core/SetupIdentitySystem.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using Insight.Database;
|
||||
using System.Data;
|
||||
|
||||
namespace Database.IdentitySystem
|
||||
{
|
||||
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;
|
||||
|
||||
public DbSetup(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)
|
||||
{
|
||||
|
||||
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));
|
||||
|
||||
_db.ExecuteSql(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,
|
||||
password_hash VARCHAR(256) NOT NULL,
|
||||
security_stamp VARCHAR(36) NOT NULL,
|
||||
email_confirmed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
access_failed_count INTEGER NOT NULL DEFAULT 0,
|
||||
lockout_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
lockout_end TIMESTAMPTZ NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login_at TIMESTAMPTZ NULL
|
||||
);";
|
||||
|
||||
ExecuteSql(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,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_by INTEGER NOT NULL REFERENCES users(id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);";
|
||||
|
||||
ExecuteSql(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),
|
||||
pin_code VARCHAR(10) NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (user_id, tenant_id)
|
||||
);";
|
||||
|
||||
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
|
||||
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
|
||||
USING (user_id = current_setting('app.user_id', TRUE)::INTEGER);"
|
||||
};
|
||||
|
||||
foreach (var statement in sql)
|
||||
{
|
||||
ExecuteSql(statement);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
62
Database/Core/SetupUser.cs
Normal file
62
Database/Core/SetupUser.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
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);
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
76
Database/Core/UserService.cs
Normal file
76
Database/Core/UserService.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
using Core.Entities.Users;
|
||||
using Insight.Database;
|
||||
using System.Data;
|
||||
|
||||
namespace Database.IdentitySystem
|
||||
{
|
||||
public class UserService
|
||||
{
|
||||
private readonly IDbConnection _db;
|
||||
|
||||
public UserService(IDbConnection db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task CreateUserWithTenant(string email, string password, string tenantConnectionString)
|
||||
{
|
||||
var schema = "dev";
|
||||
|
||||
if (_db.State != ConnectionState.Open)
|
||||
_db.Open();
|
||||
|
||||
using var transaction = _db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
// Create user
|
||||
var user = new User
|
||||
{
|
||||
Email = email,
|
||||
PasswordHash = PasswordHasher.HashPassword(password),
|
||||
SecurityStamp = Guid.NewGuid().ToString(),
|
||||
EmailConfirmed = false,
|
||||
CreatedDate = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var userId = await _db.ExecuteScalarAsync<int>(@$"
|
||||
INSERT INTO {schema}.users (email, password_hash, security_stamp, email_confirmed, created_date)
|
||||
VALUES (@Email, @PasswordHash, @SecurityStamp, @EmailConfirmed, @CreatedDate)
|
||||
RETURNING id", user);
|
||||
|
||||
// Create tenant
|
||||
var tenant = new Tenant
|
||||
{
|
||||
ConnectionString = tenantConnectionString,
|
||||
CreatedDate = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
var tenantId = await _db.ExecuteScalarAsync<int>(@$"
|
||||
INSERT INTO {schema}.tenants (connection_string, created_date, created_by, is_active)
|
||||
VALUES (@ConnectionString, @CreatedDate, @CreatedBy, @IsActive)
|
||||
RETURNING id", tenant);
|
||||
|
||||
// Link user to tenant
|
||||
var userTenant = new UserTenant
|
||||
{
|
||||
UserId = userId,
|
||||
TenantId = tenantId,
|
||||
CreatedDate = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _db.ExecuteAsync(@$"
|
||||
INSERT INTO {schema}.user_tenants (user_id, tenant_id, created_date)
|
||||
VALUES (@UserId, @TenantId, @CreatedDate)", userTenant);
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue