UserService.cs 26 KB

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