UserService.cs 19 KB

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