Cleaning up the solution. Separating Shared.WinRT, Services and Synchronization. Removing synchronization from app. Reducing bundle size by 45mb.
This commit is contained in:
22
Wino.Services/Authenticators/BaseAuthenticator.cs
Normal file
22
Wino.Services/Authenticators/BaseAuthenticator.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System.Threading.Tasks;
|
||||
using Wino.Domain.Entities;
|
||||
using Wino.Domain.Enums;
|
||||
using Wino.Domain.Interfaces;
|
||||
|
||||
namespace Wino.Services.Authenticators
|
||||
{
|
||||
public abstract class BaseAuthenticator
|
||||
{
|
||||
public abstract MailProviderType ProviderType { get; }
|
||||
|
||||
protected ITokenService TokenService { get; }
|
||||
|
||||
protected BaseAuthenticator(ITokenService tokenService)
|
||||
{
|
||||
TokenService = tokenService;
|
||||
}
|
||||
|
||||
internal Task SaveTokenInternalAsync(MailAccount account, TokenInformation tokenInformation)
|
||||
=> TokenService.SaveTokenInformationAsync(account.Id, tokenInformation);
|
||||
}
|
||||
}
|
||||
216
Wino.Services/Authenticators/GmailAuthenticator.cs
Normal file
216
Wino.Services/Authenticators/GmailAuthenticator.cs
Normal file
@@ -0,0 +1,216 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Wino.Domain;
|
||||
using Wino.Domain.Exceptions;
|
||||
using Wino.Domain.Entities;
|
||||
using Wino.Domain.Enums;
|
||||
using Wino.Domain.Exceptions;
|
||||
using Wino.Domain.Interfaces;
|
||||
using Wino.Domain.Models.Authentication;
|
||||
using Wino.Domain.Models.Authorization;
|
||||
|
||||
namespace Wino.Services.Authenticators
|
||||
{
|
||||
public class GmailAuthenticator : BaseAuthenticator, IGmailAuthenticator
|
||||
{
|
||||
public string ClientId { get; } = "973025879644-s7b4ur9p3rlgop6a22u7iuptdc0brnrn.apps.googleusercontent.com";
|
||||
|
||||
private const string TokenEndpoint = "https://www.googleapis.com/oauth2/v4/token";
|
||||
private const string RefreshTokenEndpoint = "https://oauth2.googleapis.com/token";
|
||||
private const string UserInfoEndpoint = "https://gmail.googleapis.com/gmail/v1/users/me/profile";
|
||||
|
||||
public override MailProviderType ProviderType => MailProviderType.Gmail;
|
||||
|
||||
private TaskCompletionSource<Uri> _authorizationCompletionSource = null;
|
||||
private CancellationTokenSource _authorizationCancellationTokenSource = null;
|
||||
|
||||
private readonly INativeAppService _nativeAppService;
|
||||
|
||||
public event EventHandler<string> InteractiveAuthenticationRequired;
|
||||
|
||||
public GmailAuthenticator(ITokenService tokenService, INativeAppService nativeAppService) : base(tokenService)
|
||||
{
|
||||
_nativeAppService = nativeAppService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs tokenization code exchange and retrieves the actual Access - Refresh tokens from Google
|
||||
/// after redirect uri returns from browser.
|
||||
/// </summary>
|
||||
/// <param name="tokenizationRequest">Tokenization request.</param>
|
||||
/// <exception cref="GoogleAuthenticationException">In case of network or parsing related error.</exception>
|
||||
private async Task<TokenInformation> PerformCodeExchangeAsync(GoogleTokenizationRequest tokenizationRequest)
|
||||
{
|
||||
var uri = tokenizationRequest.BuildRequest();
|
||||
|
||||
var content = new StringContent(uri, Encoding.UTF8, "application/x-www-form-urlencoded");
|
||||
|
||||
var handler = new HttpClientHandler()
|
||||
{
|
||||
AllowAutoRedirect = true
|
||||
};
|
||||
|
||||
var client = new HttpClient(handler);
|
||||
|
||||
var response = await client.PostAsync(TokenEndpoint, content);
|
||||
string responseString = await response.Content.ReadAsStringAsync();
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new GoogleAuthenticationException(Translator.Exception_GoogleAuthorizationCodeExchangeFailed);
|
||||
|
||||
var parsed = JsonNode.Parse(responseString).AsObject();
|
||||
|
||||
if (parsed.ContainsKey("error"))
|
||||
throw new GoogleAuthenticationException(parsed["error"]["message"].GetValue<string>());
|
||||
|
||||
var accessToken = parsed["access_token"].GetValue<string>();
|
||||
var refreshToken = parsed["refresh_token"].GetValue<string>();
|
||||
var expiresIn = parsed["expires_in"].GetValue<long>();
|
||||
|
||||
var expirationDate = DateTime.UtcNow.AddSeconds(expiresIn);
|
||||
|
||||
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
|
||||
|
||||
// Get basic user info for UserName.
|
||||
|
||||
var userinfoResponse = await client.GetAsync(UserInfoEndpoint);
|
||||
string userinfoResponseContent = await userinfoResponse.Content.ReadAsStringAsync();
|
||||
|
||||
var parsedUserInfo = JsonNode.Parse(userinfoResponseContent).AsObject();
|
||||
|
||||
if (parsedUserInfo.ContainsKey("error"))
|
||||
throw new GoogleAuthenticationException(parsedUserInfo["error"]["message"].GetValue<string>());
|
||||
|
||||
var username = parsedUserInfo["emailAddress"].GetValue<string>();
|
||||
|
||||
return new TokenInformation()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Address = username,
|
||||
AccessToken = accessToken,
|
||||
RefreshToken = refreshToken,
|
||||
ExpiresAt = expirationDate
|
||||
};
|
||||
}
|
||||
|
||||
public void ContinueAuthorization(Uri authorizationResponseUri) => _authorizationCompletionSource?.TrySetResult(authorizationResponseUri);
|
||||
|
||||
public async Task<TokenInformation> GetTokenAsync(MailAccount account)
|
||||
{
|
||||
var cachedToken = await TokenService.GetTokenInformationAsync(account.Id)
|
||||
?? throw new AuthenticationAttentionException(account);
|
||||
|
||||
if (cachedToken.IsExpired)
|
||||
{
|
||||
// Refresh token with new exchanges.
|
||||
// No need to check Username for account.
|
||||
|
||||
var refreshedTokenInfoBase = await RefreshTokenAsync(cachedToken.RefreshToken);
|
||||
|
||||
cachedToken.RefreshTokens(refreshedTokenInfoBase);
|
||||
|
||||
// Save new token and return.
|
||||
await SaveTokenInternalAsync(account, cachedToken);
|
||||
}
|
||||
|
||||
return cachedToken;
|
||||
}
|
||||
|
||||
|
||||
public async Task<TokenInformation> GenerateTokenAsync(MailAccount account, bool saveToken)
|
||||
{
|
||||
var authRequest = _nativeAppService.GetGoogleAuthorizationRequest();
|
||||
|
||||
_authorizationCompletionSource = new TaskCompletionSource<Uri>();
|
||||
_authorizationCancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
var authorizationUri = authRequest.BuildRequest(ClientId);
|
||||
|
||||
await _nativeAppService.LaunchUriAsync(new Uri(authorizationUri));
|
||||
|
||||
Uri responseRedirectUri = null;
|
||||
|
||||
try
|
||||
{
|
||||
responseRedirectUri = await _authorizationCompletionSource.Task.WaitAsync(_authorizationCancellationTokenSource.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new AuthenticationException(Translator.Exception_AuthenticationCanceled);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_authorizationCancellationTokenSource.Dispose();
|
||||
_authorizationCancellationTokenSource = null;
|
||||
_authorizationCompletionSource = null;
|
||||
}
|
||||
|
||||
authRequest.ValidateAuthorizationCode(responseRedirectUri);
|
||||
|
||||
// Start tokenization.
|
||||
var tokenizationRequest = new GoogleTokenizationRequest(authRequest);
|
||||
var tokenInformation = await PerformCodeExchangeAsync(tokenizationRequest);
|
||||
|
||||
if (saveToken)
|
||||
{
|
||||
await SaveTokenInternalAsync(account, tokenInformation);
|
||||
}
|
||||
|
||||
return tokenInformation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Internally exchanges refresh token with a new access token and returns new TokenInformation.
|
||||
/// </summary>
|
||||
/// <param name="refresh_token">Token to be used in refreshing.</param>
|
||||
/// <returns>New TokenInformationBase that has new tokens and expiration date without a username. This token is not saved to database after returned.</returns>
|
||||
private async Task<TokenInformationBase> RefreshTokenAsync(string refresh_token)
|
||||
{
|
||||
// TODO: This doesn't work.
|
||||
var refreshUri = string.Format("client_id={0}&refresh_token={1}&grant_type=refresh_token", ClientId, refresh_token);
|
||||
|
||||
//Uri.EscapeDataString(refreshUri);
|
||||
var content = new StringContent(refreshUri, Encoding.UTF8, "application/x-www-form-urlencoded");
|
||||
|
||||
var client = new HttpClient();
|
||||
|
||||
var response = await client.PostAsync(RefreshTokenEndpoint, content);
|
||||
|
||||
string responseString = await response.Content.ReadAsStringAsync();
|
||||
var parsed = JsonNode.Parse(responseString).AsObject();
|
||||
|
||||
// TODO: Error parsing is incorrect.
|
||||
if (parsed.ContainsKey("error"))
|
||||
throw new GoogleAuthenticationException(parsed["error_description"].GetValue<string>());
|
||||
|
||||
var accessToken = parsed["access_token"].GetValue<string>();
|
||||
|
||||
string activeRefreshToken = refresh_token;
|
||||
|
||||
// Refresh token might not be returned.
|
||||
// In this case older refresh token is still available for new refreshes.
|
||||
// Only change if provided.
|
||||
|
||||
if (parsed.ContainsKey("refresh_token"))
|
||||
{
|
||||
activeRefreshToken = parsed["refresh_token"].GetValue<string>();
|
||||
}
|
||||
|
||||
var expiresIn = parsed["expires_in"].GetValue<long>();
|
||||
var expirationDate = DateTime.UtcNow.AddSeconds(expiresIn);
|
||||
|
||||
return new TokenInformationBase()
|
||||
{
|
||||
AccessToken = accessToken,
|
||||
ExpiresAt = expirationDate,
|
||||
RefreshToken = activeRefreshToken
|
||||
};
|
||||
}
|
||||
|
||||
public void CancelAuthorization() => _authorizationCancellationTokenSource?.Cancel();
|
||||
}
|
||||
}
|
||||
12
Wino.Services/Authenticators/Office365Authenticator.cs
Normal file
12
Wino.Services/Authenticators/Office365Authenticator.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using Wino.Domain.Enums;
|
||||
using Wino.Domain.Interfaces;
|
||||
|
||||
namespace Wino.Services.Authenticators
|
||||
{
|
||||
public class Office365Authenticator : OutlookAuthenticator
|
||||
{
|
||||
public Office365Authenticator(ITokenService tokenService, INativeAppService nativeAppService) : base(tokenService, nativeAppService) { }
|
||||
|
||||
public override MailProviderType ProviderType => MailProviderType.Office365;
|
||||
}
|
||||
}
|
||||
121
Wino.Services/Authenticators/OutlookAuthenticator.cs
Normal file
121
Wino.Services/Authenticators/OutlookAuthenticator.cs
Normal file
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Identity.Client;
|
||||
using Wino.Domain;
|
||||
using Wino.Domain.Exceptions;
|
||||
using Wino.Domain.Entities;
|
||||
using Wino.Domain.Enums;
|
||||
using Wino.Domain.Interfaces;
|
||||
using Wino.Services.Extensions;
|
||||
|
||||
namespace Wino.Services.Authenticators
|
||||
{
|
||||
public class OutlookAuthenticator : BaseAuthenticator, IOutlookAuthenticator
|
||||
{
|
||||
// Outlook
|
||||
private const string Authority = "https://login.microsoftonline.com/common";
|
||||
|
||||
public string ClientId { get; } = "b19c2035-d740-49ff-b297-de6ec561b208";
|
||||
|
||||
private readonly string[] MailScope = new string[] { "email", "mail.readwrite", "offline_access", "mail.send" };
|
||||
|
||||
public override MailProviderType ProviderType => MailProviderType.Outlook;
|
||||
|
||||
private readonly IPublicClientApplication _publicClientApplication;
|
||||
|
||||
public OutlookAuthenticator(ITokenService tokenService, INativeAppService nativeAppService) : base(tokenService)
|
||||
{
|
||||
var authenticationRedirectUri = nativeAppService.GetWebAuthenticationBrokerUri();
|
||||
|
||||
var outlookAppBuilder = PublicClientApplicationBuilder.Create(ClientId)
|
||||
.WithAuthority(Authority);
|
||||
|
||||
#if WINDOWS_UWP
|
||||
outlookAppBuilder.WithRedirectUri(authenticationRedirectUri);
|
||||
#else
|
||||
outlookAppBuilder.WithDefaultRedirectUri();
|
||||
#endif
|
||||
_publicClientApplication = outlookAppBuilder.Build();
|
||||
|
||||
|
||||
}
|
||||
|
||||
#pragma warning disable S1133 // Deprecated code should be removed
|
||||
[Obsolete("Not used for OutlookAuthenticator.")]
|
||||
#pragma warning restore S1133 // Deprecated code should be removed
|
||||
public void ContinueAuthorization(Uri authorizationResponseUri) { }
|
||||
|
||||
#pragma warning disable S1133 // Deprecated code should be removed
|
||||
[Obsolete("Not used for OutlookAuthenticator.")]
|
||||
#pragma warning restore S1133 // Deprecated code should be removed
|
||||
public void CancelAuthorization() { }
|
||||
|
||||
public async Task<TokenInformation> GetTokenAsync(MailAccount account)
|
||||
{
|
||||
var cachedToken = await TokenService.GetTokenInformationAsync(account.Id)
|
||||
?? throw new AuthenticationAttentionException(account);
|
||||
|
||||
// We have token but it's expired.
|
||||
// Silently refresh the token and save new token.
|
||||
|
||||
if (cachedToken.IsExpired)
|
||||
{
|
||||
var cachedOutlookAccount = (await _publicClientApplication.GetAccountsAsync()).FirstOrDefault(a => a.Username == account.Address);
|
||||
|
||||
// Again, not expected at all...
|
||||
// Force interactive login at this point.
|
||||
|
||||
if (cachedOutlookAccount == null)
|
||||
{
|
||||
// What if interactive login info is for different account?
|
||||
|
||||
return await GenerateTokenAsync(account, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Silently refresh token from cache.
|
||||
|
||||
AuthenticationResult authResult = await _publicClientApplication.AcquireTokenSilent(MailScope, cachedOutlookAccount).ExecuteAsync();
|
||||
|
||||
// Save refreshed token and return
|
||||
var refreshedTokenInformation = authResult.CreateTokenInformation();
|
||||
|
||||
await TokenService.SaveTokenInformationAsync(account.Id, refreshedTokenInformation);
|
||||
|
||||
return refreshedTokenInformation;
|
||||
}
|
||||
}
|
||||
else
|
||||
return cachedToken;
|
||||
}
|
||||
|
||||
public async Task<TokenInformation> GenerateTokenAsync(MailAccount account, bool saveToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var authResult = await _publicClientApplication
|
||||
.AcquireTokenInteractive(MailScope)
|
||||
.ExecuteAsync();
|
||||
|
||||
var tokenInformation = authResult.CreateTokenInformation();
|
||||
|
||||
if (saveToken)
|
||||
{
|
||||
await SaveTokenInternalAsync(account, tokenInformation);
|
||||
}
|
||||
|
||||
return tokenInformation;
|
||||
}
|
||||
catch (MsalClientException msalClientException)
|
||||
{
|
||||
if (msalClientException.ErrorCode == "authentication_canceled" || msalClientException.ErrorCode == "access_denied")
|
||||
throw new AccountSetupCanceledException();
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
throw new AuthenticationException(Translator.Exception_UnknowErrorDuringAuthentication, new Exception(Translator.Exception_TokenGenerationFailed));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user