UserService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. namespace MTWorkHR.Application.Services
  22. {
  23. public class UserService : IUserService
  24. {
  25. private readonly RoleManager<ApplicationRole> _roleManager;
  26. private readonly ApplicationUserManager _userManager;
  27. private readonly IUnitOfWork _unitOfWork;
  28. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  29. private readonly AppSettingsConfiguration _configuration;
  30. private readonly IMailSender _emailSender;
  31. private readonly GlobalInfo _globalInfo;
  32. private readonly IFileService _fileService;
  33. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  34. , RoleManager<ApplicationRole> roleManager, GlobalInfo globalInfo, AppSettingsConfiguration configuration, IMailSender emailSender
  35. , IUserRoleRepository<IdentityUserRole<string>> userRole, IFileService fileService)
  36. {
  37. _userManager = userManager;
  38. _unitOfWork = unitOfWork;
  39. _roleManager = roleManager;
  40. _userRole = userRole;
  41. _configuration = configuration;
  42. _emailSender = emailSender;
  43. _globalInfo = globalInfo;
  44. _fileService = fileService;
  45. }
  46. public async Task<UserDto> GetById(string id)
  47. {
  48. var entity = await _userManager.Users
  49. .Include(x => x.UserRoles)
  50. .Include(x => x.UserAddress)
  51. .Include(x => x.UserAttachments)
  52. .FirstOrDefaultAsync(x => x.Id == id);
  53. var response = MapperObject.Mapper.Map<UserDto>(entity);
  54. return response;
  55. }
  56. //public async Task<List<UserDto>> GetAll(PagingInputDto pagingInput)
  57. //{
  58. // var employees = await _userManager.GetUsersInRoleAsync("Employee");
  59. // return employees.Select(e => new UserDto
  60. // {
  61. // Email = e.Email,
  62. // FirstName = e.FirstName,
  63. // LastName = e.LastName,
  64. // Id = e.Id
  65. // }).ToList();
  66. //}
  67. public virtual async Task<PagingResultDto<UserAllDto>> GetAll(UserPagingInputDto PagingInputDto)
  68. {
  69. var query = _userManager.Users
  70. .Include(u => u.Qualification).Include(u => u.JobTitle).Include(u => u.University).Include(u => u.Industry).Include(u => u.Country)
  71. .AsQueryable();
  72. if (PagingInputDto.Filter != null)
  73. {
  74. var filter = PagingInputDto.Filter;
  75. query = query.Where(u =>
  76. u.UserName.Contains(filter) ||
  77. u.Email.Contains(filter) ||
  78. u.FirstName.Contains(filter) ||
  79. u.LastName.Contains(filter) ||
  80. u.FavoriteName.Contains(filter) ||
  81. u.PhoneNumber.Contains(filter));
  82. }
  83. if (PagingInputDto.IndustryId != null)
  84. {
  85. query = query.Where(u => u.IndustryId == PagingInputDto.IndustryId);
  86. }
  87. if (PagingInputDto.QualificationId != null)
  88. {
  89. query = query.Where(u => u.QualificationId == PagingInputDto.QualificationId);
  90. }
  91. if (PagingInputDto.JobTitleId != null)
  92. {
  93. query = query.Where(u => u.JobTitleId == PagingInputDto.JobTitleId);
  94. }
  95. if (PagingInputDto.UniversityId != null)
  96. {
  97. query = query.Where(u => u.UniversityId == PagingInputDto.UniversityId);
  98. }
  99. if (PagingInputDto.CountryId != null)
  100. {
  101. query = query.Where(u => u.CountryId == PagingInputDto.CountryId);
  102. }
  103. var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);
  104. var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);
  105. var total = await query.CountAsync();
  106. var list = MapperObject.Mapper
  107. .Map<IList<UserAllDto>>(await page.ToListAsync());
  108. var response = new PagingResultDto<UserAllDto>
  109. {
  110. Result = list,
  111. Total = total
  112. };
  113. return response;
  114. }
  115. public async Task<List<UserDto>> GetAllEmployees()
  116. {
  117. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  118. return employees.Select(e => new UserDto
  119. {
  120. Email = e.Email,
  121. FirstName = e.FirstName,
  122. LastName = e.LastName,
  123. Id = e.Id
  124. }).ToList();
  125. }
  126. public async Task Delete(string id)
  127. {
  128. var user = await _userManager.FindByIdAsync(id);
  129. if (user != null)
  130. {
  131. user.IsDeleted = true;
  132. await _userManager.UpdateAsync(user);
  133. }
  134. }
  135. public async Task<UserDto> Create(UserDto input)
  136. {
  137. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  138. if (emailExists != null)
  139. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  140. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  141. if (phoneExists != null)
  142. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  143. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  144. if (userExists != null)
  145. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  146. //loop for given list of attachment, and move each file from Temp path to Actual path
  147. // _fileService.UploadFiles(files);
  148. if (!await _fileService.CopyFileToActualFolder(input.UserAttachments.ToList()))
  149. throw new AppException(ExceptionEnum.CouldNotMoveFiles);
  150. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  151. if(user.UserType == 0)
  152. {
  153. user.UserType = (int)UserTypeEnum.Employee;//default if not selected
  154. }
  155. _unitOfWork.BeginTran();
  156. //saving user
  157. var result = await _userManager.CreateAsync(user, input.Password);
  158. if (!result.Succeeded)
  159. throw new AppException(ExceptionEnum.RecordCreationFailed);
  160. input.Id = user.Id;
  161. //saving userRoles
  162. if(input.UserRoles == null || input.UserRoles.Count == 0)
  163. {
  164. var employeeRole = await _roleManager.FindByNameAsync("Employee");
  165. if (employeeRole == null)
  166. {
  167. await _userManager.AddToRoleAsync(user, "Employee");
  168. }
  169. }
  170. else
  171. {
  172. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  173. foreach (var role in userRoles)
  174. {
  175. role.UserId = user.Id;
  176. if (await _roleManager.FindByIdAsync(role.RoleId) == null)
  177. throw new AppException(ExceptionEnum.RecordNotExist);
  178. var roleOb = input.UserRoles?.FirstOrDefault(r => r.RoleId == role.RoleId);
  179. var roleName = roleOb != null ? roleOb.RoleName : "Employee";
  180. await _userManager.AddToRoleAsync(user, roleName);
  181. }
  182. }
  183. // await _userRole.AddRangeAsync(userRoles);
  184. await _unitOfWork.CompleteAsync();
  185. _unitOfWork.CommitTran();
  186. try
  187. {
  188. var resultPassReset = await GetConfirmEmailURL(user.Id);
  189. var sendMailResult = await _emailSender.SendEmail(new EmailMessage
  190. {
  191. Subject = "Register Confirmation",
  192. To = input.Email,
  193. Body = "Please Set Your Password (this link will expired after 24 hours)"
  194. ,
  195. url = resultPassReset.Item1,
  196. userId = user.Id
  197. });
  198. if (!sendMailResult)
  199. {
  200. throw new AppException("User created, but could not send the email!");
  201. }
  202. }
  203. catch
  204. {
  205. throw new AppException("User created, but could not send the email!");
  206. }
  207. return input;
  208. }
  209. public async Task<bool> ConfirmEmail(ForgetPasswordDto input)
  210. {
  211. var user = await _userManager.FindByIdAsync(input.UserId);
  212. if (user == null)
  213. throw new AppException(ExceptionEnum.RecordNotExist);
  214. var result = await _userManager.ConfirmEmailAsync(user, input.Token);
  215. return result.Succeeded;
  216. }
  217. private async Task<Tuple<string, string>> GetResetPasswordURL(string userId)
  218. {
  219. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  220. if (user == null)
  221. throw new AppException(ExceptionEnum.RecordNotExist);
  222. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  223. var route = "auth/ConfirmEmail";
  224. var origin = _configuration.JwtSettings.Audience;
  225. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  226. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  227. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  228. return new Tuple<string, string>(passwordResetURL, user.Email);
  229. }
  230. private async Task<Tuple<string, string>> GetConfirmEmailURL(string userId)
  231. {
  232. var user = await _userManager.Users.FirstOrDefaultAsync(x => !x.IsDeleted && x.Id.Equals(userId));
  233. if (user == null)
  234. throw new AppException(ExceptionEnum.RecordNotExist);
  235. string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  236. string codeHtmlVersion = HttpUtility.UrlEncode(token);
  237. var route = "auth/ConfirmEmail";
  238. var origin = _configuration.JwtSettings.Audience;
  239. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  240. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  241. var confirmEmailUrl = QueryHelpers.AddQueryString(userURL.ToString(), "token", codeHtmlVersion);
  242. return new Tuple<string, string>(confirmEmailUrl, user.Email);
  243. }
  244. public async Task<UserDto> Update(UserDto input)
  245. {
  246. try
  247. {
  248. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == input.Id);
  249. if (entity == null)
  250. throw new AppException(ExceptionEnum.RecordNotExist);
  251. MapperObject.Mapper.Map(input, entity);
  252. _unitOfWork.BeginTran();
  253. //saving user
  254. var result = await _userManager.UpdateAsync(entity);
  255. if (!result.Succeeded)
  256. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  257. //**saving userRoles
  258. //add new user roles
  259. var exsitedRolesIds = await _userRole.GetUserRoleIdsByUserID(input.Id);
  260. if (input.UserRoles == null)
  261. input.UserRoles = new List<UserRoleDto>();
  262. var newAddedRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles.Where(x => !exsitedRolesIds.Contains(x.RoleId)));
  263. newAddedRoles.ForEach(x => x.UserId = input.Id);
  264. await _userRole.AddRangeAsync(newAddedRoles);
  265. //delete removed roles
  266. var rolesIds = input.UserRoles.Select(x => x.RoleId).ToArray();
  267. var removedRoles = await _userRole.GetRemovedUserRoleIdsByUserID(input.Id, rolesIds);
  268. await _userRole.DeleteAsync(removedRoles.AsEnumerable());
  269. await _unitOfWork.CompleteAsync();
  270. _unitOfWork.CommitTran();
  271. }
  272. catch (Exception e)
  273. {
  274. throw e;
  275. }
  276. return input;
  277. }
  278. public Task<UserDto> UpdateWithoutChildren(UserDto input)
  279. {
  280. throw new NotImplementedException();
  281. }
  282. public async Task<bool> IsExpiredToken(ForgetPasswordDto input)
  283. {
  284. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == input.UserId);
  285. if (user == null)
  286. throw new AppException(ExceptionEnum.RecordNotExist);
  287. var purpose = UserManager<ApplicationUser>.ResetPasswordTokenPurpose;
  288. var result = await _userManager.VerifyUserTokenAsync(user, "Default", purpose, input.Token);
  289. return !result;
  290. }
  291. public async Task<bool> ForgetPassword(ForgetPasswordDto model)
  292. {
  293. var user = await _userManager.Users.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == model.UserId);
  294. if (user == null)
  295. throw new AppException(ExceptionEnum.RecordNotExist);
  296. var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
  297. return result.Succeeded;
  298. }
  299. public async Task<bool> ResetPassword(ResetPasswordDto input)
  300. {
  301. var user = await _userManager.FindByIdAsync(_globalInfo.UserId);
  302. if (user == null)
  303. throw new AppException(ExceptionEnum.RecordNotExist);
  304. if (!await _userManager.CheckPasswordAsync(user, input.OldPassword))
  305. throw new AppException(ExceptionEnum.WrongCredentials);
  306. var token = await _userManager.GeneratePasswordResetTokenAsync(user);
  307. var result = await _userManager.ResetPasswordAsync(user, token, input.NewPassword);
  308. if (!result.Succeeded)
  309. throw new AppException(ExceptionEnum.RecordUpdateFailed);
  310. return true;
  311. }
  312. public async Task ForgetPasswordMail(string userId)
  313. {
  314. var resultPassReset = await GetResetPasswordURL(userId);
  315. await _emailSender.SendEmail(new EmailMessage
  316. {
  317. Subject = "Register Confirmation",
  318. To = resultPassReset.Item2,
  319. Body = "Forget Your Password, link will expired after 24 hours",
  320. url = resultPassReset.Item1,
  321. userId = userId
  322. });
  323. }
  324. public async Task StopUser(string userId)
  325. {
  326. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  327. if (entity == null)
  328. throw new AppException(ExceptionEnum.RecordNotExist);
  329. if (!entity.IsStopped)
  330. {
  331. entity.IsStopped = true;
  332. await _unitOfWork.CompleteAsync();
  333. }
  334. }
  335. public async Task ActiveUser(string userId)
  336. {
  337. var entity = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == userId);
  338. if (entity == null)
  339. throw new AppException(ExceptionEnum.RecordNotExist);
  340. entity.IsStopped = false;
  341. entity.AccessFailedCount = 0;
  342. entity.LockoutEnabled = false;
  343. entity.LockoutEnd = null;
  344. await _unitOfWork.CompleteAsync();
  345. }
  346. }
  347. }