39 lines
1.2 KiB
C#
39 lines
1.2 KiB
C#
using Microsoft.AspNetCore.Identity;
|
|
|
|
namespace RhSolutions.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>>();
|
|
RoleManager<IdentityRole> roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
|
|
|
string username = "admin";
|
|
string password = configuration["ADMIN_PASSWORD"] ?? "RhSolutionsPassword123!";
|
|
string role = "Admins";
|
|
|
|
if (await userManager.FindByNameAsync(username) == null)
|
|
{
|
|
if (await roleManager.FindByNameAsync(role) == null)
|
|
{
|
|
await roleManager.CreateAsync(new(role));
|
|
}
|
|
IdentityUser user = new()
|
|
{
|
|
UserName = username
|
|
};
|
|
IdentityResult result = await userManager.CreateAsync(user, password);
|
|
if (result.Succeeded)
|
|
{
|
|
await userManager.AddToRoleAsync(user, role);
|
|
}
|
|
}
|
|
}
|
|
} |