diff options
author | Sergey Chebotar <s.chebotar@gmail.com> | 2023-03-07 08:18:01 +0300 |
---|---|---|
committer | Sergey Chebotar <s.chebotar@gmail.com> | 2023-03-07 08:18:01 +0300 |
commit | 45af463dbe359332967c75e4fdb8ab50e2d9e847 (patch) | |
tree | 3acf3cfe57dbf5d4fb7bf0fd01207677e0d3de95 | |
parent | 0c4d13caed53b2702eef41461d0c8a4b25df48f6 (diff) |
Create admin user seed
-rw-r--r-- | Models/IdentitySeedData.cs | 30 | ||||
-rw-r--r-- | Program.cs | 8 |
2 files changed, 38 insertions, 0 deletions
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<IdentityUser> userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>(); + + 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 @@ -17,6 +17,13 @@ builder.Services.AddDbContext<IdentityContext>(opts => builder.Services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<IdentityContext>(); + +builder.Services.Configure<IdentityOptions>( 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 |