Feature: Google oauth

This commit is contained in:
Kamigen
2024-05-08 19:04:25 -04:00
parent cd2bf64af5
commit bbbfddd6cb
5 changed files with 143 additions and 84 deletions

View File

@@ -0,0 +1,54 @@
using System.Security.Claims;
using Google.Apis.Oauth2.v2.Data;
using Hutopy.Domain.Interfaces;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Mvc;
namespace Hutopy.Web.Controllers;
public class GoogleController(
IUserService userService) : Controller
{
[HttpGet("/api/google/sign-in")]
public async Task SignIn()
{
await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, new AuthenticationProperties
{
RedirectUri = Url.Action("Callback"),
});
}
public async Task<IActionResult> Callback()
{
var authenticateResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
{
return BadRequest();
}
var claims = authenticateResult.Principal.Claims.ToList();
var userInfo = new Userinfo
{
Name = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value,
Email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value,
GivenName = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value,
FamilyName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value
};
await userService.CreateUserAsync(userInfo); // TODO: Don't create user if already exists
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new(ClaimTypes.Name, userInfo.Name),
new(ClaimTypes.Email, userInfo.Email),
new(ClaimTypes.GivenName, userInfo.GivenName),
new(ClaimTypes.Surname, userInfo.FamilyName)
}, CookieAuthenticationDefaults.AuthenticationScheme)));
return Redirect("/");
}
}