AttachController.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System.Diagnostics;
  2. using bitforum.Models;
  3. using bitforum.Models.User;
  4. using bitforum.Models.Views;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.AspNetCore.Identity;
  8. using Microsoft.EntityFrameworkCore;
  9. namespace bitforum.Controllers.Director
  10. {
  11. [Authorize]
  12. [Route("Director")]
  13. public class AttachController : Controller
  14. {
  15. private readonly ILogger<AttachController> _logger;
  16. private readonly string _ViewPath = "~/Views/Director/Attach.cshtml";
  17. private readonly UserManager<ApplicationUser> _userManager;
  18. private readonly RoleManager<IdentityRole> _roleManager;
  19. public AttachController(ILogger<AttachController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
  20. {
  21. _logger = logger;
  22. _userManager = userManager;
  23. _roleManager = roleManager;
  24. }
  25. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  26. public IActionResult Error()
  27. {
  28. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  29. }
  30. [HttpGet("Attach")]
  31. public async Task<IActionResult> Index(string userID)
  32. {
  33. var user = await _userManager.FindByIdAsync(userID);
  34. if (user == null)
  35. {
  36. return NotFound();
  37. }
  38. var roles = await _roleManager.Roles.ToListAsync();
  39. var viewModel = new AttachViewModel
  40. {
  41. UserID = user.Id,
  42. Roles = roles.Select(role => new CheckBoxViewModel
  43. {
  44. DisplayValue = role.Name,
  45. IsSelected = _userManager.IsInRoleAsync(user, role.Name).Result
  46. }).ToList()
  47. };
  48. return View(_ViewPath, viewModel);
  49. }
  50. [HttpPost]
  51. public async Task<IActionResult> Save(AttachViewModel request)
  52. {
  53. if (!ModelState.IsValid)
  54. {
  55. return View(_ViewPath, request);
  56. }
  57. var user = await _userManager.FindByIdAsync(request.UserID);
  58. if (user == null)
  59. {
  60. return NotFound();
  61. }
  62. // 회원의 역할 조회
  63. var userRoles = await _userManager.GetRolesAsync(user);
  64. // 회원의 기존 역할 제거 후 새로운 역할 추가
  65. /*
  66. await _userManager.RemoveFromRolesAsync(user, userRoles);
  67. await _userManager.AddToRolesAsync(user, model.Roles.Where(r => r.IsSelected).Select(r => r.DisplayValue));
  68. */
  69. foreach (var role in request.Roles)
  70. {
  71. // 현재 사용자의 역할에 포함되어 있으나 선택되지 않은 경우 해당 역할 제거
  72. if (userRoles.Any(r => r == role.DisplayValue) && !role.IsSelected)
  73. {
  74. await _userManager.RemoveFromRoleAsync(user, role.DisplayValue);
  75. }
  76. // 현재 사용자의 역할에 포함되지 않았으나 선택된 경우 해당 역할 추가
  77. if (!userRoles.Any(r => r == role.DisplayValue) && role.IsSelected)
  78. {
  79. await _userManager.AddToRoleAsync(user, role.DisplayValue);
  80. }
  81. }
  82. var message = $"역할이 정상적으로 적용되었습니다.";
  83. TempData["SuccessMessage"] = message;
  84. _logger.LogInformation(message);
  85. return RedirectToAction("index", "Attach", new { userId = request.UserID });
  86. }
  87. }
  88. }