UserService.cs 9.3 KB

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