Exemple #1
0
        private LoginResultData TryLogin(
            UriString host,
            string username,
            string password,
            string code = null
            )
        {
            var hasTwoFactorCode = code != null;

            var command = new StringBuilder("login");

            if (hasTwoFactorCode)
            {
                command.Append(" --twoFactor");
            }

            if (!HostAddress.IsGitHubDotCom(host))
            {
                command.Append(" -h ");
                command.Append(host.Host);
            }

            var loginTask = new OctorunTask(taskManager.Token, environment, command.ToString());

            loginTask.Configure(processManager, withInput: true);
            loginTask.OnStartProcess += proc =>
            {
                proc.StandardInput.WriteLine(username);
                proc.StandardInput.WriteLine(password);
                if (hasTwoFactorCode)
                {
                    proc.StandardInput.WriteLine(code);
                }
                proc.StandardInput.Close();
            };

            var ret = loginTask.RunSynchronously();

            if (ret.IsSuccess)
            {
                return(new LoginResultData(LoginResultCodes.Success, null, host, ret.Output[0]));
            }

            if (ret.IsTwoFactorRequired)
            {
                var resultCodes = hasTwoFactorCode ? LoginResultCodes.CodeFailed : LoginResultCodes.CodeRequired;
                var message     = hasTwoFactorCode ? "Incorrect code. Two Factor Required." : "Two Factor Required.";

                return(new LoginResultData(resultCodes, message, host, ret.Output[0]));
            }

            return(new LoginResultData(LoginResultCodes.Failed, ret.GetApiErrorMessage() ?? "Failed.", host));
        }
Exemple #2
0
        bool EnterpriseWorkaround(UriString hostAddress, Exception e)
        {
            // Older Enterprise hosts either don't have the API end-point to PUT an authorization, or they
            // return 422 because they haven't white-listed our client ID. In that case, we just ignore
            // the failure, using basic authentication (with username and password) instead of trying
            // to get an authorization token.
            var apiException = e as ApiException;

            return(!HostAddress.IsGitHubDotCom(hostAddress) &&
                   (e is NotFoundException ||
                    e is ForbiddenException ||
                    apiException?.StatusCode == (HttpStatusCode)422));
        }
Exemple #3
0
        private string RetrieveUsername(string token, UriString host)
        {
            var command     = HostAddress.IsGitHubDotCom(host) ? "validate" : "validate -h " + host.Host;
            var octorunTask = new OctorunTask(taskManager.Token, environment, command, token)
                              .Configure(processManager);

            var validateResult = octorunTask.RunSynchronously();

            if (!validateResult.IsSuccess)
            {
                throw new InvalidOperationException("Authentication validation failed");
            }

            return(validateResult.Output[1]);
        }
Exemple #4
0
        private void MaybeUpdateData()
        {
            if (connectionsNeedLoading)
            {
                connectionsNeedLoading = false;
                connections            = Platform.Keychain.Connections.OrderByDescending(HostAddress.IsGitHubDotCom).ToArray();
                connectionLabels       = connections.Select(c => HostAddress.IsGitHubDotCom(c) ? "GitHub" : c.Host.ToUriString().Host).ToArray();

                var connection = connections.First();
                selectedConnection = 0;
                selectedClient     = GetApiClient(connection);
            }

            if (ownersNeedLoading)
            {
                ownersNeedLoading = false;
                LoadOwners();
            }
        }
Exemple #5
0
        private GitHubUser GetValidatedGitHubUser()
        {
            try
            {
                var adapter = EnsureKeychainAdapter();

                var command     = HostAddress.IsGitHubDotCom() ? "validate" : "validate -h " + HostAddress.ApiUri.Host;
                var octorunTask = new OctorunTask(taskManager.Token, environment, command, adapter.Credential.Token)
                                  .Configure(processManager);

                var ret = octorunTask.RunSynchronously();
                if (ret.IsSuccess)
                {
                    var login = ret.Output[1];

                    if (!string.Equals(login, Connection.Username, StringComparison.InvariantCultureIgnoreCase))
                    {
                        logger.Trace("LoadKeychainInternal: Api username does not match");
                        throw new TokenUsernameMismatchException(Connection.Username, login);
                    }

                    return(new GitHubUser
                    {
                        Name = ret.Output[0],
                        Login = login
                    });
                }

                throw new ApiClientException(ret.GetApiErrorMessage() ?? "Error validating current user");
            }
            catch (KeychainEmptyException)
            {
                logger.Warning("Keychain is empty");
                throw;
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error Getting Current User");
                throw;
            }
        }
Exemple #6
0
        private async Task <Octokit.Repository> GetRepositoryInternal()
        {
            try
            {
                if (owner == null)
                {
                    var ownerLogin     = OriginalUrl.Owner;
                    var repositoryName = OriginalUrl.RepositoryName;

                    if (ownerLogin != null && repositoryName != null)
                    {
                        var repo = await githubClient.Repository.Get(ownerLogin, repositoryName);

                        if (repo != null)
                        {
                            repositoryCache = repo;
                        }
                        owner = ownerLogin;
                    }
                }
            }
            // it'll throw if it's private or an enterprise instance requiring authentication
            catch (ApiException apiex)
            {
                if (!HostAddress.IsGitHubDotCom(OriginalUrl.ToRepositoryUri()))
                {
                    isEnterprise = apiex.IsGitHubApiException();
                }
            }
            catch {}
            finally
            {
                sem.Release();
            }

            return(repositoryCache);
        }
