示例#1
0
        /// <inheritdoc/>
        public async Task <LoginResultData> Login(
            UriString host,
            IGitHubClient client,
            string username,
            string password)
        {
            Guard.ArgumentNotNull(host, nameof(host));
            Guard.ArgumentNotNull(client, nameof(client));
            Guard.ArgumentNotNullOrWhiteSpace(username, nameof(username));
            Guard.ArgumentNotNullOrWhiteSpace(password, nameof(password));

            // Start by saving the username and password, these will be used by the `IGitHubClient`
            // until an authorization token has been created and acquired:
            keychain.Connect(host);
            keychain.SetCredentials(new Credential(host, username, password));

            var newAuth = new NewAuthorization
            {
                Scopes      = scopes,
                Note        = authorizationNote,
                Fingerprint = fingerprint,
            };

            ApplicationAuthorization auth = null;

            try
            {
                logger.Info("Login Username:{0}", username);

                auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null);

                EnsureNonNullAuthorization(auth);
            }
            catch (TwoFactorAuthorizationException e)
            {
                LoginResultCodes result;
                if (e is TwoFactorRequiredException)
                {
                    result = LoginResultCodes.CodeRequired;
                    logger.Trace("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message);
                }
                else
                {
                    result = LoginResultCodes.CodeFailed;
                    logger.Error(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message);
                }

                return(new LoginResultData(result, e.Message, client, host, newAuth));
            }
            catch (LoginAttemptsExceededException e)
            {
                logger.Warning(e, "Login LoginAttemptsExceededException: {0}", e.Message);

                await keychain.Clear(host, false);

                return(new LoginResultData(LoginResultCodes.LockedOut, Localization.LockedOut, host));
            }
            catch (ApiValidationException e)
            {
                logger.Warning(e, "Login ApiValidationException: {0}", e.Message);

                var message = e.ApiError.FirstErrorMessageSafe();
                await keychain.Clear(host, false);

                return(new LoginResultData(LoginResultCodes.Failed, message, host));
            }
            catch (Exception e)
            {
                logger.Warning(e, "Login Exception");

                // Some enterprise instances don't support OAUTH, so fall back to using the
                // supplied password - on instances that don't support OAUTH the user should
                // be using a personal access token as the password.
                if (EnterpriseWorkaround(host, e))
                {
                    auth = new ApplicationAuthorization(password);
                }
                else
                {
                    await keychain.Clear(host, false);

                    return(new LoginResultData(LoginResultCodes.Failed, Localization.LoginFailed, host));
                }
            }

            keychain.SetToken(host, auth.Token);
            await keychain.Save(host);

            return(new LoginResultData(LoginResultCodes.Success, "Success", host));
        }
示例#2
0
        /// <inheritdoc/>
        public async Task Logout(UriString hostAddress)
        {
            Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));

            await new ActionTask(keychain.Clear(hostAddress, true)).StartAwait();
        }
示例#3
0
 internal LoginResultData(LoginResultCodes code, string message, UriString host)
     : this(code, message, null, host, null)
 {
 }
示例#4
0
        public IKeychainAdapter Connect(UriString host)
        {
            Guard.ArgumentNotNull(host, nameof(host));

            return(FindOrCreateAdapter(host));
        }
示例#5
0
 public static bool IsGitHubDotCom(UriString hostUri)
 {
     return(hostUri.Host == GitHubDotComHostAddress.WebUri.Host ||
            hostUri.Host == GitHubDotComHostAddress.ApiUri.Host ||
            hostUri.Host == gistUri.Host);
 }
示例#6
0
文件: ApiClient.cs 项目: lin5/Unity
 public async Task Logout(UriString host)
 {
     await LogoutInternal(host);
 }
示例#7
0
文件: ApiClient.cs 项目: lin5/Unity
 private async Task LogoutInternal(UriString host)
 {
     await loginManager.Logout(host);
 }
示例#8
0
 /// <inheritdoc/>
 public ITask Logout(UriString hostAddress)
 {
     Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
     return(taskManager.Run(() => keychain.Clear(hostAddress, true), "Signing out"));
 }
