UserService.cs 26 KB

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