using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using ExpenseTracker.Application.Common.Models; using ExpenseTracker.Infrastructure.Identity.Models; namespace ExpenseTracker.Infrastructure.Identity; public static class IdentitySeeder { private static UserManager _userManager; private static RoleManager _roleManager; public static void SeedIdentity(IServiceScope serviceScope) { _userManager = serviceScope.ServiceProvider.GetService>(); _userManager.UserValidators.Clear(); _userManager.PasswordValidators.Clear(); _roleManager = serviceScope.ServiceProvider.GetService>(); _roleManager.RoleValidators.Clear(); SeedRoles(); SeedUsers(); } private static void SeedRoles() { var roles = Enum.GetValues(typeof(IdentityRoles)).Cast(); foreach (var role in roles) { var roleName = role.ToString(); var roleExists = _roleManager.RoleExistsAsync(roleName).GetAwaiter().GetResult(); if (roleExists) { continue; } _roleManager.CreateAsync(new ApplicationRole() { Id = Guid.NewGuid().ToString(), Name = roleName, ConcurrencyStamp = Guid.NewGuid().ToString("D") }).GetAwaiter().GetResult(); } } private static void SeedUsers() { var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), Email = "user", NormalizedEmail = "user", EmailConfirmed = true, SecurityStamp = Guid.NewGuid().ToString("D"), Roles = _roleManager.Roles.Where(r => r.Name == IdentityRoles.User.ToString()).Select(r => r.Id).ToList(), RefreshTokens = new RefreshToken[0] }; var userExists = _userManager.FindByEmailAsync(user.Email).Result is not null; if (!userExists) { var hashed = _userManager.PasswordHasher.HashPassword(user, "user"); user.PasswordHash = hashed; _userManager.CreateAsync(user); } var admin = new ApplicationUser { Id = Guid.NewGuid().ToString(), Email = "admin", NormalizedEmail = "admin", EmailConfirmed = true, SecurityStamp = Guid.NewGuid().ToString("D"), Roles = _roleManager.Roles.Where(r => r.Name == IdentityRoles.Administrator.ToString()).Select(r => r.Id).ToList(), RefreshTokens = new RefreshToken[0] }; userExists = _userManager.FindByEmailAsync(admin.Email).Result is not null; if (!userExists) { var hashed = _userManager.PasswordHasher.HashPassword(admin, "admin"); admin.PasswordHash = hashed; _userManager.CreateAsync(admin); _userManager.AddToRoleAsync(admin, IdentityRoles.Administrator.ToString()); } var adminUser = new ApplicationUser { Id = Guid.NewGuid().ToString(), Email = "adminUser", NormalizedEmail = "ADMINUSER", EmailConfirmed = true, SecurityStamp = Guid.NewGuid().ToString("D"), Roles = _roleManager.Roles.Where(r => r.Name == IdentityRoles.Administrator.ToString() || r.Name == IdentityRoles.User.ToString()).Select(r => r.Id).ToList(), RefreshTokens = new RefreshToken[0] }; userExists = _userManager.FindByEmailAsync(adminUser.Email).Result is not null; if (!userExists) { var hashed = _userManager.PasswordHasher.HashPassword(adminUser, "adminUser"); adminUser.PasswordHash = hashed; _userManager.CreateAsync(adminUser); } } }