UserService.cs 30 KB

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