UserService.cs 20 KB

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