Just cleanup

This commit is contained in:
Jonathan Bourdon
2024-06-20 13:44:45 -04:00
parent 1725008211
commit 128e68f63f
4 changed files with 63 additions and 59 deletions

View File

@@ -8,14 +8,14 @@ public class GetCurrentUserQueryHandler(
IApplicationDbContext context,
IMapper mapper,
IIdentityService identityService
)
)
: IRequestHandler<GetCurrentUserQuery, UserDto>
{
public async Task<UserDto> 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

View File

@@ -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);

View File

@@ -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<IActionResult> 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<Claim>
{
new(ClaimTypes.Name, name),
new(ClaimTypes.Email, email),
new(ClaimTypes.GivenName, givenName),
new(ClaimTypes.Surname, familyName)
}, CookieAuthenticationDefaults.AuthenticationScheme);
var claimsIdentity = new ClaimsIdentity(
new List<Claim>
{
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("/");
}
}

View File

@@ -13,7 +13,8 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto
[HttpPost("/api/google/sign-in")]
public async Task<IActionResult> 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<Claim>
{
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<Claim>
{
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