From 45af463dbe359332967c75e4fdb8ab50e2d9e847 Mon Sep 17 00:00:00 2001 From: Sergey Chebotar Date: Tue, 7 Mar 2023 08:18:01 +0300 Subject: [PATCH] Create admin user seed --- Models/IdentitySeedData.cs | 30 ++++++++++++++++++++++++++++++ Program.cs | 8 ++++++++ 2 files changed, 38 insertions(+) create mode 100644 Models/IdentitySeedData.cs diff --git a/Models/IdentitySeedData.cs b/Models/IdentitySeedData.cs new file mode 100644 index 0000000..dcaa5c3 --- /dev/null +++ b/Models/IdentitySeedData.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Identity; + +namespace MyDarling.Models; + +public class IdentitySeedData +{ + public static void CreateAdminAccount(IServiceProvider serviceProvider, IConfiguration configuration) + { + CreateAdminAccountAsync(serviceProvider, configuration).Wait(); + } + + public static async Task CreateAdminAccountAsync(IServiceProvider serviceProvider, IConfiguration configuration) + { + serviceProvider = serviceProvider.CreateScope().ServiceProvider; + UserManager userManager = serviceProvider.GetRequiredService>(); + + string username = configuration["ADMIN_USERNAME"] ?? "admin"; + string password = configuration["ADMIN_PASSWORD"] ?? "Password123$"; + + if (await userManager.FindByNameAsync(username) == null) + { + IdentityUser adminUser = new IdentityUser + { + UserName = username + }; + + IdentityResult result = await userManager.CreateAsync(adminUser, password); + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index eda78fa..cfc572a 100644 --- a/Program.cs +++ b/Program.cs @@ -17,6 +17,13 @@ builder.Services.AddDbContext(opts => builder.Services.AddIdentity() .AddEntityFrameworkStores(); + +builder.Services.Configure( opts => +{ + opts.Password.RequiredLength = 6; + opts.Password.RequireNonAlphanumeric = false; + opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz"; +}); builder.Services.AddControllersWithViews(); @@ -28,5 +35,6 @@ app.MapDefaultControllerRoute(); app.UseAuthentication(); app.UseAuthorization(); +IdentitySeedData.CreateAdminAccount(app.Services, app.Configuration); app.Run(); \ No newline at end of file