public IActionResult Setup(AdminSetupModel model) { if (ModelState.IsValid) { var profile = new Profile(); if (_db.Profiles.All().ToList().Count == 0) { profile.IsAdmin = true; } profile.AuthorName = model.AuthorName; profile.AuthorEmail = model.AuthorEmail; profile.Title = model.Title; profile.Description = model.Description; profile.IdentityName = User.Identity.Name; profile.Slug = SlugFromTitle(profile.AuthorName); profile.Avatar = ApplicationSettings.ProfileAvatar; profile.BlogTheme = ApplicationSettings.BlogTheme; profile.LastUpdated = SystemClock.Now(); _db.Profiles.Add(profile); _db.Complete(); return(RedirectToAction("Index")); } return(View(_theme + "Setup.cshtml", model)); }
public void CreateAdminUser(AdminSetupModel adminSetupModel) { if (_connectionString == null) { _connectionString = ConfigurationManager.ConnectionStrings["eFormMainConnection"].ConnectionString; } // Seed admin and demo users var manager = new EformUserManager(new EformUserStore(new BaseDbContext(_connectionString))); var adminUser = new EformUser() { UserName = adminSetupModel.UserName, Email = adminSetupModel.Email, FirstName = adminSetupModel.FirstName, LastName = adminSetupModel.LastName, EmailConfirmed = true, TwoFactorEnabled = false, IsGoogleAuthenticatorEnabled = false }; if (!manager.Users.Any(x => x.Email.Equals(adminUser.Email))) { IdentityResult ir = manager.Create(adminUser, adminSetupModel.Password); if (ir != null) { manager.AddToRole(adminUser.Id, "admin"); } else { throw new Exception("Could not create the user"); } } }
public void CreateAdminUser(AdminSetupModel adminSetupModel) { if (_connectionString == null) { _connectionString = ConfigurationManager.ConnectionStrings["eFormMainConnection"].ConnectionString; } // Seed admin and demo users var manager = new EformUserManager(new EformUserStore(new BaseDbContext(_connectionString))); var adminUser = new EformUser() { UserName = adminSetupModel.UserName, Email = adminSetupModel.Email, FirstName = adminSetupModel.FirstName, LastName = adminSetupModel.LastName, EmailConfirmed = true, }; if (!manager.Users.Any(x => x.Email.Equals(adminUser.Email))) { manager.Create(adminUser, adminSetupModel.Password); manager.AddToRole(adminUser.Id, "admin"); } }
private static async Task InitializeSettings(IWebHost webHost, string[] args) { using var scope = webHost.Services.GetService <IServiceScopeFactory>().CreateScope(); var settingsService = scope.ServiceProvider.GetRequiredService <ISettingsService>(); var existsResult = settingsService.ConnectionStringExist(); if (!existsResult.Success)// do need to initialize database { // Find file var filePath = Path.Combine(Directory.GetCurrentDirectory(), "init.json"); if (File.Exists(filePath)) { Log.LogEvent($"Try initialize from {filePath}"); // Get content var startupContent = await File.ReadAllTextAsync(filePath); var startup = JsonConvert.DeserializeObject <StartupInitializeModel>(startupContent); // Apply settings var updateConnectionResult = await settingsService.UpdateConnectionString(startup.InitialSettings); if (!updateConnectionResult.Success) { throw new Exception("Init error: " + updateConnectionResult.Message); } var adminSettingsUpdateModel = new AdminSettingsModel { S3SettingsModel = startup.S3SettingsModel, SMTPSettingsModel = startup.SMTPSettingsModel, SdkSettingsModel = startup.SdkSettingsModel, SendGridSettingsModel = startup.SendGridSettingsModel, SwiftSettingsModel = startup.SwiftSettingsModel, }; var updateAdminSettingsResult = await settingsService.UpdateAdminSettings(adminSettingsUpdateModel); if (!updateAdminSettingsResult.Success) { throw new Exception("Init error: " + updateAdminSettingsResult.Message); } EnabledPlugins = PluginHelper.GetPlugins(_defaultConnectionString); DisabledPlugins = PluginHelper.GetDisablePlugins(_defaultConnectionString); // Enable plugins foreach (var pluginId in startup.PluginsList) { var pluginObject = DisabledPlugins.FirstOrDefault(x => x.PluginId == pluginId); if (pluginObject != null) { var contextFactory = new BaseDbContextFactory(); await using var dbContext = contextFactory.CreateDbContext(new[] { _defaultConnectionString }); var eformPlugin = await dbContext.EformPlugins .Where(x => x.Status == (int)PluginStatus.Disabled) .FirstOrDefaultAsync(x => x.PluginId == pluginObject.PluginId); if (eformPlugin != null) { eformPlugin.Status = (int)PluginStatus.Enabled; dbContext.EformPlugins.Update(eformPlugin); await dbContext.SaveChangesAsync(); var pluginMenu = pluginObject.GetNavigationMenu(scope.ServiceProvider); // Load to database all navigation menu from plugin by id var pluginMenuItemsLoader = new PluginMenuItemsLoader(dbContext, pluginId); pluginMenuItemsLoader.Load(pluginMenu); } } } // not need because settingsService.UpdateAdminSettings call restart // Restart(); // restart IF some plugins has been enabled } else if (args.Any()) { Log.LogEvent("Try initialize from args"); var defaultConfig = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var firstName = defaultConfig.GetValue("FirstName", ""); var lastName = defaultConfig.GetValue("LastName", ""); var email = defaultConfig.GetValue("Email", ""); var password = defaultConfig.GetValue("Password", ""); var token = defaultConfig.GetValue("Token", ""); if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) && !string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password)) { var sdkConnectionString = _defaultConnectionString.Replace("_Angular", "_SDK"); // get customer number const RegexOptions options = RegexOptions.Multiline | RegexOptions.CultureInvariant; const string pattern = @"[D|d]atabase=(\D*)(\d*)_Angular"; if (int.TryParse(Regex.Match(_defaultConnectionString, pattern, options).Groups[^ 1].Value, out var customerNumber)) { var adminTools = new AdminTools(sdkConnectionString); // Setup SDK DB await adminTools.DbSetup(token); var core = new Core(); await core.StartSqlOnly(sdkConnectionString); await core.SetSdkSetting(Settings.customerNo, customerNumber.ToString()); // setup admin var adminSetupModel = new AdminSetupModel() { DarkTheme = false, FirstName = firstName, LastName = lastName, Email = email, Password = password, }; var contextFactory = new BaseDbContextFactory(); await using var dbContext = contextFactory.CreateDbContext(new[] { _defaultConnectionString }); var connectionStringsSdk = scope.ServiceProvider.GetRequiredService <IDbOptions <ConnectionStringsSdk> >(); await connectionStringsSdk.UpdateDb( options => { options.SdkConnection = sdkConnectionString; }, dbContext); await SeedAdminHelper.SeedAdmin(adminSetupModel, "", dbContext); Restart(); } } } } }
public static async Task SeedAdmin(AdminSetupModel adminSetupModel, string defaultLocale, BaseDbContext dbContext) { var userStore = new UserStore <EformUser, EformRole, BaseDbContext, int, IdentityUserClaim <int>, EformUserRole, IdentityUserLogin <int>, IdentityUserToken <int>, IdentityRoleClaim <int> >(dbContext); IPasswordHasher <EformUser> hasher = new PasswordHasher <EformUser>(); var validator = new UserValidator <EformUser>(); var validators = new List <UserValidator <EformUser> > { validator }; var userManager = new UserManager <EformUser>(userStore, null, hasher, validators, null, null, null, null, null); // Set-up token providers. IUserTwoFactorTokenProvider <EformUser> tokenProvider = new EmailTokenProvider <EformUser>(); userManager.RegisterTokenProvider("Default", tokenProvider); IUserTwoFactorTokenProvider <EformUser> phoneTokenProvider = new PhoneNumberTokenProvider <EformUser>(); userManager.RegisterTokenProvider("PhoneTokenProvider", phoneTokenProvider); // Roles var roleStore = new RoleStore <EformRole, BaseDbContext, int>(dbContext); var roleManager = new RoleManager <EformRole>(roleStore, null, null, null, null); if (!await roleManager.RoleExistsAsync(EformRole.Admin)) { await roleManager.CreateAsync(new EformRole { Name = EformRole.Admin }); } if (!await roleManager.RoleExistsAsync(EformRole.User)) { await roleManager.CreateAsync(new EformRole { Name = EformRole.User }); } // Seed admin and demo users var timeZoneString = "Europe/Copenhagen"; try { TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); } catch { timeZoneString = "E. Europe Standard Time"; } var adminUser = new EformUser { UserName = adminSetupModel.Email, Email = adminSetupModel.Email, FirstName = adminSetupModel.FirstName, LastName = adminSetupModel.LastName, Locale = string.IsNullOrEmpty(defaultLocale) ? LocaleNames.English : defaultLocale, TimeZone = timeZoneString, DarkTheme = true, Formats = LocaleNames.German, EmailConfirmed = true, TwoFactorEnabled = false, IsGoogleAuthenticatorEnabled = false }; if (!userManager.Users.Any(x => x.Email.Equals(adminUser.Email))) { var createResult = await userManager.CreateAsync(adminUser, adminSetupModel.Password); if (!createResult.Succeeded) { throw new Exception("Could not create the user"); } } var user = userManager.Users.FirstOrDefault(x => x.Email.Equals(adminUser.Email)); if (!await userManager.IsInRoleAsync(user, EformRole.Admin)) { await userManager.AddToRoleAsync(user, EformRole.Admin); } }