示例#9
0
 public ITask Logout(UriString host)
 {
     return(loginManager.Logout(host));
 }
示例#10
0
 public IKeychainAdapter Connect(UriString host)
 {
     return(FindOrCreateAdapter(host));
 }
示例#11
0
        public static bool Download(ILogging logger, UriString url,
                                    Stream destinationStream,
                                    Func <long, long, bool> onProgress)
        {
            long bytes = destinationStream.Length;

            var expectingResume = bytes > 0;

            var webRequest = (HttpWebRequest)WebRequest.Create(url);

            if (expectingResume)
            {
                // classlib for 3.5 doesn't take long overloads...
                webRequest.AddRange((int)bytes);
            }

            webRequest.Method  = "GET";
            webRequest.Timeout = ApplicationConfiguration.WebTimeout;

            if (expectingResume)
            {
                logger.Trace($"Resuming download of {url}");
            }
            else
            {
                logger.Trace($"Downloading {url}");
            }

            if (!onProgress(bytes, bytes * 2))
            {
                return(false);
            }

            using (var webResponse = (HttpWebResponse)webRequest.GetResponseWithoutException())
            {
                var httpStatusCode = webResponse.StatusCode;
                logger.Trace($"Downloading {url} StatusCode:{(int)webResponse.StatusCode}");

                if (expectingResume && httpStatusCode == HttpStatusCode.RequestedRangeNotSatisfiable)
                {
                    return(!onProgress(bytes, bytes));
                }

                if (!(httpStatusCode == HttpStatusCode.OK || httpStatusCode == HttpStatusCode.PartialContent))
                {
                    return(false);
                }

                if (expectingResume && httpStatusCode == HttpStatusCode.OK)
                {
                    expectingResume = false;
                    destinationStream.Seek(0, SeekOrigin.Begin);
                }

                var responseLength = webResponse.ContentLength;
                if (expectingResume)
                {
                    if (!onProgress(bytes, bytes + responseLength))
                    {
                        return(false);
                    }
                }

                using (var responseStream = webResponse.GetResponseStream())
                {
                    return(Utils.Copy(responseStream, destinationStream, responseLength,
                                      progress: (totalRead, timeToFinish) =>
                    {
                        return onProgress(totalRead, responseLength);
                    }));
                }
            }
        }
示例#12
0
 public DownloadData(UriString url, NPath file)
 {
     this.Url  = url;
     this.File = file;
 }
示例#13
0
        private void GoToProfile(object obj)
        {
            var uriString = new UriString(connection.Host).Combine(connection.Username);

            Application.OpenURL(uriString);
        }
