private async Task CreateTenantResources(string email, string password) { _roleManager.RoleValidators.Clear(); _roleManager.RoleValidators.Add(new CustomRoleValidator()); var tenantContact = _hostRepository.GetFirst <TenantContact>(tc => tc.Email == email && tc.PasswordHash == password, includeProperties: "Tenant"); var tenant = tenantContact.Tenant; if (tenant.ResourcesCreated) { return; } string dbName = GenerateDbName(tenant.AppName); string connectionString = GenerateConnectionString(dbName); string dbScript = await GetDbScript(); var appAdminRole = new ApplicationRole { Id = Guid.NewGuid(), Name = "Appadmin", NormalizedName = "APPADMIN", TenantId = tenant.Id }; var roleResult = await _roleManager.CreateAsync(appAdminRole); if (!roleResult.Succeeded) { throw new ApplicationException( string.Join(",", roleResult.Errors.Select(r => r.Description))); } var applicationUser = new ApplicationUser { Id = Guid.NewGuid(), UserName = email, NormalizedEmail = email, NormalizedUserName = email, Email = email, EmailConfirmed = tenantContact.EmailConfirmed, Fullname = $"{tenantContact.Name} {tenantContact.Surname}", TenantId = tenant.Id, }; var userResult = await _userManager.CreateAsync(applicationUser, _encryptionService.Decrypt(tenantContact.PasswordHash)); if (userResult.Succeeded) { await AddUserToRole(applicationUser, appAdminRole); await CreateAdminPermissions(appAdminRole); tenant.ConnectionString = connectionString; tenant.ResourcesCreated = true; _hostRepository.Update(tenant); await _hostRepository.SaveAsync(); await _hostRepository.ExecuteSqlCommand($"CREATE DATABASE {dbName};"); using var connection = new NpgsqlConnection(connectionString); using var command = new NpgsqlCommand($"{dbScript}", connection); await connection.OpenAsync(); await command.ExecuteNonQueryAsync(); await ReloadTenantsToCache(); } else { throw new ApplicationException( string.Join(",", userResult.Errors.Select(r => r.Description))); } }