UserService.cs 23 KB

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