Just cleanup
This commit is contained in:
@@ -8,14 +8,14 @@ public class GetCurrentUserQueryHandler(
|
|||||||
IApplicationDbContext context,
|
IApplicationDbContext context,
|
||||||
IMapper mapper,
|
IMapper mapper,
|
||||||
IIdentityService identityService
|
IIdentityService identityService
|
||||||
)
|
)
|
||||||
: IRequestHandler<GetCurrentUserQuery, UserDto>
|
: IRequestHandler<GetCurrentUserQuery, UserDto>
|
||||||
{
|
{
|
||||||
public async Task<UserDto> Handle(GetCurrentUserQuery request, CancellationToken cancellationToken)
|
public async Task<UserDto> Handle(GetCurrentUserQuery request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var identityUser = await identityService.GetCurrentUserAsync();
|
var identityUser = await identityService.GetCurrentUserAsync();
|
||||||
var currentUserId = new Guid(identityUser?.Id ?? "");
|
var currentUserId = Guid.Parse(identityUser!.Id!);
|
||||||
|
|
||||||
var transactions = await context.UserTransactions
|
var transactions = await context.UserTransactions
|
||||||
.Where(x => x.ApplicationUserId == currentUserId.ToString())
|
.Where(x => x.ApplicationUserId == currentUserId.ToString())
|
||||||
.OrderBy(x => x.LastModified)
|
.OrderBy(x => x.LastModified)
|
||||||
@@ -30,7 +30,7 @@ public class GetCurrentUserQueryHandler(
|
|||||||
Id = currentUserId,
|
Id = currentUserId,
|
||||||
FirstName = identityUser?.FirstName ?? "",
|
FirstName = identityUser?.FirstName ?? "",
|
||||||
LastName = identityUser?.LastName ?? "",
|
LastName = identityUser?.LastName ?? "",
|
||||||
UserName =identityUser?.UserName ?? "",
|
UserName = identityUser?.UserName ?? "",
|
||||||
UserTransactions = transactions,
|
UserTransactions = transactions,
|
||||||
TotalBalance = transactions.Sum(x => x.Amount),
|
TotalBalance = transactions.Sum(x => x.Amount),
|
||||||
UserRoles = roles
|
UserRoles = roles
|
||||||
|
|||||||
@@ -9,20 +9,18 @@ public static class JwtTokenHelper
|
|||||||
{
|
{
|
||||||
public static string GenerateJwtToken(string issuer, string audience, string key, string userId)
|
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 securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
||||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||||
|
|
||||||
var token = new JwtSecurityToken(
|
var token = new JwtSecurityToken(
|
||||||
issuer: issuer,
|
issuer: issuer,
|
||||||
audience: audience,
|
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),
|
expires: DateTime.Now.AddMinutes(30),
|
||||||
signingCredentials: credentials);
|
signingCredentials: credentials);
|
||||||
|
|
||||||
|
|||||||
@@ -13,41 +13,45 @@ public class FacebookController(IIdentityService identityService) : Controller
|
|||||||
[HttpGet("/api/facebook/sign-in")]
|
[HttpGet("/api/facebook/sign-in")]
|
||||||
public async Task SignIn()
|
public async Task SignIn()
|
||||||
{
|
{
|
||||||
await HttpContext.ChallengeAsync(FacebookDefaults.AuthenticationScheme, new AuthenticationProperties
|
await HttpContext.ChallengeAsync(FacebookDefaults.AuthenticationScheme,
|
||||||
{
|
new AuthenticationProperties { RedirectUri = Url.Action("Authorize") });
|
||||||
RedirectUri = Url.Action("Authorize")
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> Authorize()
|
public async Task<IActionResult> Authorize()
|
||||||
{
|
{
|
||||||
var authenticateResult = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme);
|
var authenticateResult = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme);
|
||||||
|
|
||||||
if (!authenticateResult.Succeeded) return BadRequest();
|
if (!authenticateResult.Succeeded) return BadRequest();
|
||||||
|
|
||||||
var claims = authenticateResult.Principal.Claims.ToList();
|
var claims = authenticateResult.Principal.Claims.ToList();
|
||||||
|
|
||||||
var name = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? "";
|
var name = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? "";
|
||||||
var email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value ?? "";
|
var email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value ?? "";
|
||||||
var givenName = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value ?? "";
|
var givenName = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value ?? "";
|
||||||
var familyName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value ?? "";
|
var familyName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value ?? "";
|
||||||
|
|
||||||
var claimsIdentity = new ClaimsIdentity(new List<Claim>
|
var claimsIdentity = new ClaimsIdentity(
|
||||||
{
|
new List<Claim>
|
||||||
new(ClaimTypes.Name, name),
|
{
|
||||||
new(ClaimTypes.Email, email),
|
new(ClaimTypes.Name, name),
|
||||||
new(ClaimTypes.GivenName, givenName),
|
new(ClaimTypes.Email, email),
|
||||||
new(ClaimTypes.Surname, familyName)
|
new(ClaimTypes.GivenName, givenName),
|
||||||
}, CookieAuthenticationDefaults.AuthenticationScheme);
|
new(ClaimTypes.Surname, familyName)
|
||||||
|
},
|
||||||
|
CookieAuthenticationDefaults.AuthenticationScheme);
|
||||||
|
|
||||||
if (await identityService.FindUserByEmailAsync(email) != null)
|
if (await identityService.FindUserByEmailAsync(email) != null)
|
||||||
{
|
{
|
||||||
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
|
await HttpContext.SignInAsync(
|
||||||
|
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||||
|
new ClaimsPrincipal(claimsIdentity));
|
||||||
return Redirect("/");
|
return Redirect("/");
|
||||||
}
|
}
|
||||||
|
|
||||||
await identityService.CreateUserAsync(email, givenName, givenName, familyName, RandomGenerator.RandomString(24));
|
await identityService.CreateUserAsync(email, givenName, givenName, familyName,
|
||||||
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
|
RandomGenerator.RandomString(24));
|
||||||
|
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
|
||||||
|
new ClaimsPrincipal(claimsIdentity));
|
||||||
return Redirect("/");
|
return Redirect("/");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto
|
|||||||
[HttpPost("/api/google/sign-in")]
|
[HttpPost("/api/google/sign-in")]
|
||||||
public async Task<IActionResult> SignIn([FromBody] GoogleSignInRequest request)
|
public async Task<IActionResult> SignIn([FromBody] GoogleSignInRequest request)
|
||||||
{
|
{
|
||||||
var httpClient = httpClientFactory.CreateClient();
|
using var httpClient = httpClientFactory.CreateClient();
|
||||||
|
|
||||||
// Verify the token with Google
|
// Verify the token with Google
|
||||||
var response = await httpClient.GetAsync($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={request.AccessToken}");
|
var response = await httpClient.GetAsync($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={request.AccessToken}");
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
@@ -21,12 +22,11 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto
|
|||||||
return BadRequest("Invalid Google token.");
|
return BadRequest("Invalid Google token.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
var userInfo = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
var email = userInfo["email"]?.ToString() ?? "";
|
||||||
var email = payload["email"]?.ToString() ?? "";
|
var name = userInfo["name"]?.ToString() ?? "";
|
||||||
var name = payload["name"]?.ToString() ?? "";
|
var givenName = userInfo["given_name"]?.ToString() ?? "";
|
||||||
var givenName = payload["given_name"]?.ToString() ?? "";
|
var familyName = userInfo["family_name"]?.ToString() ?? "";
|
||||||
var familyName = payload["family_name"]?.ToString() ?? "";
|
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(email))
|
if (string.IsNullOrEmpty(email))
|
||||||
{
|
{
|
||||||
@@ -47,27 +47,29 @@ public class GoogleController(IIdentityService identityService, IHttpClientFacto
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sign in the user
|
// Sign in the user
|
||||||
var claims = new List<Claim>
|
var claimsIdentity = new ClaimsIdentity(
|
||||||
{
|
new List<Claim>
|
||||||
new(ClaimTypes.Name, name),
|
{
|
||||||
new(ClaimTypes.Email, email),
|
new(ClaimTypes.Name, name),
|
||||||
new(ClaimTypes.GivenName, givenName),
|
new(ClaimTypes.Email, email),
|
||||||
new(ClaimTypes.Surname, familyName)
|
new(ClaimTypes.GivenName, givenName),
|
||||||
};
|
new(ClaimTypes.Surname, familyName)
|
||||||
|
},
|
||||||
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
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);
|
|
||||||
|
|
||||||
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
|
public class GoogleSignInRequest
|
||||||
|
|||||||
Reference in New Issue
Block a user