2022-09-08 13:38:32 +01:00
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
2023-05-09 13:56:57 +00:00
|
|
|
|
using VoidCat.Database;
|
2022-09-08 13:38:32 +01:00
|
|
|
|
using VoidCat.Model;
|
|
|
|
|
|
|
|
|
|
namespace VoidCat.Services.Users.Auth;
|
|
|
|
|
|
|
|
|
|
public class GoogleOAuthProvider : GenericOAuth2Service
|
|
|
|
|
{
|
|
|
|
|
private readonly HttpClient _client;
|
|
|
|
|
|
|
|
|
|
public GoogleOAuthProvider(HttpClient client, VoidSettings settings) : base(client, settings)
|
|
|
|
|
{
|
|
|
|
|
_client = client;
|
|
|
|
|
Details = settings.Google!;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public override string Id => "google";
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
2023-05-09 13:56:57 +00:00
|
|
|
|
public override ValueTask<User?> GetUserDetails(UserAuthToken token)
|
2022-09-08 13:38:32 +01:00
|
|
|
|
{
|
2022-09-08 14:29:31 +01:00
|
|
|
|
var jwt = new JwtSecurityToken(token.IdToken);
|
|
|
|
|
|
|
|
|
|
string? GetPayloadValue(string key)
|
|
|
|
|
=> jwt.Payload.TryGetValue(key, out var v)
|
|
|
|
|
? v as string
|
|
|
|
|
: default;
|
|
|
|
|
|
2023-05-09 13:56:57 +00:00
|
|
|
|
return ValueTask.FromResult(new User()
|
2022-09-08 13:38:32 +01:00
|
|
|
|
{
|
|
|
|
|
Id = Guid.NewGuid(),
|
2023-05-09 13:56:57 +00:00
|
|
|
|
Created = DateTime.UtcNow,
|
|
|
|
|
LastLogin = DateTime.UtcNow,
|
|
|
|
|
AuthType = UserAuthType.OAuth2,
|
2022-09-08 14:29:31 +01:00
|
|
|
|
Email = GetPayloadValue("email") ?? throw new InvalidOperationException("Failed to get email from Google JWT"),
|
2023-05-09 13:56:57 +00:00
|
|
|
|
DisplayName = GetPayloadValue("name") ?? "void user",
|
2022-09-08 14:29:31 +01:00
|
|
|
|
Avatar = GetPayloadValue("picture")
|
2022-09-08 13:38:32 +01:00
|
|
|
|
})!;
|
|
|
|
|
}
|
|
|
|
|
|
2022-09-08 14:29:31 +01:00
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
protected override string Prompt => "select_account";
|
|
|
|
|
|
2022-09-08 13:38:32 +01:00
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
protected override Uri AuthorizeEndpoint => new("https://accounts.google.com/o/oauth2/v2/auth");
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
protected override Uri TokenEndpoint => new("https://oauth2.googleapis.com/token");
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
protected override OAuthDetails Details { get; }
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
protected override string[] Scopes => new[]
|
|
|
|
|
{"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"};
|
|
|
|
|
}
|