UserService.cs 11 KB

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