0
0
RhSolutions-Api/RhSolutions.Api/Models/IdentitySeedData.cs
Serghei Cebotari e9e34c5fec
All checks were successful
Test and release / test (push) Successful in 1m44s
Test and release / release-image (push) Successful in 3m51s
Implement JWT tokens
2024-02-07 16:32:34 +03:00

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