UserService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. using MTWorkHR.Core.IDto;
  20. using System.Linq.Dynamic.Core;
  21. using MTWorkHR.Core.Entities.Base;
  22. namespace MTWorkHR.Application.Services
  23. {
  24. public class UserService : IUserService
  25. {
  26. private readonly RoleManager<ApplicationRole> _roleManager;
  27. private readonly ApplicationUserManager _userManager;
  28. private readonly IUnitOfWork _unitOfWork;
  29. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  30. private readonly AppSettingsConfiguration _configuration;
  31. private readonly IMailSender _emailSender;
  32. private readonly GlobalInfo _globalInfo;
  33. private readonly IFileService _fileService;
  34. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  35. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IMailSender emailSender
  36. , IUserRoleRepository<IdentityUserRole<string>> userRole, IFileService fileService)
  37. {
  38. _userManager = userManager;
  39. _unitOfWork = unitOfWork;
  40. _roleManager = roleManager;
  41. _userRole = userRole;
  42. _configuration = configuration;
  43. _emailSender = emailSender;
  44. _globalInfo = globalInfo;
  45. _fileService = fileService;
  46. }
  47. public async Task<UserDto> GetById(string id)
  48. {
  49. var entity = await _userManager.Users
  50. .Include(x => x.UserRoles)
  51. .Include(x => x.UserAddress)
  52. .Include(x => x.UserAttachments)
  53. .FirstOrDefaultAsync(x => x.Id == id);
  54. var response = MapperObject.Mapper.Map<UserDto>(entity);
  55. return response;
  56. }
  57. //public async Task<List<UserDto>> GetAll(PagingInputDto pagingInput)
  58. //{
  59. // var employees = await _userManager.GetUsersInRoleAsync("Employee");
  60. // return employees.Select(e => new UserDto
  61. // {
  62. // Email = e.Email,
  63. // FirstName = e.FirstName,
  64. // LastName = e.LastName,
  65. // Id = e.Id
  66. // }).ToList();
  67. //}
  68. public virtual async Task<PagingResultDto<UserAllDto>> GetAll(UserPagingInputDto PagingInputDto)
  69. {
  70. var query = _userManager.Users
  71. .Include(u => u.Qualification).Include(u => u.JobTitle).Include(u => u.University).Include(u => u.Industry).Include(u => u.Country)
  72. .AsQueryable();
  73. if (PagingInputDto.Filter != null)
  74. {
  75. var filter = PagingInputDto.Filter;
  76. query = query.Where(u =>
  77. u.UserName.Contains(filter) ||
  78. u.Email.Contains(filter) ||
  79. u.FirstName.Contains(filter) ||
  80. u.LastName.Contains(filter) ||
  81. u.FavoriteName.Contains(filter) ||
  82. u.PhoneNumber.Contains(filter));
  83. }
  84. if (PagingInputDto.IndustryId != null)
  85. {
  86. query = query.Where(u => u.IndustryId == PagingInputDto.IndustryId);
  87. }
  88. if (PagingInputDto.QualificationId != null)
  89. {
  90. query = query.Where(u => u.QualificationId == PagingInputDto.QualificationId);
  91. }
  92. if (PagingInputDto.JobTitleId != null)
  93. {
  94. query = query.Where(u => u.JobTitleId == PagingInputDto.JobTitleId);
  95. }
  96. if (PagingInputDto.UniversityId != null)
  97. {
  98. query = query.Where(u => u.UniversityId == PagingInputDto.UniversityId);
  99. }
  100. if (PagingInputDto.CountryId != null)
  101. {
  102. query = query.Where(u => u.CountryId == PagingInputDto.CountryId);
  103. }
  104. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  105. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  106. var total = await query.CountAsync();
  107. var list = MapperObject.Mapper
  108. .Map<IList<UserAllDto>>(await page.ToListAsync());
  109. var response = new PagingResultDto<UserAllDto>
  110. {
  111. Result = list,
  112. Total = total
  113. };
  114. return response;
  115. }
  116. public async Task<List<UserDto>> GetAllEmployees()
  117. {
  118. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  119. return employees.Select(e => new UserDto
  120. {
  121. Email = e.Email,
  122. FirstName = e.FirstName,
  123. LastName = e.LastName,
  124. Id = e.Id
  125. }).ToList();
  126. }
  127. public async Task Delete(string id)
  128. {
  129. var user = await _userManager.FindByIdAsync(id);
  130. if (user != null)
  131. {
  132. user.IsDeleted = true;
  133. await _userManager.UpdateAsync(user);
  134. }
  135. }
  136. public async Task<UserDto> Create(UserDto input)
  137. {
  138. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  139. if (emailExists != null)
  140. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  141. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  142. if (phoneExists != null)
  143. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  144. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  145. if (userExists != null)
  146. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  147. //loop for given list of attachment, and move each file from Temp path to Actual path
  148. // _fileService.UploadFiles(files);
  149. if (input.UserAttachments == null )
  150. input.UserAttachments = new List<AttachmentDto>();
  151. if(input.CVAttach != null)
  152. {
  153. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name,FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  154. }
  155. if (input.PassportAttach != null)
  156. {
  157. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  158. }
  159. if (input.EduCertificateAttach != null)
  160. {
  161. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  162. }
  163. if (input.ExperienceCertificateAttach != null)
  164. {
  165. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  166. }
  167. if (input.ProfCertificateAttach != null)
  168. {
  169. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  170. }
  171. if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  172. throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  173. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  174. if(user.UserType == 0)
  175. {
  176. user.UserType = (int)UserTypeEnum.Employee;//default if not selected
  177. }
  178. _unitOfWork.BeginTran();
  179. //saving user
  180. var result = await _userManager.CreateAsync(user, input.Password);
  181. if (!result.Succeeded)
  182. throw new AppException(ExceptionEnum.RecordCreationFailed);
  183. input.Id = user.Id;
  184. //saving userRoles
  185. if(input.UserRoles == null || input.UserRoles.Count == 0)
  186. {
  187. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  188. if (employeeRole == null)
  189. {
  190. await _userManager.AddToRoleAsync(user, "Employee");
  191. }
  192. }
  193. else
  194. {
  195. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  196. foreach (var role in userRoles)
  197. {
  198. role.UserId = user.Id;
  199. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  200. throw new AppException(ExceptionEnum.RecordNotExist);
  201. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  202. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  203. await _userManager.AddToRoleAsync(user, roleName);
  204. }
  205. }
  206. // await _userRole.AddRangeAsync(userRoles);
  207. await _unitOfWork.CompleteAsync();
  208. _unitOfWork.CommitTran();
  209. try
  210. {
  211. var resultPassReset = await GetConfirmEmailURL(user.Id);
  212. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  213. {
  214. Subject = "Register Confirmation",
  215. To = input.Email,
  216. Body = "Please Set Your Password (this link will expired after 24 hours)"
  217. ,
  218. url = resultPassReset.Item1,
  219. userId = user.Id
  220. });
  221. if (!sendMailResult)
  222. {
  223. throw new AppException("User created, but could not send the email!");
  224. }
  225. }
  226. catch
  227. {
  228. throw new AppException("User created, but could not send the email!");
  229. }
  230. return input;
  231. }
  232. public async Task<bool> ConfirmEmail(ForgetPasswordDto input)
  233. {
  234. var user = await _userManager.FindByIdAsync(input.UserId);
  235. if (user == null)
  236. throw new AppException(ExceptionEnum.RecordNotExist);
  237. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  238. return result.Succeeded;
  239. }
  240. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  241. {
  242. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  243. if (user == null)
  244. throw new AppException(ExceptionEnum.RecordNotExist);
  245. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  246. var route = "auth/ConfirmEmail";
  247. var origin = _configuration.JwtSettings.Audience;
  248. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  249. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  250. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  251. return new Tuple<string, string>(passwordResetURL, user.Email);
  252. }
  253. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  254. {
  255. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  256. if (user == null)
  257. throw new AppException(ExceptionEnum.RecordNotExist);
  258. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  259. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  260. var route = "auth/ConfirmEmail";
  261. var origin = _configuration.JwtSettings.Audience;
  262. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  263. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  264. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  265. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  266. }
  267. public async Task<UserDto> Update(UserDto input)
  268. {
  269. try
  270. {
  271. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == input.Id);
  272. if (entity == null)
  273. throw new AppException(ExceptionEnum.RecordNotExist);
  274. MapperObject.Mapper.Map(input, entity);
  275. _unitOfWork.BeginTran();
  276. //saving user
  277. var result = await _userManager.UpdateAsync(entity);
  278. if (!result.Succeeded)
  279. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  280. //**saving userRoles
  281. //add new user roles
  282. var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  283. if (input.UserRoles == null)
  284. input.UserRoles = new List<UserRoleDto>();
  285. var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  286. newAddedRoles.ForEach(x => x.UserId = input.Id);
  287. await _userRole.AddRangeAsync(newAddedRoles);
  288. //delete removed roles
  289. var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  290. var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  291. await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  292. await _unitOfWork.CompleteAsync();
  293. _unitOfWork.CommitTran();
  294. }
  295. catch (Exception e)
  296. {
  297. throw e;
  298. }
  299. return input;
  300. }
  301. public Task<UserDto> UpdateWithoutChildren(UserDto input)
  302. {
  303. throw new NotImplementedException();
  304. }
  305. public async Task<bool> IsExpiredToken(ForgetPasswordDto input)
  306. {
  307. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  308. if (user == null)
  309. throw new AppException(ExceptionEnum.RecordNotExist);
  310. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  311. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  312. return !result;
  313. }
  314. public async Task<bool> ForgetPassword(ForgetPasswordDto model)
  315. {
  316. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == model.UserId);
  317. if (user == null)
  318. throw new AppException(ExceptionEnum.RecordNotExist);
  319. var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
  320. return result.Succeeded;
  321. }
  322. public async Task<bool> ResetPassword(ResetPasswordDto input)
  323. {
  324. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  325. if (user == null)
  326. throw new AppException(ExceptionEnum.RecordNotExist);
  327. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  328. throw new AppException(ExceptionEnum.WrongCredentials);
  329. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  330. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  331. if (!result.Succeeded)
  332. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  333. return true;
  334. }
  335. public async Task ForgetPasswordMail(string email)
  336. {
  337. var foundUser = await _userManager.FindByEmailAsync(email);
  338. if (foundUser != null)
  339. {
  340. var resultPassReset = await GetResetPasswordURL(foundUser.Id);
  341. await _emailSender.SendEmail(new EmailMessage
  342. {
  343. Subject = "Register Confirmation",
  344. To = resultPassReset.Item2,
  345. Body = "Forget Your Password, link will expired after 24 hours",
  346. url = resultPassReset.Item1,
  347. userId = foundUser.Id
  348. });
  349. }
  350. else
  351. {
  352. throw new AppException(ExceptionEnum.RecordNotExist);
  353. }
  354. }
  355. public async Task StopUser(string userId)
  356. {
  357. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  358. if (entity == null)
  359. throw new AppException(ExceptionEnum.RecordNotExist);
  360. if (!entity.IsStopped)
  361. {
  362. entity.IsStopped = true;
  363. await _unitOfWork.CompleteAsync();
  364. }
  365. }
  366. public async Task ActiveUser(string userId)
  367. {
  368. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  369. if (entity == null)
  370. throw new AppException(ExceptionEnum.RecordNotExist);
  371. entity.IsStopped = false;
  372. entity.AccessFailedCount = 0;
  373. entity.LockoutEnabled = false;
  374. entity.LockoutEnd = null;
  375. await _unitOfWork.CompleteAsync();
  376. }
  377. }
  378. }