Working on this data setup logic
This commit is contained in:
parent
384cc3c6fd
commit
447b27f69b
16 changed files with 409 additions and 211 deletions
96
Database/IdentitySystem/DbInfrastructureSetup.cs
Normal file
96
Database/IdentitySystem/DbInfrastructureSetup.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
using Insight.Database;
|
||||
using System.Data;
|
||||
|
||||
namespace Database.Identity
|
||||
{
|
||||
public class DbInfrastructureSetup
|
||||
{
|
||||
private readonly IDbConnection _db;
|
||||
string _schema;
|
||||
|
||||
public DbInfrastructureSetup(IDbConnection db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task CreateDatabaseWithSchema(string schema)
|
||||
{
|
||||
_schema = schema;
|
||||
|
||||
if (_db.State != ConnectionState.Open)
|
||||
_db.Open();
|
||||
|
||||
using var transaction = _db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
await CreateUserTable();
|
||||
await CreateTenantTable();
|
||||
await CreateUserTenantTable();
|
||||
await SetupRLS();
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateUserTable()
|
||||
{
|
||||
await _db.ExecuteSqlAsync(@$"
|
||||
CREATE TABLE IF NOT EXISTS {_schema}.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,
|
||||
created_date TIMESTAMP NOT NULL,
|
||||
last_login_date TIMESTAMP NULL
|
||||
);");
|
||||
}
|
||||
|
||||
private async Task CreateTenantTable()
|
||||
{
|
||||
await _db.ExecuteSqlAsync(@$"
|
||||
CREATE TABLE IF NOT EXISTS {_schema}.tenants (
|
||||
id SERIAL PRIMARY KEY,
|
||||
connection_string VARCHAR(500) NOT NULL,
|
||||
created_date TIMESTAMP NOT NULL,
|
||||
created_by INTEGER REFERENCES {_schema}.users(id),
|
||||
is_active BOOLEAN DEFAULT true
|
||||
);");
|
||||
}
|
||||
|
||||
private async Task CreateUserTenantTable()
|
||||
{
|
||||
await _db.ExecuteSqlAsync(@$"
|
||||
CREATE TABLE IF NOT EXISTS {_schema}.user_tenants (
|
||||
user_id INTEGER REFERENCES {_schema}.users(id),
|
||||
tenant_id INTEGER REFERENCES {_schema}.tenants(id),
|
||||
created_date TIMESTAMP NOT NULL,
|
||||
PRIMARY KEY (user_id, tenant_id)
|
||||
);");
|
||||
}
|
||||
|
||||
private async Task SetupRLS()
|
||||
{
|
||||
await _db.ExecuteSqlAsync(@$"
|
||||
ALTER TABLE {_schema}.tenants ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE {_schema}.user_tenants ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
DROP POLICY IF EXISTS tenant_access ON {_schema}.tenants;
|
||||
CREATE POLICY tenant_access ON {_schema}.tenants
|
||||
USING (id IN (
|
||||
SELECT tenant_id
|
||||
FROM {_schema}.user_tenants
|
||||
WHERE user_id = current_setting('app.user_id', TRUE)::INTEGER
|
||||
));
|
||||
|
||||
DROP POLICY IF EXISTS user_tenant_access ON {_schema}.user_tenants;
|
||||
CREATE POLICY user_tenant_access ON {_schema}.user_tenants
|
||||
USING (user_id = current_setting('app.user_id', TRUE)::INTEGER);");
|
||||
}
|
||||
}
|
||||
}
|
||||
115
Database/IdentitySystem/Setup.cs
Normal file
115
Database/IdentitySystem/Setup.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using System;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Database.Tenants
|
||||
{
|
||||
public class DbSetup
|
||||
{
|
||||
private readonly IDbConnection _db;
|
||||
|
||||
public DbSetup(IDbConnection db)
|
||||
{
|
||||
_db = db ?? throw new ArgumentNullException(nameof(db));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the users table in the ptmain schema.
|
||||
/// </summary>
|
||||
public void CreateUsersTable()
|
||||
{
|
||||
ExecuteInTransaction(@"
|
||||
CREATE TABLE IF NOT EXISTS ptmain.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
|
||||
);");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the tenants table in the ptmain schema.
|
||||
/// </summary>
|
||||
public void CreateTenantsTable()
|
||||
{
|
||||
ExecuteInTransaction(@"
|
||||
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
|
||||
);");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the user_tenants table in the ptmain schema.
|
||||
/// </summary>
|
||||
public void CreateUserTenantsTable()
|
||||
{
|
||||
ExecuteInTransaction(@"
|
||||
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)
|
||||
);");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
|
||||
/// </summary>
|
||||
public void 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)
|
||||
{
|
||||
_db.ExecuteSql(sql, transaction: transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw new InvalidOperationException("Failed to execute SQL commands in transaction.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
76
Database/IdentitySystem/UserService.cs
Normal file
76
Database/IdentitySystem/UserService.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
using Core.Entities.Users;
|
||||
using Insight.Database;
|
||||
using System.Data;
|
||||
|
||||
namespace Database.Identity
|
||||
{
|
||||
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