UserService.cs 30 KB

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