WebApplicationExtensions.cs 2.2 KB

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