diff --git a/Application/Application.csproj b/Application/Application.csproj
index 86cddeb..bfbcf6c 100644
--- a/Application/Application.csproj
+++ b/Application/Application.csproj
@@ -11,6 +11,7 @@
+
diff --git a/Application/Startup.cs b/Application/Startup.cs
index d64ad4b..a5b9a03 100644
--- a/Application/Startup.cs
+++ b/Application/Startup.cs
@@ -34,7 +34,7 @@ namespace PlanTempus
}
public void ConfigureContainer(ContainerBuilder builder)
{
- builder.RegisterModule(new Core.ModuleRegistry.DbPostgreSqlModule
+ builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
{
ConnectionString = ConfigurationRoot.GetConnectionString("ptdb")
});
diff --git a/Core/ModuleRegistry/DbPostgreSqlModule.cs b/Core/ModuleRegistry/DbPostgreSqlModule.cs
deleted file mode 100644
index 3207442..0000000
--- a/Core/ModuleRegistry/DbPostgreSqlModule.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using Autofac;
-using Npgsql;
-using System.Data;
-namespace Core.ModuleRegistry
-{
- public class DbPostgreSqlModule : Module
- {
- public required string ConnectionString { get; set; }
- protected override void Load(ContainerBuilder builder)
- {
- Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider();
-
- builder.Register(c =>
- {
- IDbConnection connection = new NpgsqlConnection(ConnectionString);
- return connection;
- })
- .InstancePerLifetimeScope();
-
- }
- }
-}
diff --git a/Core/ModuleRegistry/TelemetryModule.cs b/Core/ModuleRegistry/TelemetryModule.cs
index db5c25b..5be3862 100644
--- a/Core/ModuleRegistry/TelemetryModule.cs
+++ b/Core/ModuleRegistry/TelemetryModule.cs
@@ -6,66 +6,66 @@ using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
namespace Core.ModuleRegistry
{
- public class TelemetryModule : Module
- {
- public TelemetryConfig TelemetryConfig { get; set; }
- protected override void Load(ContainerBuilder builder)
- {
- if (TelemetryConfig == null)
- throw new Exceptions.ConfigurationException("TelemetryConfig is missing");
+ public class TelemetryModule : Module
+ {
+ public TelemetryConfig TelemetryConfig { get; set; }
+ protected override void Load(ContainerBuilder builder)
+ {
+ if (TelemetryConfig == null)
+ throw new Exceptions.ConfigurationException("TelemetryConfig is missing");
- //builder.Register(c =>
- //{
- // var channel = new Telemetry.DualTelemetryChannel("C:\\logs\\telemetry.log");
- // channel.DeveloperMode = true;
- // var config = new TelemetryConfiguration
- // {
+ //builder.Register(c =>
+ //{
+ // var channel = new Telemetry.DualTelemetryChannel("C:\\logs\\telemetry.log");
+ // channel.DeveloperMode = true;
+ // var config = new TelemetryConfiguration
+ // {
- // ConnectionString = TelemetryConfig.ConnectionString,
- // TelemetryChannel = channel
- // };
- // return new TelemetryClient(config);
- //}).InstancePerLifetimeScope();
+ // ConnectionString = TelemetryConfig.ConnectionString,
+ // TelemetryChannel = channel
+ // };
+ // return new TelemetryClient(config);
+ //}).InstancePerLifetimeScope();
- var telemetryChannel = new InMemoryChannel
- {
- DeveloperMode = true
- };
+ var telemetryChannel = new InMemoryChannel
+ {
+ DeveloperMode = true
+ };
- //var configuration = new TelemetryConfiguration
- //{
- // ConnectionString = TelemetryConfig.ConnectionString,
- // TelemetryChannel = telemetryChannel
- //};
+ //var configuration = new TelemetryConfiguration
+ //{
+ // ConnectionString = TelemetryConfig.ConnectionString,
+ // TelemetryChannel = telemetryChannel
+ //};
- //telemetryChannel.Initialize(configuration);
+ //telemetryChannel.Initialize(configuration);
- var tmc = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
- tmc.ConnectionString = TelemetryConfig.ConnectionString;
- tmc.TelemetryChannel.DeveloperMode = true;
- var channel = new Telemetry.DebugTelemetryChannel("C:\\logs\\telemetry.log");
+ var tmc = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
+ tmc.ConnectionString = TelemetryConfig.ConnectionString;
+ tmc.TelemetryChannel.DeveloperMode = true;
+ var channel = new Telemetry.DebugTelemetryChannel("C:\\logs\\telemetry.log");
- tmc.TelemetryChannel = channel;
+ tmc.TelemetryChannel = channel;
- ////var r = new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(tmc);
- ////r.Use(next => new Domain.EventTelemetryEnrichers.EnrichWithMetaTelemetry(next));
- ////r.Build();
+ ////var r = new Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryProcessorChainBuilder(tmc);
+ ////r.Use(next => new Domain.EventTelemetryEnrichers.EnrichWithMetaTelemetry(next));
+ ////r.Build();
- //builder.RegisterInstance(configuration);
- builder.Register(c => new TelemetryClient(tmc)).InstancePerLifetimeScope();
+ //builder.RegisterInstance(configuration);
+ builder.Register(c => new TelemetryClient(tmc)).InstancePerLifetimeScope();
- //builder.RegisterType()
- // .InstancePerLifetimeScope();
+ //builder.RegisterType()
+ // .InstancePerLifetimeScope();
- //builder.RegisterType()
- // .As()
- // .InstancePerLifetimeScope();
- }
- }
+ //builder.RegisterType()
+ // .As()
+ // .InstancePerLifetimeScope();
+ }
+ }
- public class TelemetryConfig
- {
- public string ConnectionString { get; set; }
- }
+ public class TelemetryConfig
+ {
+ public string ConnectionString { get; set; }
+ }
}
diff --git a/Database/Core/DCL/SetupApplicationUser.cs b/Database/Core/DCL/SetupApplicationUser.cs
index 5420617..9685d38 100644
--- a/Database/Core/DCL/SetupApplicationUser.cs
+++ b/Database/Core/DCL/SetupApplicationUser.cs
@@ -2,35 +2,42 @@
using Database.Common;
using Insight.Database;
-namespace Database.Core.DataControlLanguage
+namespace Database.Core.DCL
{
///
/// Only a superadmin or similar can create Application Users
///
- public class SetupApplicationUser
+ public class SetupApplicationUser : IDbConfigure
{
+ public class Command
+ {
+ public required string Schema { get; init; }
+ public required string User { get; init; }
+ public required string Password { get; init; }
+ }
+
IDbConnection _db;
- string _schema;
- string _user;
- string _password;
+ Command _command;
public SetupApplicationUser(IDbConnection db)
{
_db = db;
}
- public void CreateUserWithSchemaInDatabase(string schema, string user, string password)
+ public void Setup(string schema = null)
{
- _schema = schema;
- _password = password;
- _user = user;
+ throw new NotImplementedException();
+ }
+ public void With(Command command)
+ {
+ _command = command;
- if (!Validations.IsValidSchemaName(_schema))
- throw new ArgumentException("Invalid schema name", _schema);
+ if (!Validations.IsValidSchemaName(_command.Schema))
+ throw new ArgumentException("Invalid schema name", _command.Schema);
- using (var transaction = _db.BeginTransaction())
+ using (var transaction = _db.OpenWithTransaction())
{
try
{
@@ -55,32 +62,56 @@ namespace Database.Core.DataControlLanguage
private void CreateSchema()
{
- var sql = $"CREATE SCHEMA IF NOT EXISTS {_schema}";
+ var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
ExecuteSql(sql);
}
private void CreateRole()
{
- var sql = $"CREATE ROLE {_user} WITH CREATEDB CREATEROLE LOGIN PASSWORD '{_password}';";
+ var sql = $@"
+ DO $$
+ BEGIN
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{_command.User}') THEN
+ CREATE ROLE {_command.User} WITH CREATEDB CREATEROLE LOGIN PASSWORD '{_command.Password}';
+ END IF;
+ END $$;";
ExecuteSql(sql);
- var sql1 = $"ALTER ROLE {_user} SET search_path='{_schema}';";
+ var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
ExecuteSql(sql1);
-
}
private void GrantSchemaRights()
{
- var sql = $"GRANT USAGE ON SCHEMA {_schema} TO {_user};";
+ // Grant USAGE og alle CREATE rettigheder på schema niveau
+ var sql = $@"
+ GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};
+ GRANT ALL ON SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql);
- var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_schema} " +
- $"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_user};";
+ // Grant rettigheder på eksisterende og fremtidige tabeller
+ var sql1 = $"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql1);
- var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_schema} TO {_user};";
+ var sql2 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT ALL PRIVILEGES ON TABLES TO {_command.User};";
ExecuteSql(sql2);
+ // Grant sequence rettigheder
+ var sql3 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};";
+ ExecuteSql(sql3);
+
+ // Grant execute på functions
+ var sql4 = $"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA {_command.Schema} TO {_command.User};";
+ ExecuteSql(sql4);
+
+ // Grant for fremtidige functions
+ var sql5 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT EXECUTE ON FUNCTIONS TO {_command.User};";
+ ExecuteSql(sql5);
+
+ // Grant for fremtidige sequences
+ var sql6 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} GRANT USAGE ON SEQUENCES TO {_command.User};";
+ ExecuteSql(sql6);
}
+
}
}
diff --git a/Database/Core/DCL/SetupOrganizationUser.cs b/Database/Core/DCL/SetupOrganizationUser.cs
index b58b98b..e5f4f16 100644
--- a/Database/Core/DCL/SetupOrganizationUser.cs
+++ b/Database/Core/DCL/SetupOrganizationUser.cs
@@ -2,30 +2,33 @@
using Database.Common;
using Insight.Database;
-namespace Database.Core.DataControlLanguage
+namespace Database.Core.DCL
{
- public class SetupOrganization
+ public class SetupOrganization : IDbConfigure
{
+ public class Command
+ {
+ public required string Schema { get; init; }
+ public required string User { get; init; }
+ public required string Password { get; init; }
+ }
IDbConnection _db;
- string _schema;
- string _user;
- string _password;
+ Command _command;
public SetupOrganization(IDbConnection db)
{
_db = db;
}
- public void CreateUserWithSchemaInDatabase(string schema, string user, string password)
+ public void With(Command command)
{
- _schema = schema;
- _password = password;
- _user = user;
+ _command = command;
- if (!Validations.IsValidSchemaName(_schema))
- throw new ArgumentException("Invalid schema name", _schema);
+
+ if (!Validations.IsValidSchemaName(_command.Schema))
+ throw new ArgumentException("Invalid schema name", _command.Schema);
using (var transaction = _db.BeginTransaction())
{
@@ -44,9 +47,6 @@ namespace Database.Core.DataControlLanguage
}
}
-
-
-
}
private void ExecuteSql(string sql)
{
@@ -55,32 +55,39 @@ namespace Database.Core.DataControlLanguage
private void CreateSchema()
{
- var sql = $"CREATE SCHEMA IF NOT EXISTS {_schema}";
+ var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
ExecuteSql(sql);
}
private void CreateRole()
{
- var sql = $"CREATE ROLE {_user} LOGIN PASSWORD '{_password}';";
+ var sql = $"CREATE ROLE {_command.User} LOGIN PASSWORD '{_command.Password}';";
ExecuteSql(sql);
- var sql1 = $"ALTER ROLE {_user} SET search_path='{_schema}';";
+ var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
ExecuteSql(sql1);
}
private void GrantSchemaRights()
{
- var sql = $"GRANT USAGE ON SCHEMA {_schema} TO {_user};";
+ var sql = $"GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql);
- var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_schema} " +
- $"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_user};";
+ var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} " +
+ $"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_command.User};";
ExecuteSql(sql1);
- var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_schema} TO {_user};";
+ var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};";
ExecuteSql(sql2);
+ var sql3 = $"GRANT CREATE TABLE ON SCHEMA {_command.Schema} TO {_command.User};";
+ ExecuteSql(sql3);
+ }
+ public void RevokeCreateTable()
+ {
+ var sql = $"REVOKE CREATE TABLE ON SCHEMA {_command.Schema} FROM {_command.User};";
+ ExecuteSql(sql);
}
}
}
diff --git a/Database/Core/DDL/SetupIdentitySystem.cs b/Database/Core/DDL/SetupIdentitySystem.cs
index 072106e..a85184b 100644
--- a/Database/Core/DDL/SetupIdentitySystem.cs
+++ b/Database/Core/DDL/SetupIdentitySystem.cs
@@ -1,67 +1,64 @@
using Insight.Database;
using System.Data;
-namespace Database.Core.DataDefinitionLanguage
+namespace Database.Core.DDL
{
- public interface IDbSetup
- {
- void CreateSystem(string schema = null);
- }
+ ///
+ /// This is by purpose not async await
+ /// It is intended that this is created with the correct Application User, which is why the schema name is omitted.
+ ///
+ public class SetupIdentitySystem : IDbConfigure
+ {
+ public class Command { }
- ///
- /// This is by purpose not async await
- ///
- public class SetupIdentitySystem : IDbSetup
- {
- readonly IDbConnection _db;
- IDbTransaction _transaction = null;
- string _schema;
+ readonly IDbConnection _db;
+ IDbTransaction _transaction = null;
+ string _schema;
- public SetupIdentitySystem(IDbConnection db)
- {
- _db = db;
- }
+ public SetupIdentitySystem(IDbConnection db)
+ {
+ _db = db;
+ }
- ///
- /// Creates the system tables in the specified schema within a transaction.
- ///
- /// The schema name where the tables will be created.
- public void CreateSystem(string schema = null)
- {
+ ///
+ /// Creates the system tables in the specified schema within a transaction.
+ ///
+ /// The schema name where the tables will be created.
+ public void With(Command emptyByIntention)
+ {
+ 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 SetupIdentitySystem. Transaction is rolled back", 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);
+ }
- ///
- /// Creates the users table
- ///
- public void CreateUsersTable()
- {
- var sql = @"
+ ///
+ /// Creates the users table
+ ///
+ public void CreateUsersTable()
+ {
+ var sql = @"
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(256) NOT NULL UNIQUE,
@@ -76,16 +73,16 @@ namespace Database.Core.DataDefinitionLanguage
last_login_at TIMESTAMPTZ NULL
);";
- ExecuteSql(sql);
+ ExecuteSql(sql);
- }
+ }
- ///
- /// Creates the tenants table
- ///
- public void CreateTenantsTable()
- {
- var sql = @"
+ ///
+ /// Creates the tenants table
+ ///
+ public void CreateTenantsTable()
+ {
+ var sql = @"
CREATE TABLE IF NOT EXISTS tenants (
id SERIAL PRIMARY KEY,
connection_string VARCHAR(500) NOT NULL,
@@ -94,16 +91,16 @@ namespace Database.Core.DataDefinitionLanguage
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);";
- ExecuteSql(sql);
+ ExecuteSql(sql);
- }
+ }
- ///
- /// Creates the user_tenants table
- ///
- public void CreateUserTenantsTable()
- {
- var sql = @"
+ ///
+ /// Creates the user_tenants table
+ ///
+ 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 +109,37 @@ namespace Database.Core.DataDefinitionLanguage
PRIMARY KEY (user_id, tenant_id)
);";
- ExecuteSql(sql);
+ ExecuteSql(sql);
- }
+ }
- ///
- /// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
- ///
- 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
+ ///
+ /// Sets up Row Level Security (RLS) for the tenants and user_tenants tables.
+ ///
+ 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);
+ }
+ }
- }
+ }
}
\ No newline at end of file
diff --git a/Database/Core/IDbConfigure.cs b/Database/Core/IDbConfigure.cs
new file mode 100644
index 0000000..c591665
--- /dev/null
+++ b/Database/Core/IDbConfigure.cs
@@ -0,0 +1,7 @@
+namespace Database.Core
+{
+ public interface IDbConfigure
+ {
+ void With(T command);
+ }
+}
diff --git a/Database/ModuleRegistry/DbPostgreSqlModule.cs b/Database/ModuleRegistry/DbPostgreSqlModule.cs
new file mode 100644
index 0000000..4b9eabb
--- /dev/null
+++ b/Database/ModuleRegistry/DbPostgreSqlModule.cs
@@ -0,0 +1,22 @@
+using Autofac;
+using Npgsql;
+using System.Data;
+namespace Database.ModuleRegistry
+{
+ public class DbPostgreSqlModule : Module
+ {
+ public required string ConnectionString { get; set; }
+ protected override void Load(ContainerBuilder builder)
+ {
+ Insight.Database.Providers.PostgreSQL.PostgreSQLInsightDbProvider.RegisterProvider();
+
+ builder.Register(c =>
+ {
+ IDbConnection connection = new NpgsqlConnection(ConnectionString);
+ return connection;
+ })
+ .InstancePerLifetimeScope();
+
+ }
+ }
+}
diff --git a/Database/NavigationSystem/Setup.cs b/Database/NavigationSystem/Setup.cs
index 9cb30c5..24e4a01 100644
--- a/Database/NavigationSystem/Setup.cs
+++ b/Database/NavigationSystem/Setup.cs
@@ -14,22 +14,22 @@ namespace Database.NavigationSystem
}
public void CreateSystem()
{
- //await CreateNavigationLinkTemplatesTable(schema);
- //await CreateNavigationLinkTemplateTranslationsTable(schema);
- }
+ //await CreateNavigationLinkTemplatesTable(schema);
+ //await CreateNavigationLinkTemplateTranslationsTable(schema);
+ }
- private async Task CreateNavigationLinkTemplatesTable(string schema)
+ private async Task CreateNavigationLinkTemplatesTable()
{
var sql = $@"
- CREATE TABLE IF NOT EXISTS {schema}.navigation_link_templates (
+ CREATE TABLE IF NOT EXISTS navigation_link_templates (
id SERIAL PRIMARY KEY,
parent_id INTEGER NULL,
url VARCHAR(500) NOT NULL,
permission_id INTEGER NULL,
icon VARCHAR(100) NULL,
default_order INTEGER NOT NULL,
- FOREIGN KEY (permission_id) REFERENCES {schema}.permissions(id),
- FOREIGN KEY (parent_id) REFERENCES {schema}.navigation_link_templates(id)
+ FOREIGN KEY (permission_id) REFERENCES permissions(id),
+ FOREIGN KEY (parent_id) REFERENCES navigation_link_templates(id)
)";
await _db.ExecuteAsync(sql);
}
@@ -37,17 +37,14 @@ namespace Database.NavigationSystem
private async Task CreateNavigationLinkTemplateTranslationsTable(string schema)
{
var sql = $@"
- CREATE TABLE IF NOT EXISTS {schema}.navigation_link_template_translations (
+ CREATE TABLE IF NOT EXISTS navigation_link_template_translations (
id SERIAL PRIMARY KEY,
template_id INTEGER NOT NULL,
language VARCHAR(10) NOT NULL,
display_name VARCHAR(100) NOT NULL,
- FOREIGN KEY (template_id) REFERENCES {schema}.navigation_link_templates(id)
+ FOREIGN KEY (template_id) REFERENCES navigation_link_templates(id)
)";
await _db.ExecuteAsync(sql);
}
-
-
-
}
}
diff --git a/Database/RolesPermissionSystem/Setup.cs b/Database/RolesPermissionSystem/Setup.cs
index 71bd30b..09a70c2 100644
--- a/Database/RolesPermissionSystem/Setup.cs
+++ b/Database/RolesPermissionSystem/Setup.cs
@@ -4,95 +4,97 @@ using Insight.Database;
namespace Database.RolesPermissionSystem
{
- public class Setup
- {
- IDbConnection _db;
- string _schema;
+ ///
+ /// This is by purpose not async await
+ /// It is intended that this is created with the correct Application User, which is why the schema name is omitted.
+ ///
+ public class Setup
+ {
+ IDbConnection _db;
- public Setup(IDbConnection db)
- {
- _db = db;
- }
+ public Setup(IDbConnection db)
+ {
+ _db = db;
+ }
- ///
- /// Creates the system tables in the specified schema within a transaction.
- ///
- /// The schema name where the tables will be created.
- public void CreateSystem(string schema)
- {
- _schema = schema;
+ ///
+ /// Creates the system tables in the specified schema within a transaction.
+ ///
+ /// The schema name where the tables will be created.
+ public void CreateSystem()
+ {
- if (!Validations.IsValidSchemaName(_schema))
- throw new ArgumentException("Invalid schema name", _schema);
+ //if (!Validations.IsValidSchemaName(_schema))
+ // throw new ArgumentException("Invalid schema name", _schema);
- using (var transaction = _db.BeginTransaction())
- {
- try
- {
- CreateRolesTable();
- CreatePermissionsTable();
- CreatePermissionTypesTable();
- CreateRolePermissionsTable();
+ using (var transaction = _db.BeginTransaction())
+ {
+ try
+ {
+ CreateRolesTable();
+ CreatePermissionsTable();
+ CreatePermissionTypesTable();
+ CreateRolePermissionsTable();
- transaction.Commit();
- }
- catch (Exception ex)
- {
- transaction.Rollback();
- throw new InvalidOperationException("Failed to create system tables.", ex);
- }
- }
- }
+ transaction.Commit();
+ }
+ catch (Exception ex)
+ {
+ transaction.Rollback();
+ throw new InvalidOperationException("Failed to create system tables.", ex);
+ }
+ }
+ }
- private void ExecuteSql(string sql)
- {
- _db.ExecuteSql(sql);
- }
+ private void ExecuteSql(string sql)
+ {
+ _db.ExecuteSql(sql);
+ }
- private void CreatePermissionTypesTable()
- {
- var sql = $@"
- CREATE TABLE IF NOT EXISTS {_schema}.permission_types (
+ private void CreatePermissionTypesTable()
+ {
+ var sql = $@"
+ CREATE TABLE IF NOT EXISTS permission_types (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE
)";
- ExecuteSql(sql);
- }
+ ExecuteSql(sql);
+ }
- private void CreatePermissionsTable()
- {
- var sql = $@"
- CREATE TABLE IF NOT EXISTS {_schema}.permissions (
+ private void CreatePermissionsTable()
+ {
+ var sql = $@"
+ CREATE TABLE IF NOT EXISTS permissions (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE,
type_id INTEGER NOT NULL,
- FOREIGN KEY (type_id) REFERENCES {_schema}.permission_types(id)
+ FOREIGN KEY (type_id) REFERENCES permission_types(id)
)";
- ExecuteSql(sql);
- }
+ ExecuteSql(sql);
+ }
- private void CreateRolesTable()
- {
- var sql = $@"
- CREATE TABLE IF NOT EXISTS {_schema}.roles (
+ private void CreateRolesTable()
+ {
+ var sql = $@"
+ CREATE TABLE IF NOT EXISTS roles (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE
)";
- ExecuteSql(sql);
- }
+ ExecuteSql(sql);
+ }
- private void CreateRolePermissionsTable()
- {
- var sql = $@"
- CREATE TABLE IF NOT EXISTS {_schema}.role_permissions (
+ private void CreateRolePermissionsTable()
+ {
+ var sql = $@"
+ CREATE TABLE IF NOT EXISTS role_permissions (
role_id INTEGER NOT NULL,
permission_id INTEGER NOT NULL,
PRIMARY KEY (role_id, permission_id),
- FOREIGN KEY (role_id) REFERENCES {_schema}.roles(id),
- FOREIGN KEY (permission_id) REFERENCES {_schema}.permissions(id)
+ FOREIGN KEY (role_id) REFERENCES roles(id),
+ FOREIGN KEY (permission_id) REFERENCES permissions(id)
)";
- ExecuteSql(sql);
- }
- }
+ ExecuteSql(sql);
+ }
+ }
}
\ No newline at end of file
diff --git a/SetupInfrastructure/Program.cs b/SetupInfrastructure/Program.cs
index 7b6da29..7fad4a5 100644
--- a/SetupInfrastructure/Program.cs
+++ b/SetupInfrastructure/Program.cs
@@ -29,7 +29,7 @@ namespace SetupInfrastructure
{
do
{
- Console.WriteLine("Input :");
+ Console.WriteLine("Input username:password for a superadmin role");
userPass = Console.ReadLine() ?? string.Empty;
} while (!userPass.Contains(":") || userPass.Split(":").Length != 2 ||
string.IsNullOrEmpty(userPass.Split(":")[0]) ||
@@ -41,8 +41,10 @@ namespace SetupInfrastructure
);
_container = new Startup().ConfigureContainer(ctp);
- if (TestDbRole())
+ if (IsSuperAdmin())
{
+ var setup = _container.Resolve();
+ setup.With(new Database.Core.DCL.SetupApplicationUser.Command { Password = "3911", Schema = "system", User = "sathumper" });
// SetupApplicationUser
// SetupIdentitySystem
@@ -70,7 +72,7 @@ namespace SetupInfrastructure
}
- static bool TestDbRole()
+ static bool IsSuperAdmin()
{
var backgroundColor = Console.BackgroundColor;
var foregroundColor = Console.ForegroundColor;
diff --git a/SetupInfrastructure/Startup.cs b/SetupInfrastructure/Startup.cs
index c047aea..7e9c07c 100644
--- a/SetupInfrastructure/Startup.cs
+++ b/SetupInfrastructure/Startup.cs
@@ -5,37 +5,41 @@ using Core.Configurations.JsonConfigProvider;
namespace SetupInfrastructure
{
- public class Startup
- {
- public virtual IConfigurationRoot Configuration()
- {
- var configuration = new ConfigurationBuilder()
- .AddJsonFile("appconfiguration.json")
- .Build();
+ public class Startup
+ {
+ public virtual IConfigurationRoot Configuration()
+ {
+ var configuration = new ConfigurationBuilder()
+ .AddJsonFile("appconfiguration.json")
+ .Build();
- return configuration;
- }
+ return configuration;
+ }
- public IContainer ConfigureContainer(ConnectionStringTemplateParameters ctp)
- {
- var builder = new ContainerBuilder();
- var configuration = Configuration();
+ public IContainer ConfigureContainer(ConnectionStringTemplateParameters ctp)
+ {
+ var builder = new ContainerBuilder();
+ var configuration = Configuration();
- builder.RegisterModule(new Core.ModuleRegistry.DbPostgreSqlModule
- {
- ConnectionString = configuration.GetConnectionString("DefaultConnection").Replace("{usr}", ctp.user).Replace("{pwd}", ctp.pwd)
- });
+ builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
+ {
+ ConnectionString = configuration.GetConnectionString("DefaultConnection").Replace("{usr}", ctp.user).Replace("{pwd}", ctp.pwd)
+ });
- builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule
- {
- TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject()
- });
+ builder.RegisterModule(new Core.ModuleRegistry.TelemetryModule
+ {
+ TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject()
+ });
+
+ builder.RegisterAssemblyTypes(typeof(Database.Core.IDbConfigure<>).Assembly)
+ .AsClosedTypesOf(typeof(Database.Core.IDbConfigure<>))
+ .AsSelf();
- return builder.Build();
- }
+ return builder.Build();
+ }
- public record ConnectionStringTemplateParameters(string user, string pwd);
- }
+ public record ConnectionStringTemplateParameters(string user, string pwd);
+ }
}
diff --git a/SqlManagement/.dbeaver/.project-metadata.json.bak b/SqlManagement/.dbeaver/.project-metadata.json.bak
index a675f9d..1adf556 100644
--- a/SqlManagement/.dbeaver/.project-metadata.json.bak
+++ b/SqlManagement/.dbeaver/.project-metadata.json.bak
@@ -1 +1 @@
-{"resources":{"Scripts/Script-1.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"postgres"},"Scripts/Script-2.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"Scripts/Script-3.sql":{"default-datasource":"postgres-jdbc-19484872d85-cd2a4a40116e706","default-catalog":"ptdb01","default-schema":"ptmain"},"Scripts/Script-4.sql":{"default-datasource":"postgres-jdbc-19484872d85-cd2a4a40116e706","default-catalog":"ptdb01","default-schema":"ptmain"},"Scripts/Script-5.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/Script.sql":{"default-datasource":"postgres-jdbc-19484872d85-cd2a4a40116e706","default-catalog":"sandbox","default-schema":"public"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}}
\ No newline at end of file
+{"resources":{"Scripts/Script-11.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"}}}
\ No newline at end of file
diff --git a/SqlManagement/.dbeaver/project-metadata.json b/SqlManagement/.dbeaver/project-metadata.json
index ff0a6f6..1adf556 100644
--- a/SqlManagement/.dbeaver/project-metadata.json
+++ b/SqlManagement/.dbeaver/project-metadata.json
@@ -1 +1 @@
-{"resources":{"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}}
\ No newline at end of file
+{"resources":{"Scripts/Script-11.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"sandbox"}}}
\ No newline at end of file
diff --git a/Tests/PostgresTests.cs b/Tests/PostgresTests.cs
index 9e531ed..5d8f0ba 100644
--- a/Tests/PostgresTests.cs
+++ b/Tests/PostgresTests.cs
@@ -59,8 +59,8 @@ namespace Tests
{
var conn = Container.Resolve();
- var identitySystem = new Database.Core.SetupIdentitySystem(conn);
- identitySystem.CreateSystem("swp");
+ var identitySystem = new Database.Core.DDL.SetupIdentitySystem(conn);
+ // identitySystem..CreateSystem("swp");
}
[TestMethod]