Example #1
0
 /**
  * Authenticates the current user for the upcoming API calls.
  */
 private function authenticate()
 {
     try {
         $this->client->authenticate($this->user->token, GitHubClient::AUTH_HTTP_TOKEN);
     } catch (\Exception $e) {
         \Bugsnag::notifyError('Exception', 'GitHub Authentication failed: ' . $e->getMessage());
     }
 }
 /**
  * @param string $apiToken
  */
 public function __construct($apiToken = '')
 {
     $this->apiToken = $apiToken;
     $this->client = new Client();
     if ($apiToken) {
         $this->client->authenticate($apiToken, null, Client::AUTH_HTTP_TOKEN);
     }
 }
Example #3
0
 /**
  * @param string $token
  * @param Client $client
  */
 public function __construct($token = null, Client $client = null)
 {
     $this->client = $client ?: new Client(new CachedHttpClient());
     if ($token) {
         $this->client->authenticate($token, null, Client::AUTH_HTTP_PASSWORD);
     }
     parent::__construct();
 }
 /**
  * @return Client
  */
 public function getGithubClient()
 {
     if (!$this->client) {
         $token = $this->container->getParameter('github')['api']['auth_token'];
         $this->client = new \Github\Client();
         $this->client->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
     }
     return $this->client;
 }
Example #5
0
 /**
  * コンストラクタ
  *
  * アクセストークンを利用して認証する
  *
  * @param string $access_token githubのアクセストークン
  * @param string $repo_owner   リポジトリのオーナー名
  * @param string $repo_name    リポジトリ名
  */
 public function __construct($access_token, $repo_owner, $repo_name)
 {
     $this->client = new \Github\Client();
     $this->client->authenticate($access_token, \Github\Client::AUTH_HTTP_TOKEN);
     $this->repo_owner = $repo_owner;
     $this->repo_name = $repo_name;
     $this->fh_pr = new JsonFile(sprintf(self::PR_SAVE_FILE_PATH_TPL, $repo_owner, $repo_name));
     $this->fh_comment = new JsonFile(sprintf(self::COMMENT_SAVE_FILE_PATH_TPL, $repo_owner, $repo_name));
 }
Example #6
0
 public function login(array $credentials)
 {
     $this->user = $credentials['user'];
     $this->repo = $credentials['repo'];
     $this->client = new Client();
     $this->client->authenticate($credentials['oauth_token'], Client::AUTH_HTTP_TOKEN);
     $this->checkLogin();
     return $this;
 }
 /**
  * @param string|null $accessToken
  * @return Client
  */
 public function createClient($accessToken = null)
 {
     $client = new Client();
     if ($this->token instanceof OAuthToken && null === $accessToken) {
         $client->authenticate($this->token->getAccessToken(), null, Client::AUTH_HTTP_TOKEN);
     } elseif (null !== $accessToken) {
         $client->authenticate($accessToken, null, Client::AUTH_HTTP_TOKEN);
     }
     return $client;
 }
Example #8
0
 public function init()
 {
     parent::init();
     $this->api = new Client();
     if ($this->enterpriseUrl) {
         $this->api->setEnterpriseUrl($this->enterpriseUrl);
     }
     $this->api->authenticate($this->authKey, null, Client::AUTH_URL_TOKEN);
     //$this->repoInfo = $this->api->repository()->show($this->owner, $this->repository);
 }
Example #9
0
 /**
  * @inheritdoc
  */
 public function __construct($token)
 {
     $cacheDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'snipper';
     // @codeCoverageIgnoreStart
     if (!is_dir($cacheDir)) {
         mkdir($cacheDir);
     }
     // @codeCoverageIgnoreEnd
     $this->client = new Client(new CachedHttpClient(['cache_dir' => $cacheDir]));
     $this->client->authenticate($token, Client::AUTH_HTTP_TOKEN);
 }
 /**
  * @return Client
  * @throws InvalidConfigurationException
  */
 protected function getClient()
 {
     if (!$this->client) {
         $this->client = $this->gitHubClientFactory->createClient();
         $token = $this->configProvider->getApiToken();
         if (empty($token)) {
             throw new InvalidConfigurationException('GitHub API token isn\'t set.');
         }
         $this->client->authenticate($token, null, Client::AUTH_URL_TOKEN);
     }
     return $this->client;
 }