示例#14
0
        private void MaybeUpdateData()
        {
            UriString host = null;

            if (!HasRepository || String.IsNullOrEmpty(Repository.CloneUrl))
            {
                var firstConnection = Platform.Keychain.Connections.FirstOrDefault();
                if (firstConnection != null)
                {
                    host = firstConnection.Host;
                }
                else
                {
                    host = UriString.ToUriString(HostAddress.GitHubDotComHostAddress.WebUri);
                }
            }
            else
            {
                host = new UriString(Repository.CloneUrl.ToRepositoryUri()
                                     .GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
            }

            connection = Platform.Keychain.Connections.FirstOrDefault(x => x.Host.ToUriString() == host);

            if (repositoryProgressHasUpdate)
            {
                if (repositoryProgress != null)
                {
                    repositoryProgressMessage = repositoryProgress.Message;
                    repositoryProgressValue   = repositoryProgress.Percentage;
                    if (progressMessageClearTime == -1f || progressMessageClearTime < EditorApplication.timeSinceStartup + DefaultNotificationTimeout)
                    {
                        progressMessageClearTime = EditorApplication.timeSinceStartup + DefaultNotificationTimeout;
                    }
                }
                else
                {
                    repositoryProgressMessage = "";
                    repositoryProgressValue   = 0;
                    progressMessageClearTime  = -1f;
                }
                repositoryProgressHasUpdate = false;
            }

            if (appManagerProgressHasUpdate)
            {
                if (appManagerProgress != null)
                {
                    appManagerProgressValue   = appManagerProgress.Percentage;
                    appManagerProgressMessage = appManagerProgress.Message;
                }
                else
                {
                    appManagerProgressValue   = 0;
                    appManagerProgressMessage = "";
                }
                appManagerProgressHasUpdate = false;
            }

            string updatedRepoRemote = null;
            string updatedRepoUrl    = Localization.DefaultRepoUrl;

            var shouldUpdateContentFields = false;

            if (currentTrackingStatusHasUpdate)
            {
                currentTrackingStatusHasUpdate = false;
                statusAhead  = Repository.CurrentAhead;
                statusBehind = Repository.CurrentBehind;
            }

            if (currentStatusEntriesHasUpdate)
            {
                currentStatusEntriesHasUpdate = false;
                var currentChanges = Repository.CurrentChanges;
                hasItemsToCommit = currentChanges != null &&
                                   currentChanges.Any(entry => entry.Status != GitFileStatus.Ignored && !entry.Staged);
            }

            if (currentBranchAndRemoteHasUpdate)
            {
                hasRemote = false;
            }

            if (Repository != null)
            {
                if (currentBranch == null || currentRemoteName == null || currentBranchAndRemoteHasUpdate)
                {
                    currentBranchAndRemoteHasUpdate = false;

                    var    repositoryCurrentBranch = Repository.CurrentBranch;
                    string updatedRepoBranch;
                    if (repositoryCurrentBranch.HasValue)
                    {
                        updatedRepoBranch      = repositoryCurrentBranch.Value.Name;
                        isTrackingRemoteBranch = !string.IsNullOrEmpty(repositoryCurrentBranch.Value.Tracking);
                    }
                    else
                    {
                        updatedRepoBranch      = null;
                        isTrackingRemoteBranch = false;
                    }

                    var repositoryCurrentRemote = Repository.CurrentRemote;
                    if (repositoryCurrentRemote.HasValue)
                    {
                        hasRemote         = true;
                        updatedRepoRemote = repositoryCurrentRemote.Value.Name;
                        if (!string.IsNullOrEmpty(repositoryCurrentRemote.Value.Url))
                        {
                            updatedRepoUrl = repositoryCurrentRemote.Value.Url;
                        }
                    }

                    if (currentRemoteName != updatedRepoRemote)
                    {
                        currentRemoteName         = updatedRepoRemote;
                        shouldUpdateContentFields = true;
                    }

                    if (currentBranch != updatedRepoBranch)
                    {
                        currentBranch             = updatedRepoBranch;
                        shouldUpdateContentFields = true;
                    }

                    if (currentRemoteUrl != updatedRepoUrl)
                    {
                        currentRemoteUrl          = updatedRepoUrl;
                        shouldUpdateContentFields = true;
                    }
                }
            }
            else
            {
                isTrackingRemoteBranch = false;

                if (currentRemoteName != null)
                {
                    currentRemoteName         = null;
                    shouldUpdateContentFields = true;
                }

                if (currentBranch != null)
                {
                    currentBranch             = null;
                    shouldUpdateContentFields = true;
                }

                if (currentRemoteUrl != Localization.DefaultRepoUrl)
                {
                    currentRemoteUrl          = Localization.DefaultRepoUrl;
                    shouldUpdateContentFields = true;
                }
            }

            if (shouldUpdateContentFields || currentBranchContent == null || currentRemoteUrlContent == null)
            {
                currentBranchContent = new GUIContent(currentBranch, Localization.Window_RepoBranchTooltip);

                if (currentRemoteName != null)
                {
                    currentRemoteUrlContent = new GUIContent(currentRemoteUrl, string.Format(Localization.Window_RepoUrlTooltip, currentRemoteName));
                }
                else
                {
                    currentRemoteUrlContent = new GUIContent(currentRemoteUrl, Localization.Window_RepoNoUrlTooltip);
                }
            }
        }