Application User setup WIP

This commit is contained in:
Janus Knudsen 2025-02-11 17:07:01 +01:00
parent c83442b4af
commit cb6dd39596
16 changed files with 362 additions and 314 deletions

View file

@ -11,6 +11,7 @@
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
<ProjectReference Include="..\Database\Database.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -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")
});

View file

@ -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();
}
}
}

View file

@ -2,35 +2,42 @@
using Database.Common;
using Insight.Database;
namespace Database.Core.DataControlLanguage
namespace Database.Core.DCL
{
/// <summary>
/// Only a superadmin or similar can create Application Users
/// </summary>
public class SetupApplicationUser
public class SetupApplicationUser : IDbConfigure<SetupApplicationUser.Command>
{
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);
}
}
}

View file

@ -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<SetupOrganization.Command>
{
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);
}
}
}

View file

@ -1,18 +1,16 @@
using Insight.Database;
using System.Data;
namespace Database.Core.DataDefinitionLanguage
namespace Database.Core.DDL
{
public interface IDbSetup
{
void CreateSystem(string schema = null);
}
/// <summary>
/// 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.
/// </summary>
public class SetupIdentitySystem : IDbSetup
public class SetupIdentitySystem : IDbConfigure<SetupIdentitySystem.Command>
{
public class Command { }
readonly IDbConnection _db;
IDbTransaction _transaction = null;
string _schema;
@ -26,9 +24,8 @@ namespace Database.Core.DataDefinitionLanguage
/// Creates the system tables in the specified schema within a transaction.
/// </summary>
/// <param name="schema">The schema name where the tables will be created.</param>
public void CreateSystem(string schema = null)
public void With(Command emptyByIntention)
{
using (_transaction = _db.BeginTransaction())
{
try
@ -43,7 +40,7 @@ namespace Database.Core.DataDefinitionLanguage
catch (Exception ex)
{
_transaction.Rollback();
throw new InvalidOperationException("Failed to create system tables.", ex);
throw new InvalidOperationException("Failed to SetupIdentitySystem. Transaction is rolled back", ex);
}
}
}

View file

@ -0,0 +1,7 @@
namespace Database.Core
{
public interface IDbConfigure<T>
{
void With(T command);
}
}

View file

@ -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();
}
}
}

View file

@ -18,18 +18,18 @@ namespace Database.NavigationSystem
//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);
}
}
}

View file

@ -4,10 +4,13 @@ using Insight.Database;
namespace Database.RolesPermissionSystem
{
/// <summary>
/// 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.
/// </summary>
public class Setup
{
IDbConnection _db;
string _schema;
public Setup(IDbConnection db)
{
@ -18,12 +21,11 @@ namespace Database.RolesPermissionSystem
/// Creates the system tables in the specified schema within a transaction.
/// </summary>
/// <param name="schema">The schema name where the tables will be created.</param>
public void CreateSystem(string schema)
public void CreateSystem()
{
_schema = schema;
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())
{
@ -53,7 +55,7 @@ namespace Database.RolesPermissionSystem
private void CreatePermissionTypesTable()
{
var sql = $@"
CREATE TABLE IF NOT EXISTS {_schema}.permission_types (
CREATE TABLE IF NOT EXISTS permission_types (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE
)";
@ -63,11 +65,11 @@ namespace Database.RolesPermissionSystem
private void CreatePermissionsTable()
{
var sql = $@"
CREATE TABLE IF NOT EXISTS {_schema}.permissions (
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);
}
@ -75,7 +77,7 @@ namespace Database.RolesPermissionSystem
private void CreateRolesTable()
{
var sql = $@"
CREATE TABLE IF NOT EXISTS {_schema}.roles (
CREATE TABLE IF NOT EXISTS roles (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE
)";
@ -85,12 +87,12 @@ namespace Database.RolesPermissionSystem
private void CreateRolePermissionsTable()
{
var sql = $@"
CREATE TABLE IF NOT EXISTS {_schema}.role_permissions (
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);
}

View file

@ -29,7 +29,7 @@ namespace SetupInfrastructure
{
do
{
Console.WriteLine("Input <username>:<password>");
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<Database.Core.DCL.SetupApplicationUser>();
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;

View file

@ -22,7 +22,7 @@ namespace SetupInfrastructure
var configuration = Configuration();
builder.RegisterModule(new Core.ModuleRegistry.DbPostgreSqlModule
builder.RegisterModule(new Database.ModuleRegistry.DbPostgreSqlModule
{
ConnectionString = configuration.GetConnectionString("DefaultConnection").Replace("{usr}", ctp.user).Replace("{pwd}", ctp.pwd)
});
@ -32,6 +32,10 @@ namespace SetupInfrastructure
TelemetryConfig = configuration.GetSection("ApplicationInsights").ToObject<Core.ModuleRegistry.TelemetryConfig>()
});
builder.RegisterAssemblyTypes(typeof(Database.Core.IDbConfigure<>).Assembly)
.AsClosedTypesOf(typeof(Database.Core.IDbConfigure<>))
.AsSelf();
return builder.Build();
}

View file

@ -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"}}}
{"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"}}}

View file

@ -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"}}}
{"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"}}}

View file

@ -59,8 +59,8 @@ namespace Tests
{
var conn = Container.Resolve<IDbConnection>();
var identitySystem = new Database.Core.SetupIdentitySystem(conn);
identitySystem.CreateSystem("swp");
var identitySystem = new Database.Core.DDL.SetupIdentitySystem(conn);
// identitySystem..CreateSystem("swp");
}
[TestMethod]