UserController.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using System.Diagnostics;
  2. using bitforum.Models;
  3. using bitforum.Models.User;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Identity;
  7. using Microsoft.EntityFrameworkCore;
  8. using bitforum.Models.Views;
  9. namespace bitforum.Controllers.Director
  10. {
  11. [Authorize]
  12. [Route("Director")]
  13. public class UserController : Controller
  14. {
  15. private readonly ILogger<UserController> _logger;
  16. private readonly UserManager<ApplicationUser> _userManager;
  17. private readonly RoleManager<IdentityRole> _roleManager;
  18. public UserController(ILogger<UserController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
  19. {
  20. _logger = logger;
  21. _userManager = userManager;
  22. _roleManager = roleManager;
  23. }
  24. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  25. public IActionResult Error()
  26. {
  27. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  28. }
  29. [HttpGet("User")]
  30. public async Task<IActionResult> Index()
  31. {
  32. var currentUser = await _userManager.GetUserAsync(User);
  33. var allUsers = await _userManager.Users.Where(a => a.Id != currentUser.Id).ToListAsync();
  34. // 사용자와 역할 정보를 매핑
  35. var userViewModels = new List<UserViewModel>();
  36. foreach (var user in allUsers)
  37. {
  38. var roles = await _userManager.GetRolesAsync(user); // 역할 조회
  39. userViewModels.Add(new UserViewModel
  40. {
  41. ID = user.Id,
  42. Name = user.FullName,
  43. Email = user.Email,
  44. Roles = roles.ToList()
  45. });
  46. }
  47. return View("~/Views/Director/User/Index.cshtml", userViewModels);
  48. }
  49. [HttpGet("User/{userID}")]
  50. public async Task<IActionResult> Edit(string userID)
  51. {
  52. var user = new ApplicationUser();
  53. try
  54. {
  55. if (string.IsNullOrEmpty(userID))
  56. {
  57. throw new Exception("유효하지 않은 사용자 ID입니다.");
  58. }
  59. user = await _userManager.FindByIdAsync(userID);
  60. if (user is null)
  61. {
  62. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  63. }
  64. }
  65. catch (Exception e)
  66. {
  67. _logger.LogError(e, e.Message);
  68. TempData["ErrorMessages"] = e.Message;
  69. return RedirectToAction(nameof(Index));
  70. }
  71. var viewModel = new UserViewModel{
  72. ID = user.Id,
  73. Name = user.UserName,
  74. Email = user.Email,
  75. Phone = user.PhoneNumber
  76. };
  77. return View("~/Views/Director/User/Edit.cshtml", viewModel);
  78. }
  79. [HttpPost("User")]
  80. public async Task<IActionResult> Update(UserViewModel request)
  81. {
  82. var user = new ApplicationUser();
  83. try
  84. {
  85. if (!ModelState.IsValid)
  86. {
  87. throw new Exception("유효성 검사에 실패하였습니다.");
  88. }
  89. user = await _userManager.FindByIdAsync(request.ID);
  90. if (user is null)
  91. {
  92. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  93. }
  94. // 중복확인
  95. if (await _userManager.Users.AnyAsync(u => u.Email == request.Email && u.Id != request.ID))
  96. {
  97. throw new Exception("이미 존재하는 이메일 주소입니다.");
  98. }
  99. // 사용자 정보 업데이트
  100. user.FullName = request.Name;
  101. user.Email = request.Email;
  102. user.NormalizedEmail = request.Email;
  103. user.PhoneNumber = request.Phone;
  104. var result = await _userManager.UpdateAsync(user);
  105. if (!result.Succeeded)
  106. {
  107. foreach (var error in result.Errors)
  108. {
  109. ModelState.AddModelError(string.Empty, error.Description);
  110. }
  111. throw new Exception("사용자 정보를 업데이트하는 중 오류가 발생했습니다.");
  112. }
  113. TempData["SuccessMessage"] = "사용자 정보가 정상적으로 수정되었습니다.";
  114. return RedirectToAction(nameof(Edit), new { userID = request.ID });
  115. }
  116. catch (Exception e)
  117. {
  118. _logger.LogError(e, e.Message);
  119. TempData["ErrorMessages"] = e.Message;
  120. return RedirectToAction(nameof(Edit), new { userID = request.ID });
  121. }
  122. }
  123. }
  124. }