Create admin user seed
This commit is contained in:
parent
0c4d13caed
commit
45af463dbe
30
Models/IdentitySeedData.cs
Normal file
30
Models/IdentitySeedData.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -18,6 +18,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();
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
@ -28,5 +35,6 @@ app.MapDefaultControllerRoute();
|
|||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
IdentitySeedData.CreateAdminAccount(app.Services, app.Configuration);
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
Loading…
Reference in New Issue
Block a user