From c83442b4afc71786e7a6af4989f739724059ec3d Mon Sep 17 00:00:00 2001 From: Janus Knudsen Date: Mon, 10 Feb 2025 18:41:51 +0100 Subject: [PATCH] wip --- Database/Core/DCL/SetupApplicationUser.cs | 86 ++++++++++ Database/Core/DCL/SetupOrganizationUser.cs | 86 ++++++++++ .../Core/{ => DDL}/SetupIdentitySystem.cs | 2 +- Database/Tenants/Setup.cs | 88 ---------- SetupInfrastructure/Program.cs | 156 ++++++++++++++---- .../SetupInfrastructure.csproj | 27 ++- SetupInfrastructure/Startup.cs | 2 +- SetupInfrastructure/appconfiguration.json | 2 +- .../.dbeaver/.credentials-config.json.bak | Bin 112 -> 128 bytes SqlManagement/.dbeaver/.data-sources.json.bak | 3 +- .../.dbeaver/.project-metadata.json.bak | 2 +- .../.dbeaver/credentials-config.json | Bin 128 -> 128 bytes SqlManagement/.dbeaver/data-sources.json | 32 +--- SqlManagement/.dbeaver/project-metadata.json | 2 +- SqlManagement/Scripts/Script-1.sql | 0 SqlManagement/Scripts/Script-2.sql | 99 ----------- 16 files changed, 315 insertions(+), 272 deletions(-) create mode 100644 Database/Core/DCL/SetupApplicationUser.cs create mode 100644 Database/Core/DCL/SetupOrganizationUser.cs rename Database/Core/{ => DDL}/SetupIdentitySystem.cs (99%) delete mode 100644 Database/Tenants/Setup.cs delete mode 100644 SqlManagement/Scripts/Script-1.sql delete mode 100644 SqlManagement/Scripts/Script-2.sql diff --git a/Database/Core/DCL/SetupApplicationUser.cs b/Database/Core/DCL/SetupApplicationUser.cs new file mode 100644 index 0000000..5420617 --- /dev/null +++ b/Database/Core/DCL/SetupApplicationUser.cs @@ -0,0 +1,86 @@ +using System.Data; +using Database.Common; +using Insight.Database; + +namespace Database.Core.DataControlLanguage +{ + + /// + /// Only a superadmin or similar can create Application Users + /// + public class SetupApplicationUser + { + + IDbConnection _db; + string _schema; + string _user; + string _password; + + public SetupApplicationUser(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 SetupApplicationUser in Database", 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} WITH CREATEDB CREATEROLE 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/Core/DCL/SetupOrganizationUser.cs b/Database/Core/DCL/SetupOrganizationUser.cs new file mode 100644 index 0000000..b58b98b --- /dev/null +++ b/Database/Core/DCL/SetupOrganizationUser.cs @@ -0,0 +1,86 @@ +using System.Data; +using Database.Common; +using Insight.Database; + +namespace Database.Core.DataControlLanguage +{ + public class SetupOrganization + { + + IDbConnection _db; + string _schema; + string _user; + string _password; + + public SetupOrganization(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 SetupOrganization in Database", 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/Core/SetupIdentitySystem.cs b/Database/Core/DDL/SetupIdentitySystem.cs similarity index 99% rename from Database/Core/SetupIdentitySystem.cs rename to Database/Core/DDL/SetupIdentitySystem.cs index 6400ce1..072106e 100644 --- a/Database/Core/SetupIdentitySystem.cs +++ b/Database/Core/DDL/SetupIdentitySystem.cs @@ -1,7 +1,7 @@ using Insight.Database; using System.Data; -namespace Database.Core +namespace Database.Core.DataDefinitionLanguage { public interface IDbSetup { diff --git a/Database/Tenants/Setup.cs b/Database/Tenants/Setup.cs deleted file mode 100644 index 61dcd62..0000000 --- a/Database/Tenants/Setup.cs +++ /dev/null @@ -1,88 +0,0 @@ -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/SetupInfrastructure/Program.cs b/SetupInfrastructure/Program.cs index fcc0471..7b6da29 100644 --- a/SetupInfrastructure/Program.cs +++ b/SetupInfrastructure/Program.cs @@ -1,48 +1,136 @@ using Autofac; +using Insight.Database; +using System.Data; 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": { - /// "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])); + /// + /// 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=;Password=;" + /// + internal class Program + { + static IContainer _container; - var ctp = new Startup.ConnectionStringTemplateParameters( - user: userPass.Split(":")[0], - pwd: userPass.Split(":")[1] - ); - var container = new Startup().ConfigureContainer(ctp); + static async Task Main(string[] args) + { + string userPass; - // SetupIdentitySystem - // ConfigurationDatabaseSetup - // input configurations!!! TODO:Missing + try + { + do + { + Console.WriteLine("Input :"); + userPass = Console.ReadLine() ?? string.Empty; + } while (!userPass.Contains(":") || userPass.Split(":").Length != 2 || + string.IsNullOrEmpty(userPass.Split(":")[0]) || + string.IsNullOrEmpty(userPass.Split(":")[1])); + + var ctp = new Startup.ConnectionStringTemplateParameters( + user: userPass.Split(":")[0], + pwd: userPass.Split(":")[1] + ); + _container = new Startup().ConfigureContainer(ctp); + + if (TestDbRole()) + { + + // SetupApplicationUser + // SetupIdentitySystem + // SetupConfiguration + //and a lot of other tables that we haven't defined yet + + // input configurations!!! TODO:Missing - } - } + } + + } + + catch (Exception e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine(e); + + } + + + } + + static bool TestDbRole() + { + var backgroundColor = Console.BackgroundColor; + var foregroundColor = Console.ForegroundColor; + + //test db access + Console.WriteLine("Testing db access..."); + + string query = @"SELECT usename, usesuper FROM pg_user WHERE usename = CURRENT_USER;"; + + var conn = _container.Resolve(); + var result = (dynamic)conn.QuerySql(query).Single(); + + string username = result.usename; + bool isSuperuser = (bool)result.usesuper; + + if ((bool)result.usesuper) + { + Console.ForegroundColor = ConsoleColor.Green; + Console.BackgroundColor = ConsoleColor.Yellow; + Console.WriteLine(); + Console.WriteLine("TEST SUCCESSFULLY"); + Console.WriteLine(); + Console.ForegroundColor = ConsoleColor.White; + Console.BackgroundColor = backgroundColor; + Console.WriteLine("-------------------------------"); + Console.WriteLine(); + Console.WriteLine($"Username: {username}"); + Console.WriteLine($"Super admin: true"); + Console.WriteLine(); + Console.WriteLine("-------------------------------"); + + + Console.WriteLine("Press any key to start database setup"); + Console.Read(); + + return true; + } + + + Console.ForegroundColor = ConsoleColor.Green; + Console.BackgroundColor = ConsoleColor.Red; + Console.WriteLine(); + Console.WriteLine("TEST WAS NOT SUCCESSFULLY"); + Console.WriteLine(); + Console.ForegroundColor = ConsoleColor.White; + Console.BackgroundColor = backgroundColor; + Console.WriteLine("-------------------------------"); + Console.WriteLine(); + Console.WriteLine($"Username: {username}"); + Console.WriteLine($"Super admin: false"); + Console.WriteLine(); + Console.WriteLine("-------------------------------"); + + + Console.WriteLine("User is required to be super admin"); + Console.Read(); + + return false; + + + } + } } diff --git a/SetupInfrastructure/SetupInfrastructure.csproj b/SetupInfrastructure/SetupInfrastructure.csproj index ac3a41d..9f1d266 100644 --- a/SetupInfrastructure/SetupInfrastructure.csproj +++ b/SetupInfrastructure/SetupInfrastructure.csproj @@ -1,20 +1,19 @@  - - Exe - net8.0 - enable - enable - + + Exe + net8.0 + enable + - - - + + + - - - Always - - + + + Always + + diff --git a/SetupInfrastructure/Startup.cs b/SetupInfrastructure/Startup.cs index aac2e6f..c047aea 100644 --- a/SetupInfrastructure/Startup.cs +++ b/SetupInfrastructure/Startup.cs @@ -10,7 +10,7 @@ namespace SetupInfrastructure public virtual IConfigurationRoot Configuration() { var configuration = new ConfigurationBuilder() - .AddJsonFile("appconfiguration.dev.json") + .AddJsonFile("appconfiguration.json") .Build(); return configuration; diff --git a/SetupInfrastructure/appconfiguration.json b/SetupInfrastructure/appconfiguration.json index 684dac2..7607c57 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={usr};Password={pwd};" + "DefaultConnection": "Host=192.168.1.57;Port=5432;Database=ptmain;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/.credentials-config.json.bak b/SqlManagement/.dbeaver/.credentials-config.json.bak index 0568d24d2de43fc83663a85230d5722262325072..95f3cea6469d8f67ce9340e2c12a54199ef068f9 100644 GIT binary patch literal 128 zcmV-`0Du2R^tH4eGO#*A^oTJI>kkn4?7F#?JcmxS6rLK_PjLujxEd2mXFwk}4d^); z=matx@z=`kkcjG^m5L;VWi87Lx*LIJp!tc@_Bhmcl%c-rlSHFz9^fxKlCDsl(CMb0@&>s^I$I#xZQ2q(XWC literal 112 zcmV-$0FVDtT^j_XdD-z5%J9?f?0Y`0$4Nn}w>FGCbX4n)pUSIhH2eFM`>gI=s`#zz z*xpd8B5PVsjbnJ*Y6emQguY>c0(!R^0EJE^7N=8e^FBt4m7 S8l+Gsx8_ZRTDZ<`OL9~^F*$1h diff --git a/SqlManagement/.dbeaver/.data-sources.json.bak b/SqlManagement/.dbeaver/.data-sources.json.bak index 253676f..ba364e4 100644 --- a/SqlManagement/.dbeaver/.data-sources.json.bak +++ b/SqlManagement/.dbeaver/.data-sources.json.bak @@ -9,8 +9,7 @@ "configuration": { "host": "192.168.1.57", "port": "5432", - "database": "postgres", - "url": "jdbc:postgresql://192.168.1.57:5432/postgres", + "url": "jdbc:postgresql://192.168.1.57:5432/", "configurationType": "MANUAL", "home": "postgresql_client", "type": "dev", diff --git a/SqlManagement/.dbeaver/.project-metadata.json.bak b/SqlManagement/.dbeaver/.project-metadata.json.bak index cf4d1a0..a675f9d 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/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":"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 diff --git a/SqlManagement/.dbeaver/credentials-config.json b/SqlManagement/.dbeaver/credentials-config.json index 804772a9a0b1e9823735bd8233223b485c55866c..d6c80afc254583713caff2e2a1bb3947285d94c6 100644 GIT binary patch literal 128 zcmV-`0Du2kD%BA*)(SqfL*-wIFS-A+rO<5!l_>U4_ia@3b$<);LOZR8a?d5$HRCr$b2q literal 128 zcmV-`0Du1%bnxxm)`>K#lEe$Fmm+xWCI|nDy{PESmtTO*<3(W<4JJ1Xz4roV(7N~y zx4Z4lT7+m%=9NA-W^wMnH-cvV