UserService.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.WebUtilities;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Configuration;
  5. using MTWorkHR.Application.Identity;
  6. using MTWorkHR.Application.MappingProfiles;
  7. using MTWorkHR.Application.Models;
  8. using MTWorkHR.Application.Services;
  9. using MTWorkHR.Application.Models.Email;
  10. using MTWorkHR.Core.Global;
  11. using MTWorkHR.Core.IRepositories;
  12. using MTWorkHR.Core.UnitOfWork;
  13. using MTWorkHR.Identity.Entities;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using NeomtechERP.Auth.Core.Global;
  20. using Microsoft.AspNetCore.Identity.UI.Services;
  21. using IEmailSender = MTWorkHR.Application.Services.IEmailSender;
  22. using System.Security.Policy;
  23. namespace MTWorkHR.Identity.Services
  24. {
  25. public class UserService : IUserService
  26. {
  27. private readonly RoleManager<ApplicationRole> _roleManager;
  28. private readonly ApplicationUserManager _userManager;
  29. private readonly IUnitOfWork _unitOfWork;
  30. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  31. private readonly AppSettingsConfiguration _configuration;
  32. private readonly IEmailSender _emailSender;
  33. private readonly GlobalInfo _globalInfo;
  34. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  35. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IEmailSender emailSender
  36. , IUserRoleRepository<IdentityUserRole<string>> userRole)
  37. {
  38. _userManager = userManager;
  39. _unitOfWork = unitOfWork;
  40. _roleManager = roleManager;
  41. _userRole = userRole;
  42. _configuration = configuration;
  43. _emailSender = emailSender;
  44. _globalInfo = globalInfo;
  45. }
  46. public async Task<UserDto> GetById(string userId)
  47. {
  48. var employee = await _userManager.FindByIdAsync(userId);
  49. return new UserDto
  50. {
  51. Email = employee.Email,
  52. FirstName = employee.FirstName,
  53. LastName = employee.LastName,
  54. Id = employee.Id
  55. };
  56. }
  57. public async Task<List<UserDto>> GetAll()
  58. {
  59. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  60. return employees.Select( e=> new UserDto
  61. {
  62. Email = e.Email,
  63. FirstName = e.FirstName,
  64. LastName = e.LastName,
  65. Id = e.Id
  66. }).ToList();
  67. }
  68. public async Task Delete(string id)
  69. {
  70. var user = await _userManager.FindByIdAsync(id);
  71. if (user != null)
  72. {
  73. user.IsDeleted = true;
  74. await _userManager.UpdateAsync(user);
  75. }
  76. }
  77. public async Task<UserDto> Create(UserDto input)
  78. {
  79. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  80. if (emailExists != null)
  81. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  82. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  83. if (phoneExists != null)
  84. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  85. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  86. if (userExists != null)
  87. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  88. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  89. _unitOfWork.BeginTran();
  90. //saving user
  91. var result = await _userManager.CreateAsync(user);
  92. if (!result.Succeeded)
  93. throw new AppException(ExceptionEnum.RecordCreationFailed);
  94. input.Id = user.Id;
  95. //saving userRoles
  96. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  97. foreach (var role in userRoles)
  98. {
  99. role.UserId = user.Id;
  100. if ((await _roleManager.FindByIdAsync(role.RoleId)) == null)
  101. throw new AppException(ExceptionEnum.RecordNotExist);
  102. }
  103. await _userRole.AddRangeAsync(userRoles);
  104. await _unitOfWork.CompleteAsync();
  105. _unitOfWork.CommitTran();
  106. try
  107. {
  108. var resultPassReset = await GetResetPasswordURL(user.Id);
  109. var sendMailResult = await _emailSender.SendEmail(new EmailMessage {
  110. Subject = "Register Confirmation",
  111. To = input.Email,
  112. Body = "Please Set Your Password (this link will expired after 24 hours)"
  113. , url = resultPassReset.Item1, userId = user.Id } );
  114. if (!sendMailResult)
  115. {
  116. throw new AppException("User created, but could not send the email!");
  117. }
  118. }
  119. catch
  120. {
  121. throw new AppException("User created, but could not send the email!");
  122. }
  123. return input;
  124. }
  125. private async Task<Tuple< string, string>> GetResetPasswordURL(string userId)
  126. {
  127. var user = await _userManager.Users.FirstOrDefaultAsync(x => (!x.IsDeleted) && x.Id.Equals(userId));
  128. if (user == null)
  129. throw new AppException(ExceptionEnum.RecordNotExist);
  130. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  131. var route = "auth/forgetpassword";
  132. var origin = _configuration.JwtSettings.Audience;
  133. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  134. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  135. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  136. return new Tuple <string, string> ( passwordResetURL, user.Email);
  137. }
  138. public Task<UserDto> Update(UserDto input)
  139. {
  140. throw new NotImplementedException();
  141. }
  142. public Task<UserDto> UpdateWithoutChildren(UserDto input)
  143. {
  144. throw new NotImplementedException();
  145. }
  146. public async Task<bool> IsExpiredToken(ForgetPasswordDto input)
  147. {
  148. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  149. if (user == null)
  150. throw new AppException(ExceptionEnum.RecordNotExist);
  151. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  152. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  153. return !result;
  154. }
  155. public async Task<bool> ForgetPassword(ForgetPasswordDto model)
  156. {
  157. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == model.UserId);
  158. if (user == null)
  159. throw new AppException(ExceptionEnum.RecordNotExist);
  160. var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
  161. return result.Succeeded;
  162. }
  163. public async Task<bool> ResetPassword(ResetPasswordDto input)
  164. {
  165. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  166. if (user == null)
  167. throw new AppException(ExceptionEnum.RecordNotExist);
  168. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  169. throw new AppException(ExceptionEnum.WrongCredentials);
  170. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  171. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  172. if (!result.Succeeded)
  173. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  174. return true;
  175. }
  176. public async Task ForgetPasswordMail(string userId)
  177. {
  178. var resultPassReset = await GetResetPasswordURL(userId);
  179. await _emailSender.SendEmail(new EmailMessage
  180. {
  181. Subject = "Register Confirmation",
  182. To = resultPassReset.Item2,
  183. Body = "Forget Your Password, link will expired after 24 hours",
  184. url = resultPassReset.Item1,
  185. userId = userId
  186. });
  187. }
  188. public async Task StopUser(string userId)
  189. {
  190. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  191. if (entity == null)
  192. throw new AppException(ExceptionEnum.RecordNotExist);
  193. if (!entity.IsStopped)
  194. {
  195. entity.IsStopped = true;
  196. await _unitOfWork.CompleteAsync();
  197. }
  198. }
  199. public async Task ActiveUser(string userId)
  200. {
  201. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  202. if (entity == null)
  203. throw new AppException(ExceptionEnum.RecordNotExist);
  204. entity.IsStopped = false;
  205. entity.AccessFailedCount = 0;
  206. entity.LockoutEnabled = false;
  207. entity.LockoutEnd = null;
  208. await _unitOfWork.CompleteAsync();
  209. }
  210. }
  211. }