From 05d6977a767df77ef61100a0ebfd2e3f5e71a7e1 Mon Sep 17 00:00:00 2001 From: "Janus C. H. Knudsen" Date: Thu, 6 Feb 2025 23:46:55 +0100 Subject: [PATCH] Conforming all these db calls --- Core/Telemetry/DebugTelemetryChannel.cs | 11 ++ ...DatabaseSetup.cs => SetupConfiguration.cs} | 4 +- Database/Core/SetupIdentitySystem.cs | 180 +++++++++--------- Database/Core/SetupUser.cs | 62 ------ Database/Core/UserService.cs | 2 +- Database/Database.csproj | 1 - .../Setup.cs} | 12 +- Database/RolesPermissionSystem/Setup.cs | 135 +++++++------ Database/Tenants/Setup.cs | 88 +++++++++ Database/Tenants/TenantSetupService.cs | 133 ------------- SetupInfrastructure/Program.cs | 63 +++--- SetupInfrastructure/Startup.cs | 50 ++--- SetupInfrastructure/appconfiguration.json | 2 +- .../.dbeaver/.project-metadata.json.bak | 2 +- SqlManagement/.dbeaver/project-metadata.json | 2 +- .../Scripts/{Script.sql => Script-1.sql} | 0 Tests/PostgresTests.cs | 4 +- 17 files changed, 337 insertions(+), 414 deletions(-) rename Database/ConfigurationManagementSystem/{ConfigurationDatabaseSetup.cs => SetupConfiguration.cs} (98%) delete mode 100644 Database/Core/SetupUser.cs rename Database/{RolesPermissionSystem/NavigationSystem.cs => NavigationSystem/Setup.cs} (82%) create mode 100644 Database/Tenants/Setup.cs delete mode 100644 Database/Tenants/TenantSetupService.cs rename SqlManagement/Scripts/{Script.sql => Script-1.sql} (100%) diff --git a/Core/Telemetry/DebugTelemetryChannel.cs b/Core/Telemetry/DebugTelemetryChannel.cs index 1a0b53f..6a7c54c 100644 --- a/Core/Telemetry/DebugTelemetryChannel.cs +++ b/Core/Telemetry/DebugTelemetryChannel.cs @@ -6,13 +6,24 @@ namespace Core.Telemetry { private readonly string _filePath; public ITelemetryChannel _defaultChannel; + static HttpClient _client = new HttpClient(); public DebugTelemetryChannel(string filePath) { + _client.BaseAddress = new Uri("http://localhost:5341"); _filePath = filePath; } public new void Send(ITelemetry telemetry) { + var l = new SeqLogger(_client, "", ""); + + //await l.LogToSeq( + // "Bruger {UserId} loggede ind", + // "Debug", + // new Dictionary { { "UserId", "12345" }, { "Counter", i++ } } + // ); + + if (telemetry is Microsoft.ApplicationInsights.DataContracts.TraceTelemetry trace) { var severity = trace.SeverityLevel; diff --git a/Database/ConfigurationManagementSystem/ConfigurationDatabaseSetup.cs b/Database/ConfigurationManagementSystem/SetupConfiguration.cs similarity index 98% rename from Database/ConfigurationManagementSystem/ConfigurationDatabaseSetup.cs rename to Database/ConfigurationManagementSystem/SetupConfiguration.cs index 5cb6070..3ed6676 100644 --- a/Database/ConfigurationManagementSystem/ConfigurationDatabaseSetup.cs +++ b/Database/ConfigurationManagementSystem/SetupConfiguration.cs @@ -3,11 +3,11 @@ using System.Data; namespace Database.ConfigurationManagementSystem; -public class ConfigurationDatabaseSetup +public class SetupConfiguration { private readonly IDbConnection _connection; - public ConfigurationDatabaseSetup(IDbConnection connection) + public SetupConfiguration(IDbConnection connection) { _connection = connection; } diff --git a/Database/Core/SetupIdentitySystem.cs b/Database/Core/SetupIdentitySystem.cs index 1690b1e..6400ce1 100644 --- a/Database/Core/SetupIdentitySystem.cs +++ b/Database/Core/SetupIdentitySystem.cs @@ -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); + } - /// - /// This is by purpose not async await - /// - public class DbSetup : IDbSetup - { - readonly IDbConnection _db; - IDbTransaction _transaction = null; - string _schema; + /// + /// This is by purpose not async await + /// + public class SetupIdentitySystem : IDbSetup + { + readonly IDbConnection _db; + IDbTransaction _transaction = null; + string _schema; - public DbSetup(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 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); + } - /// - /// 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 +76,16 @@ namespace Database.IdentitySystem 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 +94,16 @@ namespace Database.IdentitySystem 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 +112,37 @@ namespace Database.IdentitySystem 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/SetupUser.cs b/Database/Core/SetupUser.cs deleted file mode 100644 index ded9ddd..0000000 --- a/Database/Core/SetupUser.cs +++ /dev/null @@ -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); - - - - } - - - } - - -} diff --git a/Database/Core/UserService.cs b/Database/Core/UserService.cs index 2008363..bf78ddb 100644 --- a/Database/Core/UserService.cs +++ b/Database/Core/UserService.cs @@ -2,7 +2,7 @@ using Insight.Database; using System.Data; -namespace Database.IdentitySystem +namespace Database.Core { public class UserService { diff --git a/Database/Database.csproj b/Database/Database.csproj index 8f3ffb3..b281c0c 100644 --- a/Database/Database.csproj +++ b/Database/Database.csproj @@ -11,7 +11,6 @@ - diff --git a/Database/RolesPermissionSystem/NavigationSystem.cs b/Database/NavigationSystem/Setup.cs similarity index 82% rename from Database/RolesPermissionSystem/NavigationSystem.cs rename to Database/NavigationSystem/Setup.cs index b655090..9cb30c5 100644 --- a/Database/RolesPermissionSystem/NavigationSystem.cs +++ b/Database/NavigationSystem/Setup.cs @@ -1,18 +1,22 @@ using Insight.Database; using System.Data; -namespace Database.RolesPermissionSystem +namespace Database.NavigationSystem { - internal class NavigationSystem + internal class Setup { private readonly IDbConnection _db; - public NavigationSystem(IDbConnection db) + public Setup(IDbConnection db) { _db = db; } - + public void CreateSystem() + { + //await CreateNavigationLinkTemplatesTable(schema); + //await CreateNavigationLinkTemplateTranslationsTable(schema); + } private async Task CreateNavigationLinkTemplatesTable(string schema) { diff --git a/Database/RolesPermissionSystem/Setup.cs b/Database/RolesPermissionSystem/Setup.cs index 73c6eb5..71bd30b 100644 --- a/Database/RolesPermissionSystem/Setup.cs +++ b/Database/RolesPermissionSystem/Setup.cs @@ -1,99 +1,98 @@ using System.Data; -using System.Text.RegularExpressions; using Database.Common; using Insight.Database; namespace Database.RolesPermissionSystem { - public class Setup - { - private readonly IDbConnection _db; + public class Setup + { + IDbConnection _db; + string _schema; - public Setup(IDbConnection db) - { - _db = db ?? throw new ArgumentNullException(nameof(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) - { - if (!Validations.IsValidSchemaName(schema)) - throw new ArgumentException("Invalid schema name", nameof(schema)); + /// + /// 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; - using (var transaction = _db.BeginTransaction()) - { - try - { - CreateRolesTable(schema, transaction); - CreatePermissionsTable(schema, transaction); - CreatePermissionTypesTable(schema, transaction); - CreateRolePermissionsTable(schema, transaction); + if (!Validations.IsValidSchemaName(_schema)) + throw new ArgumentException("Invalid schema name", _schema); - transaction.Commit(); - } - catch (Exception ex) - { - transaction.Rollback(); - throw new InvalidOperationException("Failed to create system tables.", ex); - } - } - } + 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); + } + } + } - private void ExecuteSql(string sql, IDbTransaction transaction) - { - if (string.IsNullOrEmpty(sql)) - throw new ArgumentNullException(nameof(sql)); + private void ExecuteSql(string sql) + { + _db.ExecuteSql(sql); + } - _db.Execute(sql, transaction: transaction); - } - - private void CreatePermissionTypesTable(string schema, IDbTransaction transaction) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.permission_types ( + private void CreatePermissionTypesTable() + { + var sql = $@" + CREATE TABLE IF NOT EXISTS {_schema}.permission_types ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE )"; - ExecuteSql(sql, transaction); - } + ExecuteSql(sql); + } - private void CreatePermissionsTable(string schema, IDbTransaction transaction) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.permissions ( + private void CreatePermissionsTable() + { + var sql = $@" + CREATE TABLE IF NOT EXISTS {_schema}.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 {_schema}.permission_types(id) )"; - ExecuteSql(sql, transaction); - } + ExecuteSql(sql); + } - private void CreateRolesTable(string schema, IDbTransaction transaction) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.roles ( + private void CreateRolesTable() + { + var sql = $@" + CREATE TABLE IF NOT EXISTS {_schema}.roles ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE )"; - ExecuteSql(sql, transaction); - } + ExecuteSql(sql); + } - private void CreateRolePermissionsTable(string schema, IDbTransaction transaction) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.role_permissions ( + private void CreateRolePermissionsTable() + { + var sql = $@" + CREATE TABLE IF NOT EXISTS {_schema}.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 {_schema}.roles(id), + FOREIGN KEY (permission_id) REFERENCES {_schema}.permissions(id) )"; - ExecuteSql(sql, transaction); - } - } + ExecuteSql(sql); + } + } } \ No newline at end of file diff --git a/Database/Tenants/Setup.cs b/Database/Tenants/Setup.cs new file mode 100644 index 0000000..61dcd62 --- /dev/null +++ b/Database/Tenants/Setup.cs @@ -0,0 +1,88 @@ +using System; +using System.Data; +using System.Text.RegularExpressions; +using Database.Common; +using Insight.Database; + +namespace Database.Tenants +{ + public class Setup + { + + IDbConnection _db; + string _schema; + string _user; + string _password; + + public Setup(IDbConnection db) + { + _db = db; + } + + public void CreateUserWithSchemaInDatabase(string schema, string user, string password) + { + + _schema = schema; + _password = password; + _user = user; + + if (!Validations.IsValidSchemaName(_schema)) + throw new ArgumentException("Invalid schema name", _schema); + + using (var transaction = _db.BeginTransaction()) + { + try + { + CreateSchema(); + CreateRole(); + GrantSchemaRights(); + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + throw new InvalidOperationException("Failed to CreateUserWithSchemaInDatabase", ex); + } + } + + + + + } + private void ExecuteSql(string sql) + { + _db.ExecuteSql(sql); + } + + private void CreateSchema() + { + var sql = $"CREATE SCHEMA IF NOT EXISTS {_schema}"; + ExecuteSql(sql); + } + + private void CreateRole() + { + var sql = $"CREATE ROLE {_user} LOGIN PASSWORD '{_password}';"; + ExecuteSql(sql); + + var sql1 = $"ALTER ROLE {_user} SET search_path='{_schema}';"; + ExecuteSql(sql1); + + } + + private void GrantSchemaRights() + { + var sql = $"GRANT USAGE ON SCHEMA {_schema} TO {_user};"; + ExecuteSql(sql); + + var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_schema} " + + $"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_user};"; + ExecuteSql(sql1); + + var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_schema} TO {_user};"; + ExecuteSql(sql2); + + } + } +} diff --git a/Database/Tenants/TenantSetupService.cs b/Database/Tenants/TenantSetupService.cs deleted file mode 100644 index 10553fb..0000000 --- a/Database/Tenants/TenantSetupService.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; -using System.Data; -using System.Text.RegularExpressions; -using Insight.Database; -namespace Database.Tenants -{ - - public class Setup - { - private readonly IDbConnection _db; - - public Setup(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); - - - - } - //private async Task CreatePermissionTypesTable(string schema) - //{ - // var sql = $@" - // CREATE TABLE IF NOT EXISTS {schema}.permission_types ( - // id SERIAL PRIMARY KEY, - // name VARCHAR(100) NOT NULL UNIQUE - // )"; - // await _db.ExecuteAsync(sql); - //} - - //private async Task CreatePermissionsTable(string schema) - //{ - // var sql = $@" - // CREATE TABLE IF NOT EXISTS {schema}.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) - // )"; - // await _db.ExecuteAsync(sql); - //} - - //private async Task CreateRolesTable(string schema) - //{ - // var sql = $@" - // CREATE TABLE IF NOT EXISTS {schema}.roles ( - // id SERIAL PRIMARY KEY, - // name VARCHAR(100) NOT NULL UNIQUE - // )"; - // await _db.ExecuteAsync(sql); - //} - - //private async Task CreateRolePermissionsTable(string schema) - //{ - // var sql = $@" - // CREATE TABLE IF NOT EXISTS {schema}.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) - // )"; - // await _db.ExecuteAsync(sql); - //} - - private async Task CreateNavigationLinkTemplatesTable(string schema) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.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) - )"; - await _db.ExecuteAsync(sql); - } - - private async Task CreateNavigationLinkTemplateTranslationsTable(string schema) - { - var sql = $@" - CREATE TABLE IF NOT EXISTS {schema}.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) - )"; - await _db.ExecuteAsync(sql); - } - } - - -} diff --git a/SetupInfrastructure/Program.cs b/SetupInfrastructure/Program.cs index 2e19f6b..fcc0471 100644 --- a/SetupInfrastructure/Program.cs +++ b/SetupInfrastructure/Program.cs @@ -2,32 +2,47 @@ using Autofac; namespace SetupInfrastructure { - /// - /// SETUP APPLICATION USER NAMED sathumper - /// - /// This should be handled on the Postgresql db server with a superadmin or similar. - /// - /// Execute SQL CreateRole.txt - /// - /// After that is executed it is time for running this main program - /// Remember to use the newly created sathumper - /// "ConnectionStrings": { - /// "ptdb": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id=sathumper;Password=;" - /// - internal class Program - { - static async Task Main(string[] args) - { - var container = new Startup().ConfigureContainer(); + /// + /// SETUP APPLICATION USER NAMED sathumper + /// + /// This should be handled on the Postgresql db server with a superadmin or similar. + /// + /// Execute SQL CreateRole.txt + /// + /// After that is executed it is time for running this main program + /// Remember to use the newly created sathumper + /// "ConnectionStrings": { + /// "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id=sathumper;Password=;" + /// + internal class Program + { + static async Task Main(string[] args) + { + string userPass; + do + { + Console.WriteLine("Input username:password"); + userPass = Console.ReadLine() ?? string.Empty; + } while (!userPass.Contains(":") || userPass.Split(":").Length != 2 || + string.IsNullOrEmpty(userPass.Split(":")[0]) || + string.IsNullOrEmpty(userPass.Split(":")[1])); - - container.Resolve - - - - } - } + var ctp = new Startup.ConnectionStringTemplateParameters( + user: userPass.Split(":")[0], + pwd: userPass.Split(":")[1] + ); + var container = new Startup().ConfigureContainer(ctp); + // SetupIdentitySystem + // ConfigurationDatabaseSetup + // input configurations!!! TODO:Missing + + + + + + } + } } diff --git a/SetupInfrastructure/Startup.cs b/SetupInfrastructure/Startup.cs index 5847ee1..aac2e6f 100644 --- a/SetupInfrastructure/Startup.cs +++ b/SetupInfrastructure/Startup.cs @@ -5,35 +5,37 @@ using Core.Configurations.JsonConfigProvider; namespace SetupInfrastructure { - public class Startup - { - public virtual IConfigurationRoot Configuration() - { - var configuration = new ConfigurationBuilder() - .AddJsonFile("appconfiguration.dev.json") - .Build(); + public class Startup + { + public virtual IConfigurationRoot Configuration() + { + var configuration = new ConfigurationBuilder() + .AddJsonFile("appconfiguration.dev.json") + .Build(); - return configuration; - } + return configuration; + } - public IContainer ConfigureContainer() - { - 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") - }); + builder.RegisterModule(new Core.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() + }); - return builder.Build(); - } - } + return builder.Build(); + } + + public record ConnectionStringTemplateParameters(string user, string pwd); + } } diff --git a/SetupInfrastructure/appconfiguration.json b/SetupInfrastructure/appconfiguration.json index 192c71e..684dac2 100644 --- a/SetupInfrastructure/appconfiguration.json +++ b/SetupInfrastructure/appconfiguration.json @@ -1,7 +1,7 @@ { "AllowedHosts": "*", "ConnectionStrings": { - "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id=sathumper;Password=3911;" + "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptdb01;User Id={usr};Password={pwd};" }, "ApplicationInsights": { "ConnectionString": "InstrumentationKey=6d2e76ee-5343-4691-a5e3-81add43cb584;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/" diff --git a/SqlManagement/.dbeaver/.project-metadata.json.bak b/SqlManagement/.dbeaver/.project-metadata.json.bak index e83d733..cf4d1a0 100644 --- a/SqlManagement/.dbeaver/.project-metadata.json.bak +++ b/SqlManagement/.dbeaver/.project-metadata.json.bak @@ -1 +1 @@ -{"resources":{"Scripts/Script-2.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"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","default-schema":"ptmain"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}} \ No newline at end of file +{"resources":{"Scripts/Script-2.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01","default-schema":"ptmain"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}} \ No newline at end of file diff --git a/SqlManagement/.dbeaver/project-metadata.json b/SqlManagement/.dbeaver/project-metadata.json index cf4d1a0..877db95 100644 --- a/SqlManagement/.dbeaver/project-metadata.json +++ b/SqlManagement/.dbeaver/project-metadata.json @@ -1 +1 @@ -{"resources":{"Scripts/Script-2.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01","default-schema":"ptmain"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}} \ No newline at end of file +{"resources":{"Scripts/Script-1.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01","default-schema":"ptmain"},"Scripts/Script-2.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"Scripts/SmartConfigSystem.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"},"Scripts/grant-privileges.sql":{"default-datasource":"postgres-jdbc-1948450a8b4-5fc9eec404e65c44","default-catalog":"ptdb01"}}} \ No newline at end of file diff --git a/SqlManagement/Scripts/Script.sql b/SqlManagement/Scripts/Script-1.sql similarity index 100% rename from SqlManagement/Scripts/Script.sql rename to SqlManagement/Scripts/Script-1.sql diff --git a/Tests/PostgresTests.cs b/Tests/PostgresTests.cs index 1240242..9e531ed 100644 --- a/Tests/PostgresTests.cs +++ b/Tests/PostgresTests.cs @@ -59,8 +59,8 @@ namespace Tests { var conn = Container.Resolve(); - var dbSetup = new Database.IdentitySystem.DbSetup(conn); - await dbSetup.CreateSystem("swp"); + var identitySystem = new Database.Core.SetupIdentitySystem(conn); + identitySystem.CreateSystem("swp"); } [TestMethod]