From 128e68f63f9f160edd04cd5f46b30959a5fbe16b Mon Sep 17 00:00:00 2001 From: Jonathan Bourdon Date: Thu, 20 Jun 2024 13:44:45 -0400 Subject: [PATCH] Just cleanup --- .../Queries/GetCurrentUser/GetCurrentUser.cs | 8 +-- src/Infrastructure/Utils/GenerateJwtToken.cs | 14 ++--- src/Web/Controllers/FacebookController.cs | 44 ++++++++------- src/Web/Controllers/GoogleController.cs | 56 ++++++++++--------- 4 files changed, 63 insertions(+), 59 deletions(-) diff --git a/src/Application/Users/Queries/GetCurrentUser/GetCurrentUser.cs b/src/Application/Users/Queries/GetCurrentUser/GetCurrentUser.cs index 49f1152..7cbabd6 100644 --- a/src/Application/Users/Queries/GetCurrentUser/GetCurrentUser.cs +++ b/src/Application/Users/Queries/GetCurrentUser/GetCurrentUser.cs @@ -8,14 +8,14 @@ public class GetCurrentUserQueryHandler( IApplicationDbContext context, IMapper mapper, IIdentityService identityService - ) +) : IRequestHandler { public async Task Handle(GetCurrentUserQuery request, CancellationToken cancellationToken) { var identityUser = await identityService.GetCurrentUserAsync(); - var currentUserId = new Guid(identityUser?.Id ?? ""); - + var currentUserId = Guid.Parse(identityUser!.Id!); + var transactions = await context.UserTransactions .Where(x => x.ApplicationUserId == currentUserId.ToString()) .OrderBy(x => x.LastModified) @@ -30,7 +30,7 @@ public class GetCurrentUserQueryHandler( Id = currentUserId, FirstName = identityUser?.FirstName ?? "", LastName = identityUser?.LastName ?? "", - UserName =identityUser?.UserName ?? "", + UserName = identityUser?.UserName ?? "", UserTransactions = transactions, TotalBalance = transactions.Sum(x => x.Amount), UserRoles = roles diff --git a/src/Infrastructure/Utils/GenerateJwtToken.cs b/src/Infrastructure/Utils/GenerateJwtToken.cs index 9f01d6a..00423f9 100644 --- a/src/Infrastructure/Utils/GenerateJwtToken.cs +++ b/src/Infrastructure/Utils/GenerateJwtToken.cs @@ -9,20 +9,18 @@ public static class JwtTokenHelper { public static string GenerateJwtToken(string issuer, string audience, string key, string userId) { - var claims = new[] - { - new Claim(JwtRegisteredClaimNames.Sub, userId), - new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.NameIdentifier, userId) - }; - var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: issuer, audience: audience, - claims: claims, + claims: new[] + { + new Claim(JwtRegisteredClaimNames.Sub, userId), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.NameIdentifier, userId) + }, expires: DateTime.Now.AddMinutes(30), signingCredentials: credentials); diff --git a/src/Web/Controllers/FacebookController.cs b/src/Web/Controllers/FacebookController.cs index 679502e..3178b5f 100644 --- a/src/Web/Controllers/FacebookController.cs +++ b/src/Web/Controllers/FacebookController.cs @@ -13,41 +13,45 @@ public class FacebookController(IIdentityService identityService) : Controller [HttpGet("/api/facebook/sign-in")] public async Task SignIn() { - await HttpContext.ChallengeAsync(FacebookDefaults.AuthenticationScheme, new AuthenticationProperties - { - RedirectUri = Url.Action("Authorize") - }); + await HttpContext.ChallengeAsync(FacebookDefaults.AuthenticationScheme, + new AuthenticationProperties { RedirectUri = Url.Action("Authorize") }); } public async Task Authorize() { var authenticateResult = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme); - + if (!authenticateResult.Succeeded) return BadRequest(); - + var claims = authenticateResult.Principal.Claims.ToList(); - + var name = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? ""; var email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value ?? ""; var givenName = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value ?? ""; var familyName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value ?? ""; - - var claimsIdentity = new ClaimsIdentity(new List - { - new(ClaimTypes.Name, name), - new(ClaimTypes.Email, email), - new(ClaimTypes.GivenName, givenName), - new(ClaimTypes.Surname, familyName) - }, CookieAuthenticationDefaults.AuthenticationScheme); - + + var claimsIdentity = new ClaimsIdentity( + new List + { + new(ClaimTypes.Name, name), + new(ClaimTypes.Email, email), + new(ClaimTypes.GivenName, givenName), + new(ClaimTypes.Surname, familyName) + }, + CookieAuthenticationDefaults.AuthenticationScheme); + if (await identityService.FindUserByEmailAsync(email) != null) { - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); + await HttpContext.SignInAsync( + CookieAuthenticationDefaults.AuthenticationScheme, + new ClaimsPrincipal(claimsIdentity)); return Redirect("/"); } - - await identityService.CreateUserAsync(email, givenName, givenName, familyName, RandomGenerator.RandomString(24)); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); + + await identityService.CreateUserAsync(email, givenName, givenName, familyName, + RandomGenerator.RandomString(24)); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, + new ClaimsPrincipal(claimsIdentity)); return Redirect("/"); } } diff --git a/src/Web/Controllers/GoogleController.cs b/src/Web/Controllers/GoogleController.cs index 6df233a..40e8adc 100644 --- a/src/Web/Controllers/GoogleController.cs +++ b/src/Web/Controllers/GoogleController.cs @@ -13,7 +13,8 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto [HttpPost("/api/google/sign-in")] public async Task SignIn([FromBody] GoogleSignInRequest request) { - var httpClient = httpClientFactory.CreateClient(); + using var httpClient = httpClientFactory.CreateClient(); + // Verify the token with Google var response = await httpClient.GetAsync($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={request.AccessToken}"); if (!response.IsSuccessStatusCode) @@ -21,12 +22,11 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto return BadRequest("Invalid Google token."); } - var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); - - var email = payload["email"]?.ToString() ?? ""; - var name = payload["name"]?.ToString() ?? ""; - var givenName = payload["given_name"]?.ToString() ?? ""; - var familyName = payload["family_name"]?.ToString() ?? ""; + var userInfo = JObject.Parse(await response.Content.ReadAsStringAsync()); + var email = userInfo["email"]?.ToString() ?? ""; + var name = userInfo["name"]?.ToString() ?? ""; + var givenName = userInfo["given_name"]?.ToString() ?? ""; + var familyName = userInfo["family_name"]?.ToString() ?? ""; if (string.IsNullOrEmpty(email)) { @@ -47,27 +47,29 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto } // Sign in the user - var claims = new List - { - new(ClaimTypes.Name, name), - new(ClaimTypes.Email, email), - new(ClaimTypes.GivenName, givenName), - new(ClaimTypes.Surname, familyName) - }; - - var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); - - var issuer = configuration["Jwt-Issuer"] ?? - throw new ArgumentNullException("The Jwt issuer is missing."); - var audience = configuration["Jwt-Audience"] ?? - throw new ArgumentNullException("The Jwt audience is missing."); - var key = configuration["Jwt-Key"] ?? - throw new ArgumentNullException("The Jwt key is missing."); - - var jwtToken = JwtTokenHelper.GenerateJwtToken(issuer, audience, key, user.Id); + var claimsIdentity = new ClaimsIdentity( + new List + { + new(ClaimTypes.Name, name), + new(ClaimTypes.Email, email), + new(ClaimTypes.GivenName, givenName), + new(ClaimTypes.Surname, familyName) + }, + CookieAuthenticationDefaults.AuthenticationScheme); - return Ok(new { accessToken = jwtToken, email }); + await HttpContext.SignInAsync( + CookieAuthenticationDefaults.AuthenticationScheme, + new ClaimsPrincipal(claimsIdentity)); + + var jwtSection = configuration.GetRequiredSection("Authentication:Jwt"); + + var token = JwtTokenHelper.GenerateJwtToken( + issuer: jwtSection["Issuer"] ?? throw new ArgumentNullException("The Jwt issuer is missing."), + audience: jwtSection["Audience"] ?? throw new ArgumentNullException("The Jwt audience is missing."), + key: jwtSection["Key"] ?? throw new ArgumentNullException("The Jwt key is missing."), + userId: user.Id); + + return Ok(new { accessToken = token, email }); } public class GoogleSignInRequest