UserService.cs 27 KB

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