0
0
RhSolutions-Api/RhSolutions.Api/Models/IdentitySeedData.cs

39 lines
1.2 KiB
C#
Raw Normal View History

2024-02-07 16:32:34 +03:00
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);
}
}
}
}