UserService.cs 13 KB

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