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. user.CreateDate = DateTime.Now;
  298. //saving user
  299. var result = await _userManager.CreateAsync(user, input.Password);
  300. if (!result.Succeeded)
  301. {
  302. if(result.Errors != null && result.Errors.Count() > 0)
  303. {
  304. var msg = result.Errors.Select(a => a.Description ).Aggregate((a,b) => a + " /r/n " + b);
  305. throw new AppException(msg);
  306. }
  307. throw new AppException(ExceptionEnum.RecordCreationFailed);
  308. }
  309. input.Id = user.Id;
  310. //saving userRoles
  311. if(input.UserRoles == null || input.UserRoles.Count == 0)
  312. {
  313. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  314. if (employeeRole != null)
  315. {
  316. await _userManager.AddToRoleAsync(user, "Employee");
  317. }
  318. }
  319. else
  320. {
  321. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  322. foreach (var role in userRoles)
  323. {
  324. role.UserId = user.Id;
  325. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  326. throw new AppException(ExceptionEnum.RecordNotExist);
  327. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  328. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  329. await _userManager.AddToRoleAsync(user, roleName);
  330. }
  331. }
  332. // await _userRole.AddRangeAsync(userRoles);
  333. await _unitOfWork.CompleteAsync();
  334. _unitOfWork.CommitTran();
  335. try
  336. {
  337. var resultPassReset = await GetConfirmEmailURL(user.Id);
  338. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  339. {
  340. Subject = "Register Confirmation",
  341. To = input.Email,
  342. Body = "Please Set Your Password (this link will expired after 24 hours)"
  343. ,
  344. url = resultPassReset.Item1,
  345. userId = user.Id
  346. });
  347. if (!sendMailResult)
  348. {
  349. throw new AppException("User created, but could not send the email!");
  350. }
  351. }
  352. catch
  353. {
  354. throw new AppException("User created, but could not send the email!");
  355. }
  356. return input;
  357. }
  358. public async Task<BlobObject> Download(string filePath)
  359. {
  360. var file = await _fileService.Download(filePath);
  361. return file;
  362. }
  363. public async Task<bool> ConfirmEmail(ConfirmEmailDto input)
  364. {
  365. var user = await _userManager.FindByIdAsync(input.UserId);
  366. if (user == null)
  367. throw new AppException(ExceptionEnum.UserNotExist);
  368. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  369. return result.Succeeded;
  370. }
  371. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  372. {
  373. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  374. if (user == null)
  375. throw new AppException(ExceptionEnum.UserNotExist);
  376. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  377. var route = "auth/ConfirmEmail";
  378. var origin = _configuration.JwtSettings.Audience;
  379. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  380. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  381. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  382. return new Tuple<string, string>(passwordResetURL, user.Email);
  383. }
  384. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  385. {
  386. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  387. if (user == null)
  388. throw new AppException(ExceptionEnum.UserNotExist);
  389. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  390. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  391. var route = "auth/ConfirmEmail";
  392. var origin = _configuration.JwtSettings.Audience;
  393. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  394. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  395. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  396. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  397. }
  398. public async Task<UserUpdateDto> Update(UserUpdateDto input)
  399. {
  400. try
  401. {
  402. var entity = _userManager.Users.Include(x => x.UserAttachments).FirstOrDefault(x=> x.Id == input.Id);
  403. if (entity == null)
  404. throw new AppException(ExceptionEnum.UserNotExist);
  405. if (input.UserAttachments == null)
  406. input.UserAttachments = new List<AttachmentDto>();
  407. var oldAttachList = entity.UserAttachments;
  408. if (input.ProfileImage != null)
  409. {
  410. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 9 || x.OriginalName == input.ProfileImage?.Name).FirstOrDefault();
  411. if(oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  412. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  413. }
  414. if (input.CVAttach != null)
  415. {
  416. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 1 || x.OriginalName == input.CVAttach?.Name).FirstOrDefault();
  417. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  418. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name, FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  419. }
  420. if (input.PassportAttach != null)
  421. {
  422. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 2 || x.OriginalName == input.PassportAttach?.Name).FirstOrDefault();
  423. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  424. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  425. }
  426. if (input.EduCertificateAttach != null)
  427. {
  428. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 3 || x.OriginalName == input.EduCertificateAttach?.Name).FirstOrDefault();
  429. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  430. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  431. }
  432. if (input.ExperienceCertificateAttach != null)
  433. {
  434. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 4 || x.OriginalName == input.ExperienceCertificateAttach?.Name).FirstOrDefault();
  435. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  436. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  437. }
  438. if (input.ProfCertificateAttach != null)
  439. {
  440. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 5 || x.OriginalName == input.ProfCertificateAttach?.Name).FirstOrDefault();
  441. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  442. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  443. }
  444. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  445. _fileService.CopyFileToCloud(ref attachs);
  446. input.UserAttachments = attachs;
  447. //if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  448. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  449. MapperObject.Mapper.Map(input, entity);
  450. _unitOfWork.BeginTran();
  451. entity.UpdateDate = DateTime.Now;
  452. //saving user
  453. var result = await _userManager.UpdateAsync(entity);
  454. if (!result.Succeeded)
  455. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  456. //**saving userRoles
  457. //add new user roles
  458. //var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  459. //if (input.UserRoles == null)
  460. // input.UserRoles = new List<UserRoleDto>();
  461. //var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  462. //newAddedRoles.ForEach(x => x.UserId = input.Id);
  463. //await _userRole.AddRangeAsync(newAddedRoles);
  464. ////delete removed roles
  465. //var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  466. //var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  467. //await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  468. await _unitOfWork.CompleteAsync();
  469. _unitOfWork.CommitTran();
  470. }
  471. catch (Exception e)
  472. {
  473. throw e;
  474. }
  475. var userResponse = await GetById(input.Id);
  476. var user = MapperObject.Mapper.Map<UserUpdateDto>(userResponse);
  477. return user;
  478. }
  479. public async Task<bool> IsExpiredToken(ConfirmEmailDto input)
  480. {
  481. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  482. if (user == null)
  483. throw new AppException(ExceptionEnum.UserNotExist);
  484. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  485. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  486. return !result;
  487. }
  488. public async Task<bool> ResetPassword(ResetPasswordDto input)
  489. {
  490. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  491. if (user == null)
  492. throw new AppException(ExceptionEnum.UserNotExist);
  493. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  494. throw new AppException(ExceptionEnum.WrongCredentials);
  495. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  496. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  497. if (!result.Succeeded)
  498. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  499. return true;
  500. }
  501. public async Task<ForgetPasswordResponseDto> ForgetPasswordMail(string email) //Begin forget password
  502. {
  503. var foundUser = await _userManager.FindByEmailAsync(email);
  504. if (foundUser != null)
  505. {
  506. string oneTimePassword = await _oTPService.RandomOneTimePassword(foundUser.Id);
  507. await _oTPService.SentOTPByMail(foundUser.Id, foundUser.Email, oneTimePassword);
  508. ForgetPasswordResponseDto res = new ForgetPasswordResponseDto { UserId = foundUser.Id};
  509. return res;
  510. }
  511. else
  512. {
  513. throw new AppException(ExceptionEnum.UserNotExist);
  514. }
  515. }
  516. public async Task<bool> VerifyOTP(VerifyOTPDto input)
  517. {
  518. if (! await _oTPService.VerifyOTP(input.UserId, input.OTP))
  519. throw new AppException(ExceptionEnum.WrongOTP);
  520. return true;
  521. }
  522. public async Task<bool> ForgetPassword(ForgetPasswordDto input)
  523. {
  524. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  525. if (user == null)
  526. throw new AppException(ExceptionEnum.UserNotExist);
  527. string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
  528. var result = await _userManager.ResetPasswordAsync(user, resetToken, input.Password);
  529. if (!result.Succeeded)
  530. {
  531. if (result.Errors != null && result.Errors.Count() > 0)
  532. {
  533. var msg = result.Errors.Select(a => a.Description).Aggregate((a, b) => a + " /r/n " + b);
  534. throw new AppException(msg);
  535. }
  536. throw new AppException(ExceptionEnum.RecordCreationFailed);
  537. }
  538. return result.Succeeded;
  539. }
  540. public async Task StopUser(string userId)
  541. {
  542. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  543. if (entity == null)
  544. throw new AppException(ExceptionEnum.UserNotExist);
  545. if (!entity.IsStopped)
  546. {
  547. entity.IsStopped = true;
  548. await _unitOfWork.CompleteAsync();
  549. }
  550. }
  551. public async Task ActiveUser(string userId)
  552. {
  553. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  554. if (entity == null)
  555. throw new AppException(ExceptionEnum.UserNotExist);
  556. entity.IsStopped = false;
  557. entity.AccessFailedCount = 0;
  558. entity.LockoutEnabled = false;
  559. entity.LockoutEnd = null;
  560. await _unitOfWork.CompleteAsync();
  561. }
  562. }
  563. }