Adds PasswordHasher + DbSetup

This commit is contained in:
Janus C. H. Knudsen 2025-01-21 23:26:05 +01:00
parent 4ec4beef21
commit db09261768
7 changed files with 269 additions and 45 deletions

View file

@ -0,0 +1,79 @@
using Insight.Database;
using System.Data;
namespace Database.Identity
{
public class DbSetup
{
private readonly IDbConnection _db;
public DbSetup(IDbConnection db)
{
_db = db;
}
public void CreateDatabase()
{
var schema = "dev";
if (_db.State != ConnectionState.Open)
_db.Open();
using var transaction = _db.BeginTransaction();
try
{
// Create tables
_db.Execute(@$"
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
);
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 users(id),
is_active BOOLEAN DEFAULT true
);
CREATE TABLE IF NOT EXISTS {schema}.user_tenants (
user_id INTEGER REFERENCES users(id),
tenant_id INTEGER REFERENCES tenants(id),
created_date TIMESTAMP NOT NULL,
PRIMARY KEY (user_id, tenant_id)
);
-- Enable RLS både tenants og user_tenants
ALTER TABLE {schema}.tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE {schema}.user_tenants ENABLE ROW LEVEL SECURITY;
-- RLS policy for tenants
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
));
-- RLS policy for user_tenants
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);");
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
}