Beispiel #1
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;
            }
        }
Beispiel #2
0
        public void GetOrganizations(Action <Organization[]> onSuccess, Action <Exception> onError = null)
        {
            Guard.ArgumentNotNull(onSuccess, nameof(onSuccess));
            new FuncTask <Organization[]>(taskManager.Token, () =>
            {
                var octorunTask = new OctorunTask(taskManager.Token, keychain, environment,
                                                  "organizations")
                                  .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();
        }
Beispiel #3
0
        private async Task <GitHubUser> GetValidatedGitHubUser(Connection keychainConnection, IKeychainAdapter keychainAdapter)
        {
            try
            {
                var octorunTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath, octorunScriptPath, "validate",
                                                  user: keychainConnection.Username, userToken: keychainAdapter.Credential.Token)
                                  .Configure(processManager);

                var ret = await octorunTask.StartAsAsync();

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

                    if (login != keychainConnection.Username)
                    {
                        logger.Trace("LoadKeychainInternal: Api username does not match");
                        throw new TokenUsernameMismatchException(keychainConnection.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;
            }
        }
Beispiel #4
0
        private async Task GetOrganizationInternal(Action <Organization[]> onSuccess, Action <Exception> onError = null)
        {
            try
            {
                logger.Trace("Getting Organizations");

                var user = await GetCurrentUser();

                var keychainAdapter = keychain.Connect(OriginalUrl);

                var octorunTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath, octorunScriptPath, "organizations",
                                                  user: user.Login, userToken: keychainAdapter.Credential.Token)
                                  .Configure(processManager);

                var ret = await octorunTask.StartAsAsync();

                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]
                        });
                    }

                    onSuccess(organizations.ToArray());
                    return;
                }

                throw new ApiClientException(ret.GetApiErrorMessage() ?? "Error getting organizations");
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error Getting Organizations");
                onError?.Invoke(ex);
            }
        }
Beispiel #5
0
        private GitHubUser GetValidatedGitHubUser(Connection keychainConnection, IKeychainAdapter keychainAdapter)
        {
            try
            {
                var octorunTask = new OctorunTask(taskManager.Token, keychain, environment, "validate")
                                  .Configure(processManager);

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

                    if (login != keychainConnection.Username)
                    {
                        logger.Trace("LoadKeychainInternal: Api username does not match");
                        throw new TokenUsernameMismatchException(keychainConnection.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;
            }
        }
Beispiel #6
0
        public void CreateOAuthToken(string code, Action <bool, string> result)
        {
            var command     = "token -h " + HostAddress.WebUri.Host;
            var octorunTask = new OctorunTask(taskManager.Token, environment, command, code)
                              .Configure(processManager);

            octorunTask
            .Then((b, octorunResult) =>
            {
                if (b && octorunResult.IsSuccess)
                {
                    var first = octorunResult.Output.FirstOrDefault();
                    if (first == null)
                    {
                        result(false, "Error validating token.");
                        return;
                    }

                    var match = accessTokenRegex.Match(first);
                    if (match.Success)
                    {
                        var token = match.Groups[1].Value;
                        LoginWithToken(token, b1 => result(b1, "Error validating token."));
                    }
                    else
                    {
                        result(false, octorunResult.Output.FirstOrDefault());
                    }
                }
                else
                {
                    result(false, octorunResult.Output.FirstOrDefault());
                }
            })
            .Catch(exception => result(false, exception.ToString()))
            .Start();
        }
Beispiel #7
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, () =>
            {
                // this validates the user, again
                GetCurrentUser();

                var command = new StringBuilder("publish -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 octorunTask = new OctorunTask(taskManager.Token, keychain, environment, command.ToString())
                                  .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();
        }
Beispiel #8
0
        private async Task <LoginResultData> TryLogin(
            UriString host,
            string username,
            string password,
            string code = null
            )
        {
            if (!nodeJsExecutablePath.HasValue)
            {
                throw new InvalidOperationException("nodeJsExecutablePath must be set");
            }

            if (!octorunScript.HasValue)
            {
                throw new InvalidOperationException("octorunScript must be set");
            }

            var hasTwoFactorCode = code != null;

            var arguments = hasTwoFactorCode ? "login --twoFactor" : "login";
            var loginTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath.Value, octorunScript.Value,
                                            arguments, ApplicationInfo.ClientId, ApplicationInfo.ClientSecret);

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

            var ret = await loginTask.StartAwait();

            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]));
            }

            if (ret.IsBadCredentials)
            {
                return(new LoginResultData(LoginResultCodes.Failed, "Bad credentials.", host, ret.Output[0]));
            }

            if (ret.IsLocked)
            {
                return(new LoginResultData(LoginResultCodes.LockedOut, "Account locked.", host, ret.Output[0]));
            }

            if (ret.Output.Any())
            {
                return(new LoginResultData(LoginResultCodes.Failed, "Failed.", host, ret.Output[0]));
            }

            return(new LoginResultData(LoginResultCodes.Failed, "Failed.", host));
        }
Beispiel #9
0
        private async Task <GitHubRepository> CreateRepositoryInternal(string repositoryName, string organization, string description, bool isPrivate)
        {
            try
            {
                logger.Trace("Creating repository");

                await ValidateKeychain();
                await ValidateCurrentUserInternal();

                var uriString       = keychain.Connections.First().Host;
                var keychainAdapter = await keychain.Load(uriString);

                var command = new StringBuilder("publish -r \"");
                command.Append(repositoryName);
                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 octorunTask = new OctorunTask(taskManager.Token, nodeJsExecutablePath, octorunScriptPath, command.ToString(),
                                                  user: keychainAdapter.Credential.Username, userToken: keychainAdapter.Credential.Token)
                                  .Configure(processManager);

                var ret = await octorunTask.StartAwait();

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

                if (ret.Output.Any())
                {
                    throw new ApiClientException(string.Join(Environment.NewLine, ret.Output));
                }

                throw new ApiClientException("Publish failed");
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error Creating Repository");
                throw;
            }
        }
Beispiel #10
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();
        }