UserService.cs 28 KB

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