UserService.cs 9.7 KB

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