UserService.cs 20 KB

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