UserService.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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. using System.Linq;
  27. using System.ComponentModel.Design;
  28. using static iText.StyledXmlParser.Jsoup.Select.Evaluator;
  29. using static iText.IO.Util.IntHashtable;
  30. namespace MTWorkHR.Application.Services
  31. {
  32. public class UserService : IUserService
  33. {
  34. private readonly RoleManager<ApplicationRole> _roleManager;
  35. private readonly ApplicationUserManager _userManager;
  36. private readonly IUnitOfWork _unitOfWork;
  37. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  38. private readonly AppSettingsConfiguration _configuration;
  39. private readonly IMailSender _emailSender;
  40. private readonly GlobalInfo _globalInfo;
  41. private readonly IFileService _fileService;
  42. private readonly IOTPService _oTPService;
  43. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  44. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IMailSender emailSender
  45. , IUserRoleRepository<IdentityUserRole<string>> userRole, IFileService fileService, IOTPService oTPService)
  46. {
  47. _userManager = userManager;
  48. _unitOfWork = unitOfWork;
  49. _roleManager = roleManager;
  50. _userRole = userRole;
  51. _configuration = configuration;
  52. _emailSender = emailSender;
  53. _globalInfo = globalInfo;
  54. _fileService = fileService;
  55. _oTPService = oTPService;
  56. }
  57. public async Task<UserDto> GetById()
  58. {
  59. return await GetById(_globalInfo.UserId);
  60. }
  61. public async Task<UserDto> GetByEmail(string email)
  62. {
  63. var user = _userManager.Users.FirstOrDefault(x => x.Email == email);
  64. if(user == null)
  65. throw new AppException(ExceptionEnum.UserNotExist);
  66. return await GetById(user.Id);
  67. }
  68. public async Task<UserDto> GetById(string id)
  69. {
  70. var entity = await _userManager.Users
  71. .Include(x => x.UserRoles)
  72. .Include(x => x.UserAddress).ThenInclude(x=> x.City)
  73. .Include(x => x.UserAddress).ThenInclude(x=> x.Country)
  74. .Include(x => x.UserAttachments)
  75. .Include(x => x.JobTitle)
  76. .Include(x => x.Industry)
  77. .Include(x => x.University)
  78. .Include(x => x.Country)
  79. .Include(x => x.Qualification)
  80. .FirstOrDefaultAsync(x => x.Id == id);
  81. var response = MapperObject.Mapper.Map<UserDto>(entity);
  82. if (response.UserAttachments != null)
  83. foreach (var attach in response.UserAttachments.Where(a => a.Content != null))
  84. {
  85. //var stream = new MemoryStream(attach.Content);
  86. //IFormFile file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName);
  87. using (var stream = new MemoryStream(attach.Content))
  88. {
  89. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
  90. {
  91. Headers = new HeaderDictionary(),
  92. ContentType = attach.ContentType,
  93. };
  94. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  95. {
  96. FileName = file.FileName
  97. };
  98. file.ContentDisposition = cd.ToString();
  99. switch (attach.AttachmentTypeId)
  100. {
  101. case 1:
  102. response.CVAttach = file;
  103. break;
  104. case 2:
  105. response.PassportAttach = file;
  106. break;
  107. case 3:
  108. response.EduCertificateAttach = file;
  109. break;
  110. case 4:
  111. response.ExperienceCertificateAttach= file;
  112. break;
  113. case 5:
  114. response.ProfCertificateAttach = file;
  115. break;
  116. case 6:
  117. response.CommercialRegAttach = file;
  118. break;
  119. case 7:
  120. response.TaxDeclarationAttach = file;
  121. break;
  122. case 8:
  123. response.IdAttach = file;
  124. break;
  125. case 9:
  126. response.ProfileImage = file;
  127. response.ProfileImagePath = attach.FilePath;
  128. break;
  129. }
  130. attach.Content = new byte[0];
  131. }
  132. }
  133. var attendance = await _unitOfWork.Attendance.GetAttendanceByUserId(id, DateTime.Now.Date);
  134. response.IsCheckedIn = attendance != null && attendance.CheckInTime.HasValue;
  135. response.IsCheckedOut = attendance != null && attendance.CheckOutTime.HasValue;
  136. return response;
  137. }
  138. public async Task<EmployeeInfoDto> GetEmployeeInfo(string id)
  139. {
  140. var entity = await _userManager.Users
  141. .Include(x => x.UserRoles)
  142. .Include(x => x.UserAddress).ThenInclude(x => x.City)
  143. .Include(x => x.UserAddress).ThenInclude(x => x.Country)
  144. .Include(x => x.UserAttachments)
  145. .Include(x => x.JobTitle)
  146. .Include(x => x.Industry)
  147. .Include(x => x.University)
  148. .Include(x => x.Country)
  149. .Include(x => x.Qualification)
  150. .FirstOrDefaultAsync(x => x.Id == id);
  151. if(entity == null)
  152. {
  153. throw new AppException(ExceptionEnum.RecordNotExist);
  154. }
  155. var response = MapperObject.Mapper.Map<EmployeeInfoDto>(entity);
  156. if (entity.UserAttachments != null)
  157. foreach (var attach in entity.UserAttachments.Where(a => a.Content != null))
  158. {
  159. //var stream = new MemoryStream(attach.Content);
  160. //IFormFile file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FileName);
  161. using (var stream = new MemoryStream(attach.Content))
  162. {
  163. var file = new FormFile(stream, 0, stream.Length, Path.GetFileNameWithoutExtension(attach.FileName), attach.FilePath)
  164. {
  165. Headers = new HeaderDictionary(),
  166. ContentType = attach.ContentType,
  167. };
  168. System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
  169. {
  170. FileName = file.FileName
  171. };
  172. file.ContentDisposition = cd.ToString();
  173. switch (attach.AttachmentTypeId)
  174. {
  175. case 1:
  176. response.CVAttach = file;
  177. break;
  178. case 4:
  179. response.ExperienceCertificateAttach = file;
  180. break;
  181. case 5:
  182. response.ProfCertificateAttach = file;
  183. break;
  184. case 9:
  185. response.ProfileImage = file;
  186. response.ProfileImagePath = attach.FilePath;
  187. break;
  188. }
  189. attach.Content = new byte[0];
  190. }
  191. }
  192. return response;
  193. }
  194. public async Task<UserDto> GetUserById(string id)
  195. {
  196. var entity = await _userManager.Users
  197. .FirstOrDefaultAsync(x => x.Id == id);
  198. var response = MapperObject.Mapper.Map<UserDto>(entity);
  199. return response;
  200. }
  201. public async Task<string> GetUserFullName(string userId)
  202. {
  203. var entity = await GetUserById(userId);
  204. var name = entity == null ? "" : entity.FirstName + " " + entity.LastName;
  205. return name;
  206. }
  207. public async Task<UserDto> GetUserWithAttachmentById(string id)
  208. {
  209. var entity = await _userManager.Users.Include(u=> u.UserAttachments).Include(u=> u.JobTitle)
  210. .FirstOrDefaultAsync(x => x.Id == id);
  211. var response = MapperObject.Mapper.Map<UserDto>(entity);
  212. return response;
  213. }
  214. public async Task<List<UserDto>> GetUsersWithAttachmentsByIds(List<string> ids)
  215. {
  216. // Validate input
  217. if (ids == null || !ids.Any())
  218. {
  219. return new List<UserDto>();
  220. }
  221. // Query users with related data
  222. var users = await _userManager.Users
  223. .AsNoTracking() // Optional: Use if read-only data is sufficient
  224. .Include(u => u.UserAttachments)
  225. .Include(u => u.JobTitle)
  226. .Where(u => ids.Contains(u.Id))
  227. .ToListAsync();
  228. var response = MapperObject.Mapper.Map<List<UserDto>>(users);
  229. return response;
  230. }
  231. public async Task<string> GetProfileImage(string userId)
  232. {
  233. string imagePath = "";
  234. var user = await _userManager.Users.Include(u => u.UserAttachments)
  235. .FirstOrDefaultAsync(x => x.Id == userId);
  236. if (user != null)
  237. {
  238. var imageAtt = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
  239. imagePath = imageAtt != null ? imageAtt.FilePath : "";
  240. }
  241. return imagePath;
  242. }
  243. //public async Task<List<UserDto>> GetAll(PagingInputDto pagingInput)
  244. //{
  245. // var employees = await _userManager.GetUsersInRoleAsync("Employee");
  246. // return employees.Select(e => new UserDto
  247. // {
  248. // Email = e.Email,
  249. // FirstName = e.FirstName,
  250. // LastName = e.LastName,
  251. // Id = e.Id
  252. // }).ToList();
  253. //}
  254. public virtual async Task<PagingResultDto<UserAllDto>> GetAll(UserPagingInputDto PagingInputDto)
  255. {
  256. var companies = await _unitOfWork.Company.GetAllAsync();
  257. var query = _userManager.Users
  258. .Include(u => u.Qualification)
  259. .Include(u => u.JobTitle)
  260. .Include(u => u.University)
  261. .Include(u => u.Industry)
  262. .Include(u => u.Country)
  263. .Where(u => !u.IsDeleted && !u.IsStopped && ( _globalInfo.CompanyId == null || u.CompanyId != _globalInfo.CompanyId));
  264. var filter = PagingInputDto.Filter?.Trim();
  265. // Filtering by text fields and handling full name search
  266. if (!string.IsNullOrEmpty(filter))
  267. {
  268. var filters = filter.Split(" ");
  269. var firstNameFilter = filters[0];
  270. var lastNameFilter = filters.Length > 1 ? filters[1] : "";
  271. query = query.Where(u =>
  272. u.UserName.Contains(filter) || u.Email.Contains(filter) || u.FavoriteName.Contains(filter) ||
  273. u.Position.Contains(filter) || u.PhoneNumber.Contains(filter) ||
  274. u.FirstName.Contains(firstNameFilter) && (string.IsNullOrEmpty(lastNameFilter) || u.LastName.Contains(lastNameFilter)) ||
  275. u.LastName.Contains(lastNameFilter) && (string.IsNullOrEmpty(firstNameFilter) || u.FirstName.Contains(firstNameFilter))
  276. );
  277. }
  278. // Applying additional filters
  279. if (PagingInputDto.IndustryId?.Count > 0)
  280. query = query.Where(u => u.IndustryId.HasValue && PagingInputDto.IndustryId.Contains(u.IndustryId.Value));
  281. if (PagingInputDto.QualificationId.HasValue)
  282. query = query.Where(u => u.QualificationId == PagingInputDto.QualificationId);
  283. if (PagingInputDto.JobTitleId.HasValue)
  284. query = query.Where(u => u.JobTitleId == PagingInputDto.JobTitleId);
  285. if (PagingInputDto.UniversityId.HasValue)
  286. query = query.Where(u => u.UniversityId == PagingInputDto.UniversityId);
  287. if (PagingInputDto.CountryId?.Count > 0)
  288. query = query.Where(u => u.CountryId.HasValue && PagingInputDto.CountryId.Contains(u.CountryId.Value));
  289. if (PagingInputDto.UserTypeId?.Count > 0)
  290. query = query.Where(u => PagingInputDto.UserTypeId.Contains(u.UserType));
  291. if (PagingInputDto.Employed.HasValue)
  292. query = query.Where(u => PagingInputDto.Employed.Value ? u.CompanyId != null : u.CompanyId == null);
  293. // Ordering by specified field and direction
  294. var orderByField = !string.IsNullOrEmpty(PagingInputDto.OrderByField) ? PagingInputDto.OrderByField : "UserName";
  295. var orderByDirection = PagingInputDto.OrderType?.ToLower() == "desc" ? "desc" : "asc";
  296. query = query.OrderBy($"{orderByField} {orderByDirection}");
  297. // Pagination
  298. var total = await query.CountAsync();
  299. var result = await query
  300. .Skip((PagingInputDto.PageNumber - 1) * PagingInputDto.PageSize)
  301. .Take(PagingInputDto.PageSize)
  302. .ToListAsync();
  303. var list = MapperObject.Mapper.Map<IList<UserAllDto>>(result);
  304. var ss = list
  305. .Join(companies.Item1, // Join the list with companies.Item1
  306. u => u.CompanyId, // Key selector for User (CompanyId)
  307. c => c.Id, // Key selector for Company (Id)
  308. (u, c) => { // Project the join result
  309. u.CompanyName = c.CompanyName; // Assuming 'Name' is the CompanyName in Company entity
  310. return u; // Return the updated UserAllDto with CompanyName filled
  311. })
  312. .ToList();
  313. return new PagingResultDto<UserAllDto> { Result = list, Total = total };
  314. }
  315. public async Task<List<UserDto>> GetAllEmployees()
  316. {
  317. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  318. return employees.Select(e => new UserDto
  319. {
  320. Email = e.Email,
  321. FirstName = e.FirstName,
  322. LastName = e.LastName,
  323. Id = e.Id
  324. }).ToList();
  325. }
  326. public async Task<List<UserAllDto>> GetAllCompanyEmployees()
  327. {
  328. var AllEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  329. var AllContractors = await _userManager.GetUsersInRoleAsync("Contractor");
  330. var employees = AllEmployees.Where(e => e.CompanyId == _globalInfo.CompanyId).ToList();
  331. var contractors = AllContractors.Where(e => e.CompanyId == _globalInfo.CompanyId).ToList();
  332. var allUsers = employees.Union(contractors);
  333. var response = MapperObject.Mapper.Map<List<UserAllDto>>(allUsers);
  334. return response;
  335. }
  336. public async Task<bool> UnAssignCompanyEmployees(long companyId)
  337. {
  338. try
  339. {
  340. var AllEmployees = await _userManager.GetUsersInRoleAsync("Employee");
  341. var AllContractors = await _userManager.GetUsersInRoleAsync("Contractor");
  342. var employees = AllEmployees.Where(e => e.CompanyId == companyId).ToList();
  343. var contractors = AllContractors.Where(e => e.CompanyId == companyId).ToList();
  344. foreach (var emp in employees.Union(contractors))
  345. {
  346. emp.CompanyId = null;
  347. await _userManager.UpdateAsync(emp);
  348. }
  349. await _unitOfWork.CompleteAsync();
  350. return true;
  351. }
  352. catch(Exception ex)
  353. { return false; }
  354. }
  355. public async Task Delete(string id)
  356. {
  357. var user = await _userManager.FindByIdAsync(id);
  358. if (user == null)
  359. throw new AppException(ExceptionEnum.RecordNotExist);
  360. if (!user.IsDeleted )
  361. {
  362. user.IsDeleted = true;
  363. await _userManager.UpdateAsync(user);
  364. await _unitOfWork.CompleteAsync();
  365. }
  366. }
  367. public async Task Suspend(string id)
  368. {
  369. var user = await _userManager.FindByIdAsync(id);
  370. if (user == null)
  371. throw new AppException(ExceptionEnum.RecordNotExist);
  372. if (!user.IsStopped)
  373. {
  374. user.IsStopped = true;
  375. await _userManager.UpdateAsync(user);
  376. await _unitOfWork.CompleteAsync();
  377. }
  378. }
  379. public async Task ActiveUser(string userId)
  380. {
  381. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  382. if (entity == null)
  383. throw new AppException(ExceptionEnum.RecordNotExist);
  384. entity.IsStopped = false;
  385. entity.AccessFailedCount = 0;
  386. entity.LockoutEnabled = false;
  387. entity.LockoutEnd = null;
  388. await _userManager.UpdateAsync(entity);
  389. await _unitOfWork.CompleteAsync();
  390. }
  391. public async Task<UserDto> Create(UserDto input)
  392. {
  393. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  394. if (emailExists != null)
  395. throw new AppException(ExceptionEnum.RecordEmailAlreadyExist);
  396. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  397. if (phoneExists != null)
  398. throw new AppException(ExceptionEnum.RecordPhoneAlreadyExist);
  399. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  400. if (userExists != null)
  401. throw new AppException(ExceptionEnum.RecordNameAlreadyExist);
  402. //loop for given list of attachment, and move each file from Temp path to Actual path
  403. // _fileService.UploadFiles(files);
  404. input.CountryId = input.CountryId == null || input.CountryId == 0 ? input.UserAddress?.CountryId : input.CountryId;
  405. if (input.UserAttachments == null )
  406. input.UserAttachments = new List<AttachmentDto>();
  407. if (input.ProfileImage != null)
  408. {
  409. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  410. }
  411. if (input.CVAttach != null)
  412. {
  413. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name,FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  414. }
  415. if (input.PassportAttach != null)
  416. {
  417. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  418. }
  419. if (input.EduCertificateAttach != null)
  420. {
  421. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  422. }
  423. if (input.ExperienceCertificateAttach != null)
  424. {
  425. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  426. }
  427. if (input.ProfCertificateAttach != null)
  428. {
  429. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  430. }
  431. var files = input.UserAttachments.Select(a=> a.FileData).ToList();
  432. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  433. _fileService.CopyFileToCloud(ref attachs);
  434. //if (!res)
  435. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  436. input.UserAttachments = attachs;
  437. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  438. if(user.UserType == 0)
  439. {
  440. user.UserType = (int)UserTypeEnum.Employee;//default if not selected
  441. }
  442. _unitOfWork.BeginTran();
  443. user.CreateDate = DateTime.Now;
  444. //saving user
  445. var result = await _userManager.CreateAsync(user, input.Password);
  446. if (!result.Succeeded)
  447. {
  448. if(result.Errors != null && result.Errors.Count() > 0)
  449. {
  450. var msg = result.Errors.Select(a => a.Description ).Aggregate((a,b) => a + " /r/n " + b);
  451. throw new AppException(msg);
  452. }
  453. throw new AppException(ExceptionEnum.RecordCreationFailed);
  454. }
  455. input.Id = user.Id;
  456. //saving userRoles
  457. if(input.UserRoles == null || input.UserRoles.Count == 0)
  458. {
  459. if(user.UserType == (int)UserTypeEnum.Employee)
  460. {
  461. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  462. if (employeeRole != null)
  463. {
  464. await _userManager.AddToRoleAsync(user, "Employee");
  465. }
  466. }
  467. else if (user.UserType == (int)UserTypeEnum.Contractor)
  468. {
  469. var employeeRole = await _roleManager.FindByNameAsync("Contractor");
  470. if (employeeRole != null)
  471. {
  472. await _userManager.AddToRoleAsync(user, "Contractor");
  473. }
  474. }
  475. }
  476. else
  477. {
  478. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  479. foreach (var role in userRoles)
  480. {
  481. role.UserId = user.Id;
  482. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  483. throw new AppException(ExceptionEnum.RecordNotExist);
  484. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  485. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  486. await _userManager.AddToRoleAsync(user, roleName);
  487. }
  488. }
  489. // await _userRole.AddRangeAsync(userRoles);
  490. await _unitOfWork.CompleteAsync();
  491. _unitOfWork.CommitTran();
  492. try
  493. {
  494. var resultPassReset = await GetConfirmEmailURL(user.Id);
  495. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  496. {
  497. Subject = "Register Confirmation",
  498. To = input.Email,
  499. Body = "Please Set Your Password (this link will expired after 24 hours)"
  500. ,
  501. url = resultPassReset.Item1,
  502. userId = user.Id
  503. });
  504. if (!sendMailResult)
  505. {
  506. throw new AppException("User created, but could not send the email!");
  507. }
  508. }
  509. catch
  510. {
  511. throw new AppException("User created, but could not send the email!");
  512. }
  513. return input;
  514. }
  515. public async Task<BlobObject> Download(string filePath)
  516. {
  517. var file = await _fileService.Download(filePath);
  518. return file;
  519. }
  520. public async Task<bool> ConfirmEmail(ConfirmEmailDto input)
  521. {
  522. var user = await _userManager.FindByIdAsync(input.UserId);
  523. if (user == null)
  524. throw new AppException(ExceptionEnum.UserNotExist);
  525. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  526. return result.Succeeded;
  527. }
  528. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  529. {
  530. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  531. if (user == null)
  532. throw new AppException(ExceptionEnum.UserNotExist);
  533. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  534. var route = "auth/ConfirmEmail";
  535. var origin = _configuration.JwtSettings.Audience;
  536. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  537. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  538. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  539. return new Tuple<string, string>(passwordResetURL, user.Email);
  540. }
  541. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  542. {
  543. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  544. if (user == null)
  545. throw new AppException(ExceptionEnum.UserNotExist);
  546. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  547. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  548. var route = "auth/ConfirmEmail";
  549. var origin = _configuration.JwtSettings.Audience;
  550. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  551. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  552. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  553. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  554. }
  555. public async Task<UserUpdateDto> Update(UserUpdateDto input)
  556. {
  557. try
  558. {
  559. var entity = _userManager.Users.Include(x => x.UserAttachments).FirstOrDefault(x=> x.Id == input.Id);
  560. if (entity == null)
  561. throw new AppException(ExceptionEnum.UserNotExist);
  562. if (input.UserAttachments == null)
  563. input.UserAttachments = new List<AttachmentDto>();
  564. var oldAttachList = entity.UserAttachments;
  565. if (input.ProfileImage != null)
  566. {
  567. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 9 || x.OriginalName == input.ProfileImage?.Name).FirstOrDefault();
  568. if(oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  569. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfileImage, OriginalName = input.ProfileImage?.Name, FileName = input.ProfileImage?.FileName, AttachmentTypeId = 9 });
  570. }
  571. if (input.CVAttach != null)
  572. {
  573. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 1 || x.OriginalName == input.CVAttach?.Name).FirstOrDefault();
  574. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  575. input.UserAttachments.Add(new AttachmentDto { FileData = input.CVAttach, OriginalName = input.CVAttach?.Name, FileName = input.CVAttach?.FileName, AttachmentTypeId = 1 });
  576. }
  577. if (input.PassportAttach != null)
  578. {
  579. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 2 || x.OriginalName == input.PassportAttach?.Name).FirstOrDefault();
  580. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  581. input.UserAttachments.Add(new AttachmentDto { FileData = input.PassportAttach, OriginalName = input.PassportAttach?.Name, FileName = input.PassportAttach?.FileName, AttachmentTypeId = 2 });
  582. }
  583. if (input.EduCertificateAttach != null)
  584. {
  585. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 3 || x.OriginalName == input.EduCertificateAttach?.Name).FirstOrDefault();
  586. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  587. input.UserAttachments.Add(new AttachmentDto { FileData = input.EduCertificateAttach, OriginalName = input.EduCertificateAttach?.Name, FileName = input.EduCertificateAttach?.FileName, AttachmentTypeId = 3 });
  588. }
  589. if (input.ExperienceCertificateAttach != null)
  590. {
  591. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 4 || x.OriginalName == input.ExperienceCertificateAttach?.Name).FirstOrDefault();
  592. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  593. input.UserAttachments.Add(new AttachmentDto { FileData = input.ExperienceCertificateAttach, OriginalName = input.ExperienceCertificateAttach?.Name, FileName = input.ExperienceCertificateAttach?.FileName, AttachmentTypeId = 4 });
  594. }
  595. if (input.ProfCertificateAttach != null)
  596. {
  597. var oldAttach = oldAttachList.Where(x => x.AttachmentTypeId == 5 || x.OriginalName == input.ProfCertificateAttach?.Name).FirstOrDefault();
  598. if (oldAttach != null) entity.UserAttachments.Remove(oldAttach);
  599. input.UserAttachments.Add(new AttachmentDto { FileData = input.ProfCertificateAttach, OriginalName = input.ProfCertificateAttach?.Name, FileName = input.ProfCertificateAttach?.FileName, AttachmentTypeId = 5 });
  600. }
  601. List<AttachmentDto> attachs = input.UserAttachments.ToList();
  602. _fileService.CopyFileToCloud(ref attachs);
  603. input.UserAttachments = attachs;
  604. //if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  605. // throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  606. MapperObject.Mapper.Map(input, entity);
  607. _unitOfWork.BeginTran();
  608. entity.UpdateDate = DateTime.Now;
  609. //saving user
  610. var result = await _userManager.UpdateAsync(entity);
  611. if (!result.Succeeded)
  612. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  613. //**saving userRoles
  614. //add new user roles
  615. //var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  616. //if (input.UserRoles == null)
  617. // input.UserRoles = new List<UserRoleDto>();
  618. //var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  619. //newAddedRoles.ForEach(x => x.UserId = input.Id);
  620. //await _userRole.AddRangeAsync(newAddedRoles);
  621. ////delete removed roles
  622. //var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  623. //var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  624. //await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  625. await _unitOfWork.CompleteAsync();
  626. _unitOfWork.CommitTran();
  627. }
  628. catch (Exception e)
  629. {
  630. throw e;
  631. }
  632. var userResponse = await GetById(input.Id);
  633. var user = MapperObject.Mapper.Map<UserUpdateDto>(userResponse);
  634. return user;
  635. }
  636. public async Task<bool> Update(string userId, long companyId)
  637. {
  638. try
  639. {
  640. var entity = _userManager.Users.FirstOrDefault(x => x.Id == userId);
  641. if (entity == null)
  642. throw new AppException(ExceptionEnum.UserNotExist);
  643. entity.CompanyId = companyId;
  644. entity.UpdateDate = DateTime.Now;
  645. //saving user
  646. var result = await _userManager.UpdateAsync(entity);
  647. if (!result.Succeeded)
  648. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  649. await _unitOfWork.CompleteAsync();
  650. return true;
  651. }
  652. catch (Exception e)
  653. {
  654. throw e;
  655. }
  656. }
  657. public async Task<bool> IsExpiredToken(ConfirmEmailDto input)
  658. {
  659. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  660. if (user == null)
  661. throw new AppException(ExceptionEnum.UserNotExist);
  662. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  663. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  664. return !result;
  665. }
  666. public async Task<bool> ResetPassword(ResetPasswordDto input)
  667. {
  668. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  669. if (user == null)
  670. throw new AppException(ExceptionEnum.UserNotExist);
  671. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  672. throw new AppException(ExceptionEnum.WrongCredentials);
  673. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  674. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  675. if (!result.Succeeded)
  676. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  677. return true;
  678. }
  679. public async Task<ForgetPasswordResponseDto> ForgetPasswordMail(string email) //Begin forget password
  680. {
  681. var foundUser = await _userManager.FindByEmailAsync(email);
  682. if (foundUser != null)
  683. {
  684. string oneTimePassword = await _oTPService.RandomOneTimePassword(foundUser.Id);
  685. await _oTPService.SentOTPByMail(foundUser.Id, foundUser.Email, oneTimePassword);
  686. ForgetPasswordResponseDto res = new ForgetPasswordResponseDto { UserId = foundUser.Id};
  687. return res;
  688. }
  689. else
  690. {
  691. throw new AppException(ExceptionEnum.UserNotExist);
  692. }
  693. }
  694. public async Task<bool> VerifyOTP(VerifyOTPDto input)
  695. {
  696. if (! await _oTPService.VerifyOTP(input.UserId, input.OTP))
  697. throw new AppException(ExceptionEnum.WrongOTP);
  698. return true;
  699. }
  700. public async Task<bool> ForgetPassword(ForgetPasswordDto input)
  701. {
  702. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  703. if (user == null)
  704. throw new AppException(ExceptionEnum.UserNotExist);
  705. string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
  706. var result = await _userManager.ResetPasswordAsync(user, resetToken, input.Password);
  707. if (!result.Succeeded)
  708. {
  709. if (result.Errors != null && result.Errors.Count() > 0)
  710. {
  711. var msg = result.Errors.Select(a => a.Description).Aggregate((a, b) => a + " /r/n " + b);
  712. throw new AppException(msg);
  713. }
  714. throw new AppException(ExceptionEnum.RecordCreationFailed);
  715. }
  716. return result.Succeeded;
  717. }
  718. public async Task StopUser(string userId)
  719. {
  720. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  721. if (entity == null)
  722. throw new AppException(ExceptionEnum.UserNotExist);
  723. if (!entity.IsStopped)
  724. {
  725. entity.IsStopped = true;
  726. await _unitOfWork.CompleteAsync();
  727. }
  728. }
  729. }
  730. }