UserService.cs 29 KB

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