* Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
200 lines
7.8 KiB
C#
200 lines
7.8 KiB
C#
using System;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Newtonsoft.Json.Linq;
|
|
using Wino.Core.Domain;
|
|
using Wino.Core.Domain.Entities;
|
|
using Wino.Core.Domain.Enums;
|
|
using Wino.Core.Domain.Exceptions;
|
|
using Wino.Core.Domain.Interfaces;
|
|
using Wino.Core.Domain.Models.Authentication;
|
|
using Wino.Core.Domain.Models.Authorization;
|
|
using Wino.Core.Services;
|
|
|
|
namespace Wino.Core.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 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 = JObject.Parse(responseString);
|
|
|
|
if (parsed.ContainsKey("error"))
|
|
throw new GoogleAuthenticationException(parsed["error"]["message"].Value<string>());
|
|
|
|
var accessToken = parsed["access_token"].Value<string>();
|
|
var refreshToken = parsed["refresh_token"].Value<string>();
|
|
var expiresIn = parsed["expires_in"].Value<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 = JObject.Parse(userinfoResponseContent);
|
|
|
|
if (parsedUserInfo.ContainsKey("error"))
|
|
throw new GoogleAuthenticationException(parsedUserInfo["error"]["message"].Value<string>());
|
|
|
|
var username = parsedUserInfo["emailAddress"].Value<string>();
|
|
|
|
return new TokenInformation()
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
Address = username,
|
|
AccessToken = accessToken,
|
|
RefreshToken = refreshToken,
|
|
ExpiresAt = expirationDate
|
|
};
|
|
}
|
|
|
|
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();
|
|
|
|
var authorizationUri = authRequest.BuildRequest(ClientId);
|
|
|
|
Uri responseRedirectUri = null;
|
|
|
|
try
|
|
{
|
|
//await _authorizationCompletionSource.Task.WaitAsync(_authorizationCancellationTokenSource.Token);
|
|
responseRedirectUri = await _nativeAppService.GetAuthorizationResponseUriAsync(this, authorizationUri);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
throw new AuthenticationException(Translator.Exception_AuthenticationCanceled);
|
|
}
|
|
|
|
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 = JObject.Parse(responseString);
|
|
|
|
// TODO: Error parsing is incorrect.
|
|
if (parsed.ContainsKey("error"))
|
|
throw new GoogleAuthenticationException(parsed["error_description"].Value<string>());
|
|
|
|
var accessToken = parsed["access_token"].Value<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"].Value<string>();
|
|
}
|
|
|
|
var expiresIn = parsed["expires_in"].Value<long>();
|
|
var expirationDate = DateTime.UtcNow.AddSeconds(expiresIn);
|
|
|
|
return new TokenInformationBase()
|
|
{
|
|
AccessToken = accessToken,
|
|
ExpiresAt = expirationDate,
|
|
RefreshToken = activeRefreshToken
|
|
};
|
|
}
|
|
}
|
|
}
|