UserService.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.MappingProfiles;
  7. using MTWorkHR.Application.Models;
  8. using MTWorkHR.Application.Services;
  9. using MTWorkHR.Application.Models.Email;
  10. using MTWorkHR.Core.Global;
  11. using MTWorkHR.Core.IRepositories;
  12. using MTWorkHR.Core.UnitOfWork;
  13. using MTWorkHR.Identity.Models;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using MTWorkHR.Core;
  20. namespace MTWorkHR.Identity.Services
  21. {
  22. public class UserService : IUserService
  23. {
  24. private readonly RoleManager<ApplicationRole> _roleManager;
  25. private readonly ApplicationUserManager _userManager;
  26. private readonly IUnitOfWork _unitOfWork;
  27. private readonly IUserRoleRepository<IdentityUserRole<string>> _userRole;
  28. private readonly AppSettingsConfiguration _configuration;
  29. private readonly IEmailSender _emailSender;
  30. public UserService(ApplicationUserManager userManager, IUnitOfWork unitOfWork
  31. , RoleManager<ApplicationRole> roleManager, AppSettingsConfiguration configuration, IEmailSender emailSender
  32. , IUserRoleRepository<IdentityUserRole<string>> userRole)
  33. {
  34. _userManager = userManager;
  35. _unitOfWork = unitOfWork;
  36. _roleManager = roleManager;
  37. _userRole = userRole;
  38. _configuration = configuration;
  39. _emailSender = emailSender;
  40. }
  41. public async Task<UserDto> GetById(string userId)
  42. {
  43. var employee = await _userManager.FindByIdAsync(userId);
  44. return new UserDto
  45. {
  46. Email = employee.Email,
  47. FirstName = employee.FirstName,
  48. LastName = employee.LastName,
  49. Id = employee.Id
  50. };
  51. }
  52. public async Task<List<UserDto>> GetAll()
  53. {
  54. var employees = await _userManager.GetUsersInRoleAsync("Employee");
  55. return employees.Select( e=> new UserDto
  56. {
  57. Email = e.Email,
  58. FirstName = e.FirstName,
  59. LastName = e.LastName,
  60. Id = e.Id
  61. }).ToList();
  62. }
  63. public async Task Delete(string id)
  64. {
  65. var user = await _userManager.FindByIdAsync(id);
  66. if (user != null)
  67. {
  68. user.IsDeleted = true;
  69. await _userManager.UpdateAsync(user);
  70. }
  71. }
  72. public async Task<UserDto> Create(UserDto input)
  73. {
  74. var emailExists = await _userManager.FindByEmailAsync(input.Email);
  75. if (emailExists != null)
  76. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  77. var phoneExists = await _userManager.FindByAnyAsync(input.PhoneNumber);
  78. if (phoneExists != null)
  79. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  80. var userExists = await _userManager.FindByAnyAsync(input.UserName);
  81. if (userExists != null)
  82. throw new AppException(ExceptionEnum.RecordAlreadyExist);
  83. var user = MapperObject.Mapper.Map<ApplicationUser>(input);
  84. _unitOfWork.BeginTran();
  85. //saving user
  86. var result = await _userManager.CreateAsync(user);
  87. if (!result.Succeeded)
  88. throw new AppException(ExceptionEnum.RecordCreationFailed);
  89. input.Id = user.Id;
  90. //saving userRoles
  91. var userRoles = MapperObject.Mapper.Map<List<IdentityUserRole<string>>>(input.UserRoles);
  92. foreach (var role in userRoles)
  93. {
  94. role.UserId = user.Id;
  95. if ((await _roleManager.FindByIdAsync(role.RoleId)) == null)
  96. throw new AppException(ExceptionEnum.RecordNotExist);
  97. }
  98. await _userRole.AddRangeAsync(userRoles);
  99. await _unitOfWork.CompleteAsync();
  100. _unitOfWork.CommitTran();
  101. try
  102. {
  103. string url = await GetResetPasswordURL(user.Id);
  104. var sendMailResult = await _emailSender.SendEmail(new EmailMessage {
  105. Subject = "Register Confirmation",
  106. To = input.Email,
  107. Body = "Please Set Your Password (this link will expired after 24 hours)"
  108. , url = url, userId = user.Id } );
  109. if (!sendMailResult)
  110. {
  111. throw new AppException("User created, but could not send the email!");
  112. }
  113. }
  114. catch
  115. {
  116. throw new AppException("User created, but could not send the email!");
  117. }
  118. return input;
  119. }
  120. private async Task<string> GetResetPasswordURL(string userId)
  121. {
  122. var user = await _userManager.Users.FirstOrDefaultAsync(x => (!x.IsDeleted) && x.Id.Equals(userId));
  123. if (user == null)
  124. throw new AppException(ExceptionEnum.RecordNotExist);
  125. string code = await _userManager.GeneratePasswordResetTokenAsync(user);
  126. var route = "login/forgetpassword";
  127. var origin = _configuration.JwtSettings.Audience;
  128. var endpointUri = new Uri(string.Concat($"{origin}/", route));
  129. var userURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
  130. var passwordResetURL = QueryHelpers.AddQueryString(userURL.ToString(), "token", code);
  131. return passwordResetURL;
  132. }
  133. public Task<UserDto> Update(UserDto input)
  134. {
  135. throw new NotImplementedException();
  136. }
  137. public Task<UserDto> UpdateWithoutChildren(UserDto input)
  138. {
  139. throw new NotImplementedException();
  140. }
  141. public Task ForgetPassword(string input)
  142. {
  143. throw new NotImplementedException();
  144. }
  145. public Task<bool> ConfirmForgetPassword(ForgetPasswordDto input)
  146. {
  147. throw new NotImplementedException();
  148. }
  149. public Task<bool> ResetPassword(ResetPasswordDto input)
  150. {
  151. throw new NotImplementedException();
  152. }
  153. }
  154. }