UserService.cs 32 KB

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