UserService.cs 32 KB

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