UserService.cs 14 KB

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