Пример #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));
        }
Пример #2
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]);
        }
Пример #3
0
        public void GetOrganizations(Action <Organization[]> onSuccess, Action <Exception> onError = null)
        {
            Guard.ArgumentNotNull(onSuccess, nameof(onSuccess));
            new FuncTask <Organization[]>(taskManager.Token, () =>
            {
                var adapter = EnsureKeychainAdapter();

                var command     = HostAddress.IsGitHubDotCom() ? "organizations" : "organizations -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 organizations = new List <Organization>();
                    for (var i = 0; i < ret.Output.Length; i = i + 2)
                    {
                        organizations.Add(new Organization
                        {
                            Name  = ret.Output[i],
                            Login = ret.Output[i + 1]
                        });
                    }
                    return(organizations.ToArray());
                }

                throw new ApiClientException(ret.GetApiErrorMessage() ?? "Error getting organizations");
            })
            .FinallyInUI((success, ex, orgs) =>
            {
                if (success)
                {
                    onSuccess(orgs);
                }
                else
                {
                    logger.Error(ex, "Error Getting Organizations");
                    onError?.Invoke(ex);
                }
            })
            .Start();
        }
Пример #4
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;
            }
        }
Пример #5
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();
        }
Пример #6
0
        public void GetEnterpriseServerMeta(Action <GitHubHostMeta> onSuccess, Action <Exception> onError = null)
        {
            Guard.ArgumentNotNull(onSuccess, nameof(onSuccess));
            new FuncTask <GitHubHostMeta>(taskManager.Token, () =>
            {
                var octorunTask = new OctorunTask(taskManager.Token, environment, "meta -h " + HostAddress.ApiUri.Host)
                                  .Configure(processManager);

                var ret = octorunTask.RunSynchronously();
                if (ret.IsSuccess)
                {
                    var deserializeObject = SimpleJson.DeserializeObject <Dictionary <string, object> >(ret.Output[0]);

                    return(new GitHubHostMeta
                    {
                        InstalledVersion = (string)deserializeObject["installed_version"],
                        GithubServicesSha = (string)deserializeObject["github_services_sha"],
                        VerifiablePasswordAuthentication = (bool)deserializeObject["verifiable_password_authentication"]
                    });
                }

                var message = ret.GetApiErrorMessage();

                logger.Trace("Message: {0}", message);

                if (message != null)
                {
                    if (message.Contains("ETIMEDOUT", StringComparison.InvariantCulture))
                    {
                        message = "Connection timed out.";
                    }
                    else if (message.Contains("ECONNREFUSED", StringComparison.InvariantCulture))
                    {
                        message = "Connection refused.";
                    }
                    else if (message.Contains("ENOTFOUND", StringComparison.InvariantCulture))
                    {
                        message = "Address not found.";
                    }
                    else
                    {
                        int httpStatusCode;
                        if (int.TryParse(message, out httpStatusCode))
                        {
                            var httpStatus = ((HttpStatusCode)httpStatusCode).ToString();
                            message        = httpStatusErrorRegex.Replace(httpStatus, " $1");
                        }
                    }
                }
                else
                {
                    message = "Error getting server meta";
                }

                throw new ApiClientException(message);
            })
            .FinallyInUI((success, ex, meta) =>
            {
                if (success)
                {
                    onSuccess(meta);
                }
                else
                {
                    logger.Error(ex, "Error getting server meta");
                    onError?.Invoke(ex);
                }
            })
            .Start();
        }