RoleService.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.Logging;
  4. using WebApp.Common.Exceptions.ClientSide;
  5. using WebApp.Common.Exceptions.ServerSide;
  6. using WebApp.Common.Resources;
  7. using WebApp.Data;
  8. using WebApp.Data.Entities;
  9. using WebApp.Models.MappingExtensions;
  10. using WebApp.Models.Request.Roles;
  11. using WebApp.Models.Response.Roles;
  12. using WebApp.Services.Extensions;
  13. using WebApp.Services.Interfaces;
  14. namespace WebApp.Services.Implementations;
  15. public class RoleService : IRoleService
  16. {
  17. private readonly RoleManager<ApplicationRole> _roleManager;
  18. private readonly UserManager<ApplicationUser> _userManager;
  19. private readonly IUserService _userService;
  20. private readonly ApplicationContext _applicationContext;
  21. private readonly ILogger<RoleService> _logger;
  22. public RoleService(RoleManager<ApplicationRole> roleManager,
  23. UserManager<ApplicationUser> userManager,
  24. IUserService userService,
  25. ApplicationContext applicationContext,
  26. ILogger<RoleService> logger)
  27. {
  28. _roleManager = roleManager;
  29. _userManager = userManager;
  30. _userService = userService;
  31. _applicationContext = applicationContext;
  32. _logger = logger;
  33. }
  34. public async Task CreateAsync(CreateRoleRequestModel requestModel)
  35. {
  36. bool existsRole = await _roleManager.RoleExistsAsync(requestModel.Name);
  37. if (existsRole)
  38. {
  39. _logger.LogError("Role with name {roleName} already exists", requestModel.Name);
  40. throw new ExistsRoleException(Messages.RoleNameAlreadyExists);
  41. }
  42. ApplicationRole role = new()
  43. {
  44. Name = requestModel.Name,
  45. DescriptionEn = requestModel.DescriptionEn,
  46. DescriptionBg = requestModel.DescriptionBg,
  47. };
  48. IdentityResult identityResult = await _roleManager.CreateAsync(role);
  49. if (!identityResult.Succeeded)
  50. {
  51. _logger.LogError(identityResult.DisplayIdentityResultErrorMessages());
  52. throw new InvalidIdentityResultException(Messages.GeneralErrorMessage);
  53. }
  54. _logger.LogInformation("Succeeded create new role with name: {roleName}", requestModel.Name);
  55. }
  56. public async Task<RoleResponseModel> GetByIdAsync(Guid id)
  57. {
  58. ApplicationRole role = await FindByIdAsync(id);
  59. RoleResponseModel roleResponse = role.ToRoleResponseModel();
  60. return roleResponse;
  61. }
  62. public async Task<IReadOnlyList<RoleResponseModel>> GetAllAsync()
  63. {
  64. IReadOnlyList<RoleResponseModel> roles = await _roleManager.Roles
  65. .Select(x => x.ToRoleResponseModel())
  66. .ToListAsync();
  67. return roles;
  68. }
  69. public async Task UpdateAsync(Guid id, UpdateRoleRequestModel requestModel)
  70. {
  71. ApplicationRole role = await FindByIdAsync(id);
  72. bool existsName = await _applicationContext.Roles
  73. .AnyAsync(x => x.NormalizedName == requestModel.Name.ToUpper() && x.Id != role.Id);
  74. if (existsName)
  75. {
  76. _logger.LogError("Role with name {roleName} already exists", requestModel.Name);
  77. throw new ExistsRoleException(Messages.RoleNameAlreadyExists);
  78. }
  79. role.Name = requestModel.Name;
  80. role.DescriptionEn = requestModel.DescriptionEn;
  81. role.DescriptionBg = requestModel.DescriptionBg;
  82. IdentityResult identityResult = await _roleManager.UpdateAsync(role);
  83. if (!identityResult.Succeeded)
  84. {
  85. _logger.LogError(identityResult.DisplayIdentityResultErrorMessages());
  86. throw new InvalidIdentityResultException(Messages.GeneralErrorMessage);
  87. }
  88. _logger.LogInformation("Succeeded update role with ID: {roleId}", id);
  89. }
  90. public async Task RemoveAsync(Guid id)
  91. {
  92. ApplicationRole role = await FindByIdAsync(id);
  93. bool roleIsAssignedToUser = await _applicationContext.UserRoles.AnyAsync(x => x.RoleId == id);
  94. if (roleIsAssignedToUser)
  95. {
  96. _logger.LogError("Role with ID : {roleId} currently in use", id);
  97. throw new RemoveRoleException(Messages.RoleCurrentlyUse);
  98. }
  99. IdentityResult identityResult = await _roleManager.DeleteAsync(role);
  100. if (!identityResult.Succeeded)
  101. {
  102. _logger.LogError(identityResult.DisplayIdentityResultErrorMessages());
  103. throw new InvalidIdentityResultException(Messages.GeneralErrorMessage);
  104. }
  105. }
  106. public async Task AssignUserToRoleAsync(AssignToRoleRequestModel requestModel)
  107. {
  108. ApplicationUser user = await _userService.GetByIdAsync(requestModel.UserId);
  109. ApplicationRole role = await FindByIdAsync(requestModel.RoleId);
  110. bool isInRole = await _userManager.IsInRoleAsync(user, role.Name!);
  111. if (isInRole)
  112. {
  113. _logger.LogError("User with ID : {userId} is in role with ID : {roleId}", requestModel.UserId, requestModel.RoleId);
  114. throw new UserRoleExistsException(Messages.UserRoleExists);
  115. }
  116. IdentityResult identityResult = await _userManager.AddToRoleAsync(user, role.Name!);
  117. if (!identityResult.Succeeded)
  118. {
  119. _logger.LogError(identityResult.DisplayIdentityResultErrorMessages());
  120. throw new InvalidIdentityResultException(Messages.GeneralErrorMessage);
  121. }
  122. _logger.LogInformation("Succeeded assign user with ID : {userId} to role with ID : {roleId}", requestModel.UserId, requestModel.RoleId);
  123. }
  124. public async Task RemoveUserFromRoleAsync(RemoveFromRoleRequestModel requestModel)
  125. {
  126. ApplicationUser user = await _userService.GetByIdAsync(requestModel.UserId);
  127. ApplicationRole role = await FindByIdAsync(requestModel.RoleId);
  128. bool isInRole = await _userManager.IsInRoleAsync(user, role.Name!);
  129. if (!isInRole)
  130. {
  131. _logger.LogError("User with ID : {userId} is not in role with ID : {roleId}", requestModel.UserId, requestModel.RoleId);
  132. throw new UserNotInRoleException(Messages.UserNotInRole);
  133. }
  134. IdentityResult identityResult = await _userManager.RemoveFromRoleAsync(user, role.Name!);
  135. if (!identityResult.Succeeded)
  136. {
  137. _logger.LogError(identityResult.DisplayIdentityResultErrorMessages());
  138. throw new InvalidIdentityResultException(Messages.GeneralErrorMessage);
  139. }
  140. _logger.LogInformation("Succeeded remove user with ID : {userId} from role with ID : {roleId}", requestModel.UserId, requestModel.RoleId);
  141. }
  142. private async Task<ApplicationRole> FindByIdAsync(Guid id)
  143. {
  144. ApplicationRole? role = await _roleManager.FindByIdAsync(id.ToString());
  145. if (role is null)
  146. {
  147. _logger.LogError("Not found role with present ID : {roleId}", id);
  148. throw new NotFoundRoleException(Messages.RoleNotFound);
  149. }
  150. return role;
  151. }
  152. }