Feature: Google oauth
This commit is contained in:
54
src/Web/Controllers/GoogleController.cs
Normal file
54
src/Web/Controllers/GoogleController.cs
Normal 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("/");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user