AccountService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.WebUtilities;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Logging;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using WebApp.Common.Exceptions.ClientSide;
  8. using WebApp.Common.Exceptions.ServerSide;
  9. using WebApp.Common.Resources;
  10. using WebApp.Data;
  11. using WebApp.Data.Entities;
  12. using WebApp.Models.MappingExtensions;
  13. using WebApp.Models.Request.Accounts;
  14. using WebApp.Models.Response;
  15. using WebApp.Services.Interfaces;
  16. namespace WebApp.Services.Implementations;
  17. public class AccountService : IAccountService
  18. {
  19. private readonly ApplicationContext _applicationContext;
  20. private readonly UserManager<ApplicationUser> _userManager;
  21. private readonly SignInManager<ApplicationUser> _signInManager;
  22. private readonly IJwtTokenManager _jwtTokenManager;
  23. private readonly IEmailSenderService _emailSenderService;
  24. private readonly ILogger<AccountService> _logger;
  25. public AccountService(
  26. ApplicationContext applicationContext,
  27. UserManager<ApplicationUser> userManager,
  28. SignInManager<ApplicationUser> signInManager,
  29. IJwtTokenManager jwtTokenManager,
  30. IEmailSenderService emailSenderService,
  31. ILogger<AccountService> logger)
  32. {
  33. _applicationContext = applicationContext;
  34. _userManager = userManager;
  35. _signInManager = signInManager;
  36. _jwtTokenManager = jwtTokenManager;
  37. _emailSenderService = emailSenderService;
  38. _logger = logger;
  39. }
  40. public async Task<bool> RegistrationAsync(RegistrationRequestModel requestModel)
  41. {
  42. bool existsEmail = await _applicationContext.Users.AnyAsync(x => x.Email! == requestModel.Email);
  43. if (existsEmail)
  44. {
  45. _logger.LogError("Email already exists");
  46. throw new EmailAlreadyExistsException(Messages.EmailAlreadyExists);
  47. }
  48. bool existsUsername = await _applicationContext.Users.AnyAsync(x => x.NormalizedUserName == requestModel.UserName.ToUpper());
  49. if (existsUsername)
  50. {
  51. _logger.LogError("Username already exists");
  52. throw new EmailAlreadyExistsException(Messages.UserNameAlreadyExists);
  53. }
  54. ApplicationUser user = new()
  55. {
  56. UserName = requestModel.UserName,
  57. Email = requestModel.Email,
  58. };
  59. IdentityResult identityResult = await _userManager.CreateAsync(user, requestModel.Password);
  60. if (!identityResult.Succeeded)
  61. {
  62. IList<string> messages = identityResult.Errors.Select(x => x.Description).ToList();
  63. foreach (var errorMessage in messages)
  64. {
  65. _logger.LogError(errorMessage);
  66. }
  67. throw new NotSuccessfulRegistrationException(Messages.GeneralErrorMessage);
  68. }
  69. Uri confirmationUri = await GenerateEmailConfirmationUri(user);
  70. //await _emailSenderService.SendEmailConfirmationAsync(user.Email, confirmationUri.AbsoluteUri);
  71. _logger.LogInformation("Succeeded registration with email address: {email}", requestModel.Email);
  72. return identityResult.Succeeded;
  73. }
  74. public async Task<LoginResponseModel> LoginAsync(LoginRequestModel requestModel)
  75. {
  76. ApplicationUser? user = await _userManager.FindByEmailAsync(requestModel.Email);
  77. if (user is null)
  78. {
  79. _logger.LogError("Not found user with {email}", requestModel.Email);
  80. throw new InvalidCredentialsException(Messages.InvalidCredentials);
  81. }
  82. LoginResponseModel loginResponse = new();
  83. if (!user.EmailConfirmed)
  84. {
  85. loginResponse.IsConfirmedEmail = false;
  86. return loginResponse;
  87. }
  88. SignInResult signInResult = await _signInManager.CheckPasswordSignInAsync(user, requestModel.Password, lockoutOnFailure: false);
  89. if (!signInResult.Succeeded)
  90. {
  91. _logger.LogError("Invalid authentication attempt: Email {email}", requestModel.Email);
  92. throw new InvalidCredentialsException(Messages.InvalidCredentials);
  93. }
  94. string token = await _jwtTokenManager.GenerateJwtTokenAsync(user);
  95. loginResponse.AccsesToken = token;
  96. loginResponse.IsConfirmedEmail = true;
  97. loginResponse.RememberMe = requestModel.RememberMe;
  98. return loginResponse;
  99. }
  100. public async Task ConfirmEmailAsync(ConfirmEmailRequestModel requestModel)
  101. {
  102. ApplicationUser? user = await _userManager.FindByIdAsync(requestModel.Identifire);
  103. if (user is null)
  104. {
  105. _logger.LogError("Email confirmation request contains invalid user ID {userId}", requestModel.Identifire);
  106. throw new InvalidConfirmationException("Request contains invalid user");
  107. }
  108. if (user.EmailConfirmed)
  109. {
  110. return;
  111. }
  112. string confirmEmailToken = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(requestModel.Token));
  113. bool isValidToken = await _userManager
  114. .VerifyUserTokenAsync(user, _userManager.Options.Tokens.EmailConfirmationTokenProvider, "EmailConfirmation", confirmEmailToken);
  115. if (!isValidToken)
  116. {
  117. _logger.LogError("Email confirmation request contains invalid confirmation token");
  118. throw new InvalidConfirmationException("Request contains invalid token");
  119. }
  120. IdentityResult identityResult = await _userManager.ConfirmEmailAsync(user, confirmEmailToken);
  121. if (!identityResult.Succeeded)
  122. {
  123. IList<string> messages = identityResult.Errors.Select(x => x.Description).ToList();
  124. foreach (var errorMessage in messages)
  125. {
  126. _logger.LogError(errorMessage);
  127. }
  128. throw new InvalidConfirmationException("Not succeeded email confirmation");
  129. }
  130. }
  131. public async Task ResendEmailConfirmationAsync(string email)
  132. {
  133. ApplicationUser? user = await _userManager.FindByEmailAsync(email);
  134. if (user is null)
  135. {
  136. _logger.LogError("Not found user with Email: {email}", email);
  137. throw new NotFoundUserException(Messages.UserNotFound);
  138. }
  139. Uri confirmationUri = await GenerateEmailConfirmationUri(user);
  140. await _emailSenderService.SendEmailConfirmationAsync(email, confirmationUri.AbsoluteUri);
  141. }
  142. public async Task ResetPasswordAsync(ResetPasswordRequestModel requestModel)
  143. {
  144. ApplicationUser? user = await _userManager.FindByEmailAsync(requestModel.Email);
  145. if (user is null)
  146. {
  147. _logger.LogError("Not found user with {email}", requestModel.Email);
  148. throw new NotFoundUserException(Messages.UserNotFound);
  149. }
  150. Uri changePasswordUri = await GenerateResetPasswordUri(user);
  151. await _emailSenderService.SendChangePasswordAsync(user.Email!, changePasswordUri.AbsoluteUri);
  152. }
  153. public async Task ChangePasswordAsync(ChangePasswordRequestModel requestModel)
  154. {
  155. ApplicationUser? user = await _userManager.FindByIdAsync(requestModel.Identifire);
  156. if (user is null)
  157. {
  158. _logger.LogError("Reset password request contains invalid user ID {userId}", requestModel.Identifire);
  159. throw new InvalidConfirmationException("Request contains invalid user");
  160. }
  161. string resetPasswordToken = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(requestModel.Token));
  162. bool isValidToken = await _userManager
  163. .VerifyUserTokenAsync(user, _userManager.Options.Tokens.PasswordResetTokenProvider, "ResetPassword", resetPasswordToken);
  164. if (!isValidToken)
  165. {
  166. _logger.LogError("Reset password request contains invalid token");
  167. throw new InvalidConfirmationException("Request contains invalid token");
  168. }
  169. IdentityResult identityResult = await _userManager.ResetPasswordAsync(user, resetPasswordToken, requestModel.Password);
  170. if (!identityResult.Succeeded)
  171. {
  172. IList<string> messages = identityResult.Errors.Select(x => x.Description).ToList();
  173. foreach (var errorMessage in messages)
  174. {
  175. _logger.LogError(errorMessage);
  176. }
  177. throw new InvalidConfirmationException("Not succeeded reset password operation");
  178. }
  179. }
  180. public async Task<UserProfileResponseModel> GetProfileAsync(ClaimsPrincipal claimsPrincipal)
  181. {
  182. ApplicationUser? user = await _userManager.GetUserAsync(claimsPrincipal);
  183. if (user is null)
  184. {
  185. _logger.LogError("Not found user");
  186. throw new NotFoundUserException(Messages.UserNotFound);
  187. }
  188. UserProfileResponseModel profileResponse = user.ToUserProfileResponseModel();
  189. return profileResponse;
  190. }
  191. private async Task<Uri> GenerateEmailConfirmationUri(ApplicationUser user)
  192. {
  193. string token = await _jwtTokenManager.GenerateConfirmEmailTokenAsync(user);
  194. string baseUrl = "https://localhost:7061";
  195. Uri confirmationLink = new Uri($@"{baseUrl}/account/confirm-email?identifier={user.Id}&token={token}", new UriCreationOptions());
  196. return confirmationLink;
  197. }
  198. private async Task<Uri> GenerateResetPasswordUri(ApplicationUser user)
  199. {
  200. string resetPasswordToken = await _jwtTokenManager.GenerateForgetPasswordTokenAsync(user);
  201. string baseUrl = "https://localhost:7061";
  202. Uri changePasswordLink = new Uri($@"{baseUrl}/account/change-password?identifier={user.Id}&token={resetPasswordToken}", new UriCreationOptions());
  203. return changePasswordLink;
  204. }
  205. }