PlanTempusApp/Database/Core/DCL/SetupOrganizationUser.cs

94 lines
2.1 KiB
C#
Raw Normal View History

2025-02-10 18:41:51 +01:00
using System.Data;
using Database.Common;
using Insight.Database;
2025-02-11 17:07:01 +01:00
namespace Database.Core.DCL
2025-02-10 18:41:51 +01:00
{
2025-02-11 17:07:01 +01:00
public class SetupOrganization : IDbConfigure<SetupOrganization.Command>
2025-02-10 18:41:51 +01:00
{
2025-02-11 17:07:01 +01:00
public class Command
{
public required string Schema { get; init; }
public required string User { get; init; }
public required string Password { get; init; }
}
2025-02-10 18:41:51 +01:00
IDbConnection _db;
2025-02-11 17:07:01 +01:00
Command _command;
2025-02-10 18:41:51 +01:00
public SetupOrganization(IDbConnection db)
{
_db = db;
}
2025-02-11 17:07:01 +01:00
public void With(Command command)
2025-02-10 18:41:51 +01:00
{
2025-02-11 17:07:01 +01:00
_command = command;
2025-02-10 18:41:51 +01:00
2025-02-11 17:07:01 +01:00
if (!Validations.IsValidSchemaName(_command.Schema))
throw new ArgumentException("Invalid schema name", _command.Schema);
2025-02-10 18:41:51 +01:00
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()
{
2025-02-11 17:07:01 +01:00
var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql);
}
private void CreateRole()
{
2025-02-11 17:07:01 +01:00
var sql = $"CREATE ROLE {_command.User} LOGIN PASSWORD '{_command.Password}';";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql);
2025-02-11 17:07:01 +01:00
var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql1);
}
private void GrantSchemaRights()
{
2025-02-11 17:07:01 +01:00
var sql = $"GRANT USAGE ON SCHEMA {_command.Schema} TO {_command.User};";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql);
2025-02-11 17:07:01 +01:00
var sql1 = $"ALTER DEFAULT PRIVILEGES IN SCHEMA {_command.Schema} " +
$"GRANT INSERT, SELECT, UPDATE PRIVILEGES ON TABLES TO {_command.User};";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql1);
2025-02-11 17:07:01 +01:00
var sql2 = $"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {_command.Schema} TO {_command.User};";
2025-02-10 18:41:51 +01:00
ExecuteSql(sql2);
2025-02-11 17:07:01 +01:00
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);
2025-02-10 18:41:51 +01:00
}
}
}