74 lines
2.9 KiB
C#
74 lines
2.9 KiB
C#
using Google.Apis.Auth.OAuth2;
|
|
using Google.Apis.Oauth2.v2;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Windows.Security.Authentication.Web;
|
|
using YouTube.Authorization;
|
|
using YouTube;
|
|
using System.Text.RegularExpressions;
|
|
using Windows.Security.Credentials;
|
|
using FoxTube.Core.Models;
|
|
using System.Threading;
|
|
using Google.Apis.YouTube.v3;
|
|
|
|
namespace FoxTube
|
|
{
|
|
public static class UserControl
|
|
{
|
|
static string[] Scopes { get; } = new string[]
|
|
{
|
|
Oauth2Service.Scope.UserinfoProfile,
|
|
Oauth2Service.Scope.UserinfoEmail,
|
|
YouTubeService.Scope.YoutubeForceSsl
|
|
};
|
|
|
|
static ClientSecrets ClientSecrets { get; } = new ClientSecrets
|
|
{
|
|
ClientId = "1096685398208-u95rcpkqb4e1ijfmb8jdq3jsg37l8igv.apps.googleusercontent.com",
|
|
ClientSecret = "IU5bbdjwvmx8ttJoXQ7e6JWd"
|
|
};
|
|
|
|
public static User CurrentUser { get; set; }
|
|
public static bool Authorized => CurrentUser != null;
|
|
|
|
public static async Task<bool> AddUser()
|
|
{
|
|
Uri callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
|
|
Uri requestString = AuthorizationHelpers.FormQueryString(ClientSecrets, callbackUri, Scopes);
|
|
|
|
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, requestString, AuthorizationHelpers.Endpoint);
|
|
switch(result.ResponseStatus)
|
|
{
|
|
case WebAuthenticationStatus.Success:
|
|
UserCredential credential = await AuthorizationHelpers.ExchangeToken(ClientSecrets, new Regex(@"(?<=code=).?\w+").Match(result.ResponseData).Value); // TODO: Add credential assignment
|
|
CurrentUser = new User(credential);
|
|
return true;
|
|
case WebAuthenticationStatus.UserCancel:
|
|
break;
|
|
case WebAuthenticationStatus.ErrorHttp:
|
|
Metrics.AddEvent("Authorization failed (HTTP Error)", ("Response data", result.ResponseData), ("Error details", result.ResponseErrorDetail.ToString()));
|
|
break;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public static async Task Initialize()
|
|
{
|
|
PasswordVault passwordVault = new PasswordVault();
|
|
List<PasswordCredential> credentials = passwordVault.FindAllByResource("foxtube").ToList();
|
|
|
|
if (credentials.Count == 0)
|
|
return;
|
|
|
|
credentials[0].RetrievePassword();
|
|
UserCredential credential = await AuthorizationHelpers.RestoreUser(ClientSecrets, credentials[0].Password);
|
|
CurrentUser = new User(credential);
|
|
}
|
|
|
|
public static async Task Logout() =>
|
|
await CurrentUser.Credential.RevokeTokenAsync(CancellationToken.None);
|
|
}
|
|
}
|