Example #11
0
 /**
  * Authenticates github client
  */
 private function authenticateClient()
 {
     $fileName = $_SERVER['HOME'] . '/.gh/.gh.yml';
     if (file_exists($fileName) && ($content = file_get_contents($fileName))) {
         $config = Yaml::parse($content);
         $token = isset($config['parameters']['token']) ? $config['parameters']['token'] : null;
         if (null === $token) {
             return;
         }
         $this->client = new Client();
         $this->client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
         return;
     }
 }
 /**
  * @throws InvalidConfigurationException
  */
 public function authenticate()
 {
     $gitHubAccessToken = (string) Arrays::getValueByPath($this->gitHubSettings, 'contributor.accessToken');
     if (!$gitHubAccessToken) {
         throw new InvalidConfigurationException('The GitHub access token was not configured.', 1439627205);
     }
     $this->gitHubClient->authenticate($gitHubAccessToken, GithubClient::AUTH_HTTP_TOKEN);
     try {
         $userDetails = $this->gitHubClient->currentUser()->show();
         $this->currentUserLogin = $userDetails['login'];
     } catch (RuntimeException $exception) {
         throw new InvalidConfigurationException('It was not possible to authenticate to GitHub: ' . $exception->getMessage(), $exception->getCode());
     }
 }
 public function handleResponse(UserResponseInterface $response, UserService $userService)
 {
     $fields = $response->getResponse();
     $gitHubLogin = $fields['login'];
     $accessToken = $response->getAccessToken();
     $user = $userService->findByGitHubLogin($gitHubLogin);
     if (null === $user) {
         throw new UsernameNotFoundException();
     }
     $oAuthUser = new OAuthUser($user);
     $oAuthUser->addRole('ROLE_GITHUB_USER');
     $oAuthUser->setAccessToken($accessToken);
     if (array_key_exists('name', $fields)) {
         $gitHubName = $fields['name'];
         $oAuthUser->setRealName($gitHubName);
     } else {
         $oAuthUser->setRealName($gitHubLogin);
     }
     $client = new Client();
     $client->setOption('api_version', 'v3');
     $client->authenticate($response->getAccessToken(), Client::AUTH_HTTP_TOKEN);
     /* @var \Github\Api\CurrentUser $currentUserApi */
     $currentUserApi = $client->api('current_user');
     $emails = $currentUserApi->emails();
     $allEMails = $emails->all();
     $oAuthUser->setEmail($this->getPrimaryEmailAddress($allEMails));
     return $oAuthUser;
 }
 /**
  * @param  InputInterface  $input
  * @param  OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $changelog = array();
     $client = new Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache')));
     $client->authenticate($input->getArgument("token"), null, Client::AUTH_HTTP_TOKEN);
     $pullRequestAPI = $client->api('pull_request');
     $paginator = new ResultPager($client);
     $parameters = array($input->getArgument("organisation"), $input->getArgument("repository"), array('state' => 'closed'));
     $pullRequests = $paginator->fetchAll($pullRequestAPI, 'all', $parameters);
     $mergedPullRequests = array_filter($pullRequests, function ($pullRequest) {
         return !empty($pullRequest["merged_at"]);
     });
     foreach ($mergedPullRequests as $pullRequest) {
         if (empty($pullRequest['milestone'])) {
             $milestone = "No Milestone Selected";
         } else {
             $milestone = $pullRequest['milestone']['title'] . " / " . strftime("%Y-%m-%d", strtotime($pullRequest['milestone']['due_on']));
         }
         if (!array_key_exists($milestone, $changelog)) {
             $changelog[$milestone] = array();
         }
         $changelog[$milestone][] = $pullRequest;
     }
     uksort($changelog, 'version_compare');
     $changelog = array_reverse($changelog);
     echo "# Changelog";
     foreach ($changelog as $milestone => $pullRequests) {
         echo "\n\n## {$milestone}\n\n";
         foreach ($pullRequests as $pullRequest) {
             echo "* " . $pullRequest['title'] . " [#" . $pullRequest['number'] . "](" . $pullRequest['html_url'] . ") ([@" . $pullRequest['user']['login'] . "](" . $pullRequest['user']['html_url'] . ")) \n";
         }
     }
     //var_dump($changelog);
 }
Example #15
0
 public function showPage()
 {
     if (isset($_POST["register-data"]) && isset($_POST["register-password"])) {
         try {
             $client = new Client();
             $client->authenticate($_POST["register-data"], Client::AUTH_HTTP_TOKEN);
             $user = $client->api('current_user')->show();
             $repos = [];
             foreach ($client->api('current_user')->repositories('member', 'updated', 'desc') as $repo) {
                 $repos[] = ["name" => $repo["full_name"], "isPrivate" => $repo["private"]];
             }
             if (strlen($_POST["register-password"]) >= 6) {
                 Users::createUser($user["login"], $client->api('current_user')->emails()->all()[0], $_POST["register-password"], $_POST["register-data"], $repos);
                 Channels::addChannels($repos);
                 echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["user" => $user])]);
             } else {
                 echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Passwords must be at least 6 characters long."])]);
             }
         } catch (\Exception $e) {
             echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Oh no! Your registration couldn't be completed. Do you already have an account? Is your token valid?"])]);
         }
     } else {
         echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), [])]);
     }
     //echo $this->getTemplateEngine()->render($this->getTemplate(), []);
 }
Example #16
0
 /**
  * Set oauth token (to increase API limit to 5000 per hour, instead of default 60)
  *
  * @param Client $client
  */
 protected function setToken(Client $client)
 {
     $token = getenv('BOWERPHP_TOKEN');
     if (!empty($token)) {
         $client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
     }
 }