Exemple #7
0
        private void DoAccountDropdown()
        {
            GenericMenu accountMenu = new GenericMenu();

            if (connections.Length == 1)
            {
                var connection = connections.First();
                accountMenu.AddItem(new GUIContent("Go to Profile"), false, GoToProfile, connection);
                accountMenu.AddItem(new GUIContent("Sign out"), false, SignOut, connection);
                accountMenu.AddSeparator("");
                accountMenu.AddItem(new GUIContent("Sign In"), false, SignIn, "sign in");
            }
            else
            {
                for (var index = 0; index < connections.Length; index++)
                {
                    var connection     = connections[index];
                    var isGitHubDotCom = HostAddress.IsGitHubDotCom(connection);

                    string rootPath;
                    if (isGitHubDotCom)
                    {
                        rootPath = "GitHub/";
                    }
                    else
                    {
                        var uriString = connection.Host.ToUriString();
                        rootPath = uriString.Host + "/";
                    }

                    accountMenu.AddItem(new GUIContent(rootPath + "Go to Profile"), false, GoToProfile, connection);
                    accountMenu.AddItem(new GUIContent(rootPath + "Sign out"), false, SignOut, connection);
                }
            }

            accountMenu.ShowAsContext();
        }
Exemple #8
0
        private void MaybeUpdateData()
        {
            if (firstOnGUI)
            {
                titleContent = new GUIContent(Title, Styles.SmallLogo);
            }
            firstOnGUI = false;

            if (HasRepository && !string.IsNullOrEmpty(Repository.CloneUrl))
            {
                var host = Repository.CloneUrl
                           .ToRepositoryUri()
                           .GetComponents(UriComponents.Host, UriFormat.SafeUnescaped);

                connections = Platform.Keychain.Connections.OrderByDescending(x => x.Host == host).ToArray();
            }
            else
            {
                connections = Platform.Keychain.Connections.OrderByDescending(HostAddress.IsGitHubDotCom).ToArray();
            }

            var connectionCount = connections.Length;

            if (connectionCount > 1)
            {
                var connection     = connections.First();
                var isGitHubDotCom = HostAddress.IsGitHubDotCom(connection);

                if (isGitHubDotCom)
                {
                    primaryConnectionUsername = "******" + connection.Username;
                }
                else
                {
                    primaryConnectionUsername = connection.Host + ": " + connection.Username;
                }
            }
            else if (connectionCount == 1)
            {
                primaryConnectionUsername = connections.First().Username;
            }
            else
            {
                primaryConnectionUsername = null;
            }


            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);
                }
            }
        }
Exemple #9
0
        public void CreateRepository(string name, string description, bool isPrivate,
                                     Action <GitHubRepository, Exception> callback, string organization = null)
        {
            Guard.ArgumentNotNull(callback, "callback");

            new FuncTask <GitHubRepository>(taskManager.Token, () =>
            {
                EnsureValidCredentials();

                var command = new StringBuilder("publish");

                if (!HostAddress.IsGitHubDotCom())
                {
                    command.Append(" -h ");
                    command.Append(HostAddress.ApiUri.Host);
                }

                command.Append(" -r \"");
                command.Append(name);
                command.Append("\"");

                if (!string.IsNullOrEmpty(description))
                {
                    command.Append(" -d \"");
                    command.Append(description);
                    command.Append("\"");
                }

                if (!string.IsNullOrEmpty(organization))
                {
                    command.Append(" -o \"");
                    command.Append(organization);
                    command.Append("\"");
                }

                if (isPrivate)
                {
                    command.Append(" -p");
                }

                var adapter = EnsureKeychainAdapter();

                var octorunTask = new OctorunTask(taskManager.Token, environment, command.ToString(), adapter.Credential.Token)
                                  .Configure(processManager);

                var ret = octorunTask.RunSynchronously();
                if (ret.IsSuccess && ret.Output.Length == 2)
                {
                    return(new GitHubRepository
                    {
                        Name = ret.Output[0],
                        CloneUrl = ret.Output[1]
                    });
                }

                throw new ApiClientException(ret.GetApiErrorMessage() ?? "Publish failed");
            })
            .FinallyInUI((success, ex, repository) =>
            {
                if (success)
                {
                    callback(repository, null);
                }
                else
                {
                    logger.Error(ex, "Error creating repository");
                    callback(null, ex);
                }
            })
            .Start();
        }
        public override void InitializeView(IView parent)
        {
            base.InitializeView(parent);
            Title = WindowTitle;
            Size  = viewSize;

            gitHubAuthenticationView           = gitHubAuthenticationView ?? new GitHubAuthenticationView();
            gitHubEnterpriseAuthenticationView = gitHubEnterpriseAuthenticationView ?? new GitHubEnterpriseAuthenticationView();

            try
            {
                OAuthCallbackManager.Start();
            }
            catch (Exception ex)
            {
                Logger.Trace(ex, "Error Starting OAuthCallbackManager");
            }

            gitHubAuthenticationView.InitializeView(this);
            gitHubEnterpriseAuthenticationView.InitializeView(this);

            hasGitHubDotComConnection     = Platform.Keychain.Connections.Any(HostAddress.IsGitHubDotCom);
            hasGitHubEnterpriseConnection = Platform.Keychain.Connections.Any(connection => !HostAddress.IsGitHubDotCom(connection));

            if (hasGitHubDotComConnection)
            {
                changeTab = SubTab.GitHubEnterprise;
                UpdateActiveTab();
            }
        }