UserService.cs 30 KB

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