WebApplicationExtensions.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Infrastructure.Persistence.Identity;
  2. using Microsoft.AspNetCore.Identity;
  3. namespace Admin.Extensions
  4. {
  5. public static class WebApplicationExtensions
  6. {
  7. /// <summary>
  8. /// 초기 관리자 계정 및 Admin 역할을 시드합니다.
  9. /// 계정이 이미 존재하면 Admin 역할만 보장합니다.
  10. /// </summary>
  11. public static async Task SeedAdminAccountAsync(this WebApplication app)
  12. {
  13. using var scope = app.Services.CreateScope();
  14. var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
  15. var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
  16. const string adminEmail = "jino@dpot.dev";
  17. const string adminPassword = "Admin@1234";
  18. const string adminRoleName = "Admin";
  19. // Admin 역할이 없으면 생성
  20. if (!await roleManager.RoleExistsAsync(adminRoleName))
  21. {
  22. await roleManager.CreateAsync(new IdentityRole(adminRoleName));
  23. }
  24. // 관리자 계정이 없으면 생성
  25. var existingUser = await userManager.FindByEmailAsync(adminEmail);
  26. if (existingUser == null)
  27. {
  28. var adminUser = new ApplicationUser
  29. {
  30. UserName = adminEmail,
  31. Email = adminEmail,
  32. EmailConfirmed = true
  33. };
  34. var result = await userManager.CreateAsync(adminUser, adminPassword);
  35. if (result.Succeeded)
  36. {
  37. await userManager.AddToRoleAsync(adminUser, adminRoleName);
  38. Console.WriteLine($"[Seed] 관리자 계정 생성 완료: {adminEmail}");
  39. }
  40. else
  41. {
  42. Console.WriteLine($"[Seed] 관리자 계정 생성 실패: {string.Join(", ", result.Errors.Select(e => e.Description))}");
  43. }
  44. }
  45. else
  46. {
  47. // 기존 계정이 Admin 역할이 없으면 추가
  48. if (!await userManager.IsInRoleAsync(existingUser, adminRoleName))
  49. {
  50. await userManager.AddToRoleAsync(existingUser, adminRoleName);
  51. Console.WriteLine($"[Seed] 기존 계정에 Admin 역할 부여: {adminEmail}");
  52. }
  53. }
  54. }
  55. }
  56. }