Example #17
0
 /**
  * (non-PHPdoc)
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dialog = $this->getHelper('dialog');
     try {
         $client = new Client();
         $username = $input->getOption('username');
         if (!$username) {
             $username = $dialog->ask($output, 'Please enter your GitHub username: '******'password');
         if (!$password) {
             $password = $dialog->askHiddenResponse($output, 'Please enter your GitHub password: ');
         }
         $client->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
         $forkService = $this->getForkService($input, $client);
         $forkedRepositoryList = $forkService->fork();
         $message = $this->formatMessage($forkedRepositoryList);
     } catch (\InvalidArgumentException $exception) {
         $message = $exception->getMessage();
     } catch (GithubRuntimeException $exception) {
         $message = $exception->getMessage();
         $message = "<error>{$message}</error>";
     } finally {
         $output->writeln($message);
     }
 }
Example #18
0
 /**
  * Construct GitSpam instance with its dependencies
  *
  * @param $username
  * @param $password
  *
  * @return GitSpam
  */
 private function setup($username, $password)
 {
     $client = new GithubAPIClient();
     $client->authenticate($username, $password);
     $commitReader = new YouTrackCommitReader();
     $gitSpammer = new GitSpammer($client, $commitReader);
     return $gitSpammer;
 }
Example #19
0
 public static function createClient(SettingsManager $settingsManager)
 {
     $settings = new GeneralSettings();
     $settingsManager->loadSettings($settings);
     $client = new Client();
     $client->authenticate($settings->githubToken, null, Client::AUTH_HTTP_TOKEN);
     return $client;
 }
Example #20
0
 protected function getClient()
 {
     $httpClient = new CachedHttpClient(['cache_dir' => storage_path(config('services.github.cache_url'))]);
     $client = new Client($httpClient);
     //dd($client);
     $client->authenticate(auth()->user()->github_token, 'http_token');
     return $client;
 }
/**
 * Runs pull request validation
 *
 * @param Client $client    GitHub client
 * @param Config $config    Configuration
 * @param array  $arguments Command line arguments
 *
 * @return int              Exit code
 * @throws \InvalidArgumentException
 */
function run(Client $client, Config $config, array $arguments)
{
    $config = $config->getParams();
    $client->authenticate($config['token'], null, Client::AUTH_URL_TOKEN);
    $changeset = new Changeset($client, array_shift($arguments), array_shift($arguments), array_shift($arguments));
    $runner = new Runner();
    return $runner->run($changeset, $arguments);
}
 /**
  * {@inheritdoc}
  */
 public function init(Transport $transportEntity)
 {
     $token = $transportEntity->getSettingsBag()->get('token');
     if (empty($token)) {
         throw new InvalidConfigurationException('GitHub API token isn\'t set.');
     }
     $this->gitHubOrganization = $transportEntity->getSettingsBag()->get('organization');
     if (empty($this->gitHubOrganization)) {
         throw new InvalidConfigurationException('GitHub organization isn\'t set.');
     }
     $this->gitHubRepo = $transportEntity->getSettingsBag()->get('repo');
     if (empty($this->gitHubRepo)) {
         throw new InvalidConfigurationException('GitHub repo isn\'t set.');
     }
     $this->client = $this->gitHubClientFactory->createClient();
     $this->client->authenticate($token, null, Client::AUTH_URL_TOKEN);
     return $this->client;
 }
Example #23
0
 /**
  * Get GitHub API
  *
  * @return Api
  */
 protected function getApi()
 {
     if ($this->api === null) {
         $password = new Password();
         $this->api = new Api();
         $this->api->authenticate($this->getConfig()->getNode('tracker/github/username'), $password->getPassword($this->getTrackerType()));
     }
     return $this->api;
 }
Example #24
0
 /**
  * Create a github client wrapper with automated token-based authentication.
  *
  * @param string $token The API token to authenticate with.
  * @param string $owner The owner name of the github repository.
  * @param string $repo The name of the github repository.
  * @param string $apiUrl The base url to the github API if different from the main github site (i.e., GitHub Enterprise).
  * @return self The github client wrapper, authenticated against the API.
  */
 public static function createWithToken($token, $owner, $repo, $apiUrl = null)
 {
     $client = new Client();
     if ($apiUrl !== null) {
         $client->setOption('base_url', $apiUrl);
     }
     $client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
     return new static($client, $owner, $repo);
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function interact(InputInterface $input, OutputInterface $output)
 {
     $config = parent::interact($input, $output);
     // Do authentication now so we can detect 2fa
     if (self::AUTH_HTTP_PASSWORD === $config['authentication']['http-auth-type']) {
         $client = new Client();
         try {
             $client->authenticate($config['authentication']['username'], $config['authentication']['password-or-token']);
             try {
                 // Make a call to test authentication
                 $client->api('authorizations')->all();
             } catch (TwoFactorAuthenticationRequiredException $e) {
                 // Create a random authorization to make GitHub send the code
                 // We expect an exception, which gets cached by the next catch-block
                 // Note. This authorization is not actually created
                 $client->api('authorizations')->create(['note' => 'Gush on ' . gethostname() . mt_rand(), 'scopes' => ['public_repo']]);
             }
         } catch (TwoFactorAuthenticationRequiredException $e) {
             $isAuthenticated = false;
             $authenticationAttempts = 0;
             $authorization = [];
             $scopes = ['user', 'user:email', 'public_repo', 'repo', 'repo:status', 'read:org'];
             $output->writeln(sprintf('Two factor authentication of type %s is required: ', trim($e->getType())));
             // We already know the password is valid, we just need a valid code
             // Don't want fill in everything again when you know its valid ;)
             while (!$isAuthenticated) {
                 // Prevent endless loop with a broken test
                 if ($authenticationAttempts > 500) {
                     $output->writeln('<error>To many attempts, aborting.</error>');
                     break;
                 }
                 if ($authenticationAttempts > 0) {
                     $output->writeln('<error>Authentication failed please try again.</error>');
                 }
                 try {
                     $code = $this->questionHelper->ask($input, $output, (new Question('Authentication code: '))->setValidator([$this, 'validateNoneEmpty']));
                     // Use a date with time to make sure its unique
                     // Its not possible get existing authorizations, only a new one
                     $time = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d\\TH:i:s');
                     $authorization = $client->api('authorizations')->create(['note' => sprintf('Gush on %s at %s', gethostname(), $time), 'scopes' => $scopes], $code);
                     $isAuthenticated = isset($authorization['token']);
                 } catch (TwoFactorAuthenticationRequiredException $e) {
                     // Noop, continue the loop, try again
                 } catch (\Exception $e) {
                     $output->writeln("<error>{$e->getMessage()}</error>");
                     $output->writeln('');
                 }
                 ++$authenticationAttempts;
             }
             if ($isAuthenticated) {
                 $config['authentication']['http-auth-type'] = self::AUTH_HTTP_TOKEN;
                 $config['authentication']['password-or-token'] = $authorization['token'];
             }
         }
     }
     return $config;
 }
 /**
  * Constructs a new GitHub tracker instance.
  *
  * @param string $username
  * @param string $password
  * @param string $project
  * @param string $owner Optional project owner, e.g. user or organization.
  */
 public function __construct($username, $password, $project, $owner = null)
 {
     $github = new Client();
     $github->setHeaders(array('Authorization: Basic ' . base64_encode("{$username}:{$password}")));
     $github->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
     $this->github = $github->getIssueApi();
     $this->owner = $owner ?: $username;
     $this->project = $project;
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function authenticate()
 {
     $credentials = $this->config['authentication'];
     if (Client::AUTH_HTTP_PASSWORD === $credentials['http-auth-type']) {
         $this->client->authenticate($credentials['username'], $credentials['password-or-token'], $credentials['http-auth-type']);
     } else {
         $this->client->authenticate($credentials['password-or-token'], $credentials['http-auth-type']);
     }
     $this->authenticationType = $credentials['http-auth-type'];
 }
Example #28
0
 public function testAuthenticate()
 {
     $login = '******';
     $secret = 'secret';
     $method = 'method';
     $httpClient = $this->getHttpClientMock();
     $httpClient->expects($this->exactly(2))->method('setOption')->will($this->returnValue($httpClient));
     $client = new Client($httpClient);
     $client->authenticate($login, $secret, $method);
 }
Example #29
0
 /**
  * Register the github client class.
  *
  * @param  \Illuminate\Contracts\Foundation\Application  $app
  * @return void
  */
 protected function registerGithubClient(Application $app)
 {
     $app->singleton('blogit.github.client', function ($app) {
         $cachedHttpClient = $app['blogit.github.cachedHttpClient'];
         $client = new Client($cachedHttpClient);
         $client->authenticate(env('GITHUB_TOKEN'), 'http_token');
         return $client;
     });
     $app->alias('blogit.github.client', Client::class);
 }
Example #30
0
 /**
  *
  */
 private function authenticate()
 {
     if ($this->isAuthenticationAttempted === false) {
         $credentials = $this->settings->getCredentials();
         if (empty($credentials) === false) {
             $credentials = array_replace([null, null, null], $credentials);
             $this->client->authenticate($credentials[1], $credentials[2], $credentials[0]);
         }
         $this->isAuthenticationAttempted = true;
     }
 }