using System;
using System.Threading.Tasks;
namespace Octokit
{
///
/// Represents operations to simplify triggering the authorization flow
///
public static class AuthorizationExtensions
{
///
/// This method will create a new authorization for the specified OAuth application, only if an authorization
/// for that application doesn’t already exist for the user. It returns the user’s token for the application
/// if one exists. Otherwise, it creates a new one.
///
///
///
/// This method allows the caller to provide a callback which is used to retrieve the two-factor code from
/// the user. Typically the callback is used to show some user interface to the user.
///
///
/// See API documentation
/// for more details.
///
///
/// The this method extends
/// Client Id for the OAuth application that is requesting the token
/// The client secret
/// Defines the scopes and metadata for the token
/// Callback used to retrieve the two-factor authentication code
/// from the user
///
public static async Task GetOrCreateApplicationAuthentication(
this IAuthorizationsClient authorizationsClient,
string clientId,
string clientSecret,
NewAuthorization newAuthorization,
Func> twoFactorChallengeHandler
)
{
TwoFactorRequiredException twoFactorException = null;
try
{
return await authorizationsClient.GetOrCreateApplicationAuthentication(clientId, clientSecret, newAuthorization).ConfigureAwait(false);
}
catch (TwoFactorRequiredException exception)
{
twoFactorException = exception;
}
var twoFactorChallengeResult = await twoFactorChallengeHandler(twoFactorException).ConfigureAwait(false);
return await (twoFactorChallengeResult.ResendCodeRequested
? authorizationsClient.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuthorization,
twoFactorChallengeHandler).ConfigureAwait(false)
: authorizationsClient.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuthorization,
twoFactorChallengeResult.AuthenticationCode).ConfigureAwait(false));
}
}
}