UserService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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.Application.Services.Interfaces;
  12. using MTWorkHR.Core.Email;
  13. using MTWorkHR.Core.Entities;
  14. using MTWorkHR.Infrastructure.UnitOfWorks;
  15. using MTWorkHR.Infrastructure.Entities;
  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<List<UserDto>> GetAllEmployees()
  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. // _fileService.UploadFiles(files);
  95. if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  96. throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  97. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  98. _unitOfWork.BeginTran();
  99. //saving user
  100. var result = await _userManager.CreateAsync(user, input.Password);
  101. if (!result.Succeeded)
  102. throw new AppException(ExceptionEnum.RecordCreationFailed);
  103. input.Id = user.Id;
  104. //saving userRoles
  105. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  106. foreach (var role in userRoles)
  107. {
  108. role.UserId = user.Id;
  109. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  110. throw new AppException(ExceptionEnum.RecordNotExist);
  111. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  112. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  113. await _userManager.AddToRoleAsync(user, roleName);
  114. }
  115. // await _userRole.AddRangeAsync(userRoles);
  116. await _unitOfWork.CompleteAsync();
  117. _unitOfWork.CommitTran();
  118. try
  119. {
  120. var resultPassReset = await GetConfirmEmailURL(user.Id);
  121. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  122. {
  123. Subject = "Register Confirmation",
  124. To = input.Email,
  125. Body = "Please Set Your Password (this link will expired after 24 hours)"
  126. ,
  127. url = resultPassReset.Item1,
  128. userId = user.Id
  129. });
  130. if (!sendMailResult)
  131. {
  132. throw new AppException("User created, but could not send the email!");
  133. }
  134. }
  135. catch
  136. {
  137. throw new AppException("User created, but could not send the email!");
  138. }
  139. return input;
  140. }
  141. public async Task<bool> ConfirmEmail(ForgetPasswordDto input)
  142. {
  143. var user = await _userManager.FindByEmailAsync(input.Email);
  144. if (user == null)
  145. throw new AppException(ExceptionEnum.RecordNotExist);
  146. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  147. return result.Succeeded;
  148. }
  149. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  150. {
  151. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  152. if (user == null)
  153. throw new AppException(ExceptionEnum.RecordNotExist);
  154. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  155. var route = "auth/ConfirmEmail";
  156. var origin = _configuration.JwtSettings.Audience;
  157. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  158. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  159. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  160. return new Tuple<string, string>(passwordResetURL, user.Email);
  161. }
  162. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  163. {
  164. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  165. if (user == null)
  166. throw new AppException(ExceptionEnum.RecordNotExist);
  167. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  168. var route = "auth/ConfirmEmail";
  169. var origin = _configuration.JwtSettings.Audience;
  170. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  171. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  172. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", token);
  173. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  174. }
  175. public async Task<UserDto> Update(UserDto input)
  176. {
  177. try
  178. {
  179. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == input.Id);
  180. if (entity == null)
  181. throw new AppException(ExceptionEnum.RecordNotExist);
  182. MapperObject.Mapper.Map(input, entity);
  183. _unitOfWork.BeginTran();
  184. //saving user
  185. var result = await _userManager.UpdateAsync(entity);
  186. if (!result.Succeeded)
  187. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  188. //**saving userRoles
  189. //add new user roles
  190. var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  191. if (input.UserRoles == null)
  192. input.UserRoles = new List<UserRoleDto>();
  193. var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  194. newAddedRoles.ForEach(x => x.UserId = input.Id);
  195. await _userRole.AddRangeAsync(newAddedRoles);
  196. //delete removed roles
  197. var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  198. var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  199. await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  200. await _unitOfWork.CompleteAsync();
  201. _unitOfWork.CommitTran();
  202. }
  203. catch (Exception e)
  204. {
  205. throw e;
  206. }
  207. return input;
  208. }
  209. public Task<UserDto> UpdateWithoutChildren(UserDto input)
  210. {
  211. throw new NotImplementedException();
  212. }
  213. public async Task<bool> IsExpiredToken(ForgetPasswordDto input)
  214. {
  215. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  216. if (user == null)
  217. throw new AppException(ExceptionEnum.RecordNotExist);
  218. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  219. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  220. return !result;
  221. }
  222. public async Task<bool> ForgetPassword(ForgetPasswordDto model)
  223. {
  224. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == model.UserId);
  225. if (user == null)
  226. throw new AppException(ExceptionEnum.RecordNotExist);
  227. var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
  228. return result.Succeeded;
  229. }
  230. public async Task<bool> ResetPassword(ResetPasswordDto input)
  231. {
  232. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  233. if (user == null)
  234. throw new AppException(ExceptionEnum.RecordNotExist);
  235. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  236. throw new AppException(ExceptionEnum.WrongCredentials);
  237. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  238. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  239. if (!result.Succeeded)
  240. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  241. return true;
  242. }
  243. public async Task ForgetPasswordMail(string userId)
  244. {
  245. var resultPassReset = await GetResetPasswordURL(userId);
  246. await _emailSender.SendEmail(new EmailMessage
  247. {
  248. Subject = "Register Confirmation",
  249. To = resultPassReset.Item2,
  250. Body = "Forget Your Password, link will expired after 24 hours",
  251. url = resultPassReset.Item1,
  252. userId = userId
  253. });
  254. }
  255. public async Task StopUser(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. if (!entity.IsStopped)
  261. {
  262. entity.IsStopped = true;
  263. await _unitOfWork.CompleteAsync();
  264. }
  265. }
  266. public async Task ActiveUser(string userId)
  267. {
  268. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  269. if (entity == null)
  270. throw new AppException(ExceptionEnum.RecordNotExist);
  271. entity.IsStopped = false;
  272. entity.AccessFailedCount = 0;
  273. entity.LockoutEnabled = false;
  274. entity.LockoutEnd = null;
  275. await _unitOfWork.CompleteAsync();
  276. }
  277. }
  278. }