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