|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.IO; |
| 6 | +using System.Net.Http; |
| 7 | +using System.Reflection; |
| 8 | +using System.Text; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.Git.CredentialManager; |
| 12 | +using Microsoft.Git.CredentialManager.Authentication; |
| 13 | +using Microsoft.Git.CredentialManager.Authentication.OAuth; |
| 14 | + |
| 15 | +namespace Atlassian.Bitbucket |
| 16 | +{ |
| 17 | + public interface IBitbucketAuthentication : IDisposable |
| 18 | + { |
| 19 | + Task<ICredential> GetBasicCredentialsAsync(Uri targetUri, string userName); |
| 20 | + Task<bool> ShowOAuthRequiredPromptAsync(); |
| 21 | + Task<OAuth2TokenResult> CreateOAuthCredentialsAsync(Uri targetUri); |
| 22 | + Task<OAuth2TokenResult> RefreshOAuthCredentialsAsync(string refreshToken); |
| 23 | + } |
| 24 | + |
| 25 | + public class BitbucketAuthentication : AuthenticationBase, IBitbucketAuthentication |
| 26 | + { |
| 27 | + public static readonly string[] AuthorityIds = |
| 28 | + { |
| 29 | + "bitbucket", |
| 30 | + }; |
| 31 | + |
| 32 | + private static readonly string[] Scopes = |
| 33 | + { |
| 34 | + BitbucketConstants.OAuthScopes.RepositoryWrite, |
| 35 | + BitbucketConstants.OAuthScopes.Account, |
| 36 | + }; |
| 37 | + |
| 38 | + public BitbucketAuthentication(ICommandContext context) |
| 39 | + : base(context) { } |
| 40 | + |
| 41 | + #region IBitbucketAuthentication |
| 42 | + |
| 43 | + public async Task<ICredential> GetBasicCredentialsAsync(Uri targetUri, string userName) |
| 44 | + { |
| 45 | + ThrowIfUserInteractionDisabled(); |
| 46 | + |
| 47 | + string password; |
| 48 | + |
| 49 | + // Shell out to the UI helper and show the Bitbucket u/p prompt |
| 50 | + if (Context.IsDesktopSession && TryFindHelperExecutablePath(out string helperPath)) |
| 51 | + { |
| 52 | + var cmdArgs = new StringBuilder("--prompt userpass"); |
| 53 | + if (!string.IsNullOrWhiteSpace(userName)) |
| 54 | + { |
| 55 | + cmdArgs.AppendFormat(" --username {0}", userName); |
| 56 | + } |
| 57 | + |
| 58 | + IDictionary<string, string> output = await InvokeHelperAsync(helperPath, cmdArgs.ToString()); |
| 59 | + |
| 60 | + if (!output.TryGetValue("username", out userName)) |
| 61 | + { |
| 62 | + throw new Exception("Missing username in response"); |
| 63 | + } |
| 64 | + |
| 65 | + if (!output.TryGetValue("password", out password)) |
| 66 | + { |
| 67 | + throw new Exception("Missing password in response"); |
| 68 | + } |
| 69 | + |
| 70 | + return new GitCredential(userName, password); |
| 71 | + } |
| 72 | + else |
| 73 | + { |
| 74 | + ThrowIfTerminalPromptsDisabled(); |
| 75 | + |
| 76 | + Context.Terminal.WriteLine("Enter Bitbucket credentials for '{0}'...", targetUri); |
| 77 | + |
| 78 | + if (!string.IsNullOrWhiteSpace(userName)) |
| 79 | + { |
| 80 | + // Don't need to prompt for the username if it has been specified already |
| 81 | + Context.Terminal.WriteLine("Username: {0}", userName); |
| 82 | + } |
| 83 | + else |
| 84 | + { |
| 85 | + // Prompt for username |
| 86 | + userName = Context.Terminal.Prompt("Username"); |
| 87 | + } |
| 88 | + |
| 89 | + // Prompt for password |
| 90 | + password = Context.Terminal.PromptSecret("Password"); |
| 91 | + |
| 92 | + return new GitCredential(userName, password); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + public async Task<bool> ShowOAuthRequiredPromptAsync() |
| 97 | + { |
| 98 | + ThrowIfUserInteractionDisabled(); |
| 99 | + |
| 100 | + // Shell out to the UI helper and show the Bitbucket prompt |
| 101 | + if (Context.IsDesktopSession && TryFindHelperExecutablePath(out string helperPath)) |
| 102 | + { |
| 103 | + IDictionary<string, string> output = await InvokeHelperAsync(helperPath, "--prompt oauth"); |
| 104 | + |
| 105 | + if (output.TryGetValue("continue", out string continueStr) && continueStr.IsTruthy()) |
| 106 | + { |
| 107 | + return true; |
| 108 | + } |
| 109 | + |
| 110 | + return false; |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + ThrowIfTerminalPromptsDisabled(); |
| 115 | + |
| 116 | + Context.Terminal.WriteLine($"Your account has two-factor authentication enabled.{Environment.NewLine}" + |
| 117 | + $"To continue you must complete authentication in your web browser.{Environment.NewLine}"); |
| 118 | + |
| 119 | + var _ = Context.Terminal.Prompt("Press enter to continue..."); |
| 120 | + return true; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + public async Task<OAuth2TokenResult> CreateOAuthCredentialsAsync(Uri targetUri) |
| 125 | + { |
| 126 | + var oauthClient = new BitbucketOAuth2Client(HttpClient, Context.Settings); |
| 127 | + |
| 128 | + var browserOptions = new OAuth2WebBrowserOptions |
| 129 | + { |
| 130 | + SuccessResponseHtml = BitbucketResources.AuthenticationResponseSuccessHtml, |
| 131 | + FailureResponseHtmlFormat = BitbucketResources.AuthenticationResponseFailureHtmlFormat |
| 132 | + }; |
| 133 | + |
| 134 | + var browser = new OAuth2SystemWebBrowser(browserOptions); |
| 135 | + var authCodeResult = await oauthClient.GetAuthorizationCodeAsync(Scopes, browser, CancellationToken.None); |
| 136 | + |
| 137 | + return await oauthClient.GetTokenByAuthorizationCodeAsync(authCodeResult, CancellationToken.None); |
| 138 | + } |
| 139 | + |
| 140 | + public async Task<OAuth2TokenResult> RefreshOAuthCredentialsAsync(string refreshToken) |
| 141 | + { |
| 142 | + var oauthClient = new BitbucketOAuth2Client(HttpClient, Context.Settings); |
| 143 | + |
| 144 | + return await oauthClient.GetTokenByRefreshTokenAsync(refreshToken, CancellationToken.None); |
| 145 | + } |
| 146 | + |
| 147 | + #endregion |
| 148 | + |
| 149 | + #region Private Methods |
| 150 | + |
| 151 | + private bool TryFindHelperExecutablePath(out string path) |
| 152 | + { |
| 153 | + string helperName = BitbucketConstants.BitbucketAuthHelperName; |
| 154 | + |
| 155 | + if (PlatformUtils.IsWindows()) |
| 156 | + { |
| 157 | + helperName += ".exe"; |
| 158 | + } |
| 159 | + |
| 160 | + string executableDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); |
| 161 | + path = Path.Combine(executableDirectory, helperName); |
| 162 | + return Context.FileSystem.FileExists(path); |
| 163 | + } |
| 164 | + |
| 165 | + private HttpClient _httpClient; |
| 166 | + private HttpClient HttpClient => _httpClient ??= Context.HttpClientFactory.CreateClient(); |
| 167 | + |
| 168 | + #endregion |
| 169 | + |
| 170 | + #region IDisposable |
| 171 | + |
| 172 | + public void Dispose() |
| 173 | + { |
| 174 | + _httpClient?.Dispose(); |
| 175 | + } |
| 176 | + |
| 177 | + #endregion |
| 178 | + } |
| 179 | +} |
0 commit comments