| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- using Infrastructure.Persistence.Identity;
- using Microsoft.AspNetCore.Identity;
- namespace Admin.Extensions;
- public static class WebApplicationExtensions
- {
- /// <summary>
- /// 초기 관리자 계정 및 Admin 역할을 시드합니다.
- /// 계정이 이미 존재하면 Admin 역할만 보장합니다.
- /// </summary>
- public static async Task SeedAdminAccountAsync(this WebApplication app)
- {
- using var scope = app.Services.CreateScope();
- var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
- var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
- const string adminEmail = "jino@dpot.dev";
- const string adminPassword = "Admin@1234";
- const string adminRoleName = "Admin";
- // Admin 역할이 없으면 생성
- if (!await roleManager.RoleExistsAsync(adminRoleName))
- {
- await roleManager.CreateAsync(new IdentityRole(adminRoleName));
- }
- // 관리자 계정이 없으면 생성
- var existingUser = await userManager.FindByEmailAsync(adminEmail);
- if (existingUser == null)
- {
- var adminUser = new ApplicationUser
- {
- UserName = adminEmail,
- Email = adminEmail,
- EmailConfirmed = true
- };
- var result = await userManager.CreateAsync(adminUser, adminPassword);
- if (result.Succeeded)
- {
- await userManager.AddToRoleAsync(adminUser, adminRoleName);
- Console.WriteLine($"[Seed] 관리자 계정 생성 완료: {adminEmail}");
- }
- else
- {
- Console.WriteLine($"[Seed] 관리자 계정 생성 실패: {string.Join(", ", result.Errors.Select(e => e.Description))}");
- }
- }
- else
- {
- // 기존 계정이 Admin 역할이 없으면 추가
- if (!await userManager.IsInRoleAsync(existingUser, adminRoleName))
- {
- await userManager.AddToRoleAsync(existingUser, adminRoleName);
- Console.WriteLine($"[Seed] 기존 계정에 Admin 역할 부여: {adminEmail}");
- }
- }
- // 이관/직접 INSERT 계정의 SecurityStamp 누락 보정 — 비밀번호 재설정 토큰 생성에 필수
- var stampless = userManager.Users.Where(c => c.SecurityStamp == null).ToList();
- foreach (var user in stampless)
- {
- await userManager.UpdateSecurityStampAsync(user);
- Console.WriteLine($"[Seed] SecurityStamp 보정: {user.Email}");
- }
- }
- }
|