0
0

Create admin user seed

This commit is contained in:
Sergey Chebotar 2023-03-07 08:18:01 +03:00
parent 0c4d13caed
commit 45af463dbe
2 changed files with 38 additions and 0 deletions

View File

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

View File

@ -17,6 +17,13 @@ builder.Services.AddDbContext<IdentityContext>(opts =>
builder.Services.AddIdentity<IdentityUser, IdentityRole>() builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityContext>(); .AddEntityFrameworkStores<IdentityContext>();
builder.Services.Configure<IdentityOptions>( opts =>
{
opts.Password.RequiredLength = 6;
opts.Password.RequireNonAlphanumeric = false;
opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
});
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
@ -28,5 +35,6 @@ app.MapDefaultControllerRoute();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
IdentitySeedData.CreateAdminAccount(app.Services, app.Configuration);
app.Run(); app.Run();