UserService.cs 14 KB

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