public function testSettingManualRefreshToken()
 {
     $subscriber = new Oauth2Subscriber();
     $subscriber->setRefreshToken('testRefreshToken');
     $this->assertEquals('refresh_token', $subscriber->getRefreshToken()->getType());
     $this->assertEquals('testRefreshToken', $subscriber->getRefreshToken()->getToken());
 }
Exemple #2
0
 public function auth($code = null)
 {
     $oauth2Client = new GuzzleClient(array('base_url' => $this->baseUrl));
     $config = array('token_url' => 'auth/token', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'redirect_uri' => $this->redirectUri, 'scope' => $this->scope, 'code' => $code);
     $token = new AuthorizationCode($oauth2Client, $config);
     $refreshToken = new RefreshToken($oauth2Client, $config);
     $oauth2 = new Oauth2Subscriber($token, $refreshToken);
     if (isset($this->accessToken)) {
         $oauth2->setAccessToken($this->accessToken);
     }
     $this->accessToken = $oauth2->getAccessToken();
     $client = new GuzzleClient(array('base_url' => $this->baseUrl, 'defaults' => array('auth' => 'oauth2', 'subscribers' => array($oauth2))));
     $this->client = $client;
 }
 /**
  * @Route("/cache", name="homepage-cache")
  */
 public function cacheAction()
 {
     $base_url = 'http://time-api.local';
     $oauth2Client = new Client(['base_url' => $base_url]);
     $config = ['client_id' => '1_2es0ucqqq5es4kcogow84wss8csskgk4gsso0gc444gk8wo8c4', 'client_secret' => '5ur5owi3xfgg8cowkkg4socg8g8w4csgk8gowck40g8s04oo84', 'token_url' => '/oauth/v2/token'];
     $memcached = new \Memcached();
     $memcached->addServer('localhost', 11211);
     $token = new ClientCredentials($oauth2Client, $config);
     $oauth2 = new Oauth2Subscriber($token);
     // Check if we have the cache key
     if (false !== ($cachedAccessToken = $memcached->get(self::ACCESS_TOKEN_CACHE_KEY_PREFIX))) {
         $oauth2->setAccessToken($cachedAccessToken);
     }
     // Update the cache token with the access token
     $memcached->set(self::ACCESS_TOKEN_CACHE_KEY_PREFIX, $oauth2->getAccessToken());
     $client = new Client(['defaults' => ['auth' => 'oauth2', 'subscribers' => [$oauth2]]]);
     $response = $client->get('http://time-api.local/api/time');
     $result = json_decode($response->getBody(), true);
     return new Response(sprintf("Date from the API <br/> Date: %s <br/> Time: %s", $result['date'], $result['time']));
 }
 /**
  * Get an OAuth2 subscriber to add to Guzzle clients.
  *
  * @throws \RuntimeException
  *
  * @return Oauth2Subscriber
  */
 protected function getOauth2Plugin()
 {
     if (!$this->oauth2Plugin) {
         if (!$this->isLoggedIn()) {
             throw new \RuntimeException('Not logged in');
         }
         $options = ['base_url' => $this->config['accounts'], 'defaults' => ['headers' => ['User-Agent' => $this->config['user_agent']], 'debug' => $this->config['debug'], 'verify' => $this->config['verify'], 'proxy' => $this->config['proxy']]];
         $oauth2Client = $this->getOauth2Client($options);
         $refreshTokenGrantType = null;
         if ($this->session->get('refreshToken')) {
             $refreshTokenGrantType = new RefreshToken($oauth2Client, ['client_id' => $this->config['client_id'], 'client_secret' => $this->config['client_secret'], 'refresh_token' => $this->session->get('refreshToken'), 'token_url' => $this->config['token_url']]);
         }
         $this->oauth2Plugin = new Oauth2Subscriber(null, $refreshTokenGrantType);
         if ($this->session->get('accessToken')) {
             $type = $this->session->get('tokenType');
             // If the token does not expire, the 'expires' time must be null.
             $expires = $this->session->get('expires') ?: null;
             $this->oauth2Plugin->setAccessToken($this->session->get('accessToken'), $type, $expires);
         }
     }
     return $this->oauth2Plugin;
 }
Exemple #5
0
 /**
  * @param $url
  * @return bool|void
  * @throws AJXP_UserAlertException
  * @throws Exception
  */
 public static function applyInitPathHook($url)
 {
     if (!class_exists('CommerceGuys\\Guzzle\\Oauth2\\Oauth2Subscriber')) {
         throw new Exception('Oauth plugin not loaded - go to ' . AJXP_BIN_FOLDER . '/guzzle from the command line and run \'composer update\' to install');
     }
     // Repository information
     $urlParts = AJXP_Utils::safeParseUrl($url);
     $repository = ConfService::getRepositoryById($urlParts["host"]);
     if ($repository == null) {
         throw new Exception("Cannot find repository");
     }
     $repositoryId = $repository->getId();
     if (AuthService::usersEnabled()) {
         $u = AuthService::getLoggedUser();
         $userId = $u->getId();
         if ($u->getResolveAsParent()) {
             $userId = $u->getParent();
         }
     } else {
         $userId = 'shared';
     }
     // User information
     // Repository params
     $clientId = $repository->getOption('CLIENT_ID');
     $clientSecret = $repository->getOption('CLIENT_SECRET');
     $scope = $repository->getOption('SCOPE');
     $authUrl = $repository->getOption('AUTH_URL');
     $tokenUrl = $repository->getOption('TOKEN_URL');
     $redirectUrl = $repository->getOption('REDIRECT_URL');
     $authUrl .= '?client_id=' . $clientId . '&scope=' . $scope . '&redirect_uri=' . urlencode($redirectUrl) . '&response_type=code';
     // Retrieving context
     $repoData = self::actualRepositoryWrapperData($urlParts["host"]);
     $repoProtocol = $repoData['protocol'];
     $default = stream_context_get_options(stream_context_get_default());
     // Retrieving subscriber
     $oauth2 = $default[$repoProtocol]['oauth2_subscriber'];
     if (!empty($oauth2)) {
         // Authentication already made for this request - move on
         return true;
     }
     // Retrieving tokens
     $tokensKey = self::getTokenKey($repositoryId, $userId);
     $tokens = self::getTokens($tokensKey);
     $accessToken = $tokens[0];
     $refreshToken = $tokens[1];
     // OAuth 2 Tokens
     $oauth2Client = new GuzzleClient(['base_url' => $tokenUrl]);
     $config = ['client_id' => $clientId, 'client_secret' => $clientSecret, 'scope' => $scope, 'redirect_uri' => $redirectUrl, 'token_url' => '', 'auth_location' => 'body'];
     // Setting up the subscriber
     if (empty($refreshToken) || !empty($_SESSION['oauth_code'])) {
         // Authorization code
         $config['code'] = $_SESSION['oauth_code'];
         $accessToken = new AuthorizationCode($oauth2Client, $config);
         $refreshToken = new RefreshToken($oauth2Client, $config);
         $oauth2 = new Oauth2Subscriber($accessToken, $refreshToken);
         unset($_SESSION['oauth_code']);
     } else {
         // Refresh Token
         $config['refresh_token'] = $refreshToken;
         $oauth2 = new Oauth2Subscriber(null, new RefreshToken($oauth2Client, $config));
         $oauth2->setAccessToken($accessToken);
         $oauth2->setRefreshToken($refreshToken);
     }
     // Retrieving access token and checking access
     try {
         $accessToken = $oauth2->getAccessToken();
         $refreshToken = $oauth2->getRefreshToken();
     } catch (\Exception $e) {
         throw new AJXP_UserAlertException("Please go to <a style=\"text-decoration:underline;\" href=\"" . $authUrl . "\">" . $authUrl . "</a> to authorize the access to your onedrive. Then try again to switch to this workspace");
     }
     // Saving tokens for later use
     self::setTokens($tokensKey, $accessToken->getToken(), $refreshToken->getToken());
     // Saving subscriber in context
     $default[$repoProtocol]['oauth2_subscriber'] = $oauth2;
     // Retrieving client
     $client = $default[$repoProtocol]['client'];
     $httpClient = $client->getHttpClient();
     $httpClient->getEmitter()->attach($oauth2);
     stream_context_set_default($default);
     return true;
 }
 /**
  * Configure the GuzzleHttp\Client with default options.
  */
 public static function configure()
 {
     $config = \BoletoSimples::$configuration;
     $oauth2 = new Oauth2Subscriber();
     $oauth2->setAccessToken($config->access_token);
     self::$client = new Client(['base_url' => $config->baseUri(), 'defaults' => ['headers' => ['User-Agent' => $config->userAgent()], 'auth' => 'oauth2', 'subscribers' => [$oauth2]]]);
     self::$default_options = ['headers' => ['Content-Type' => 'application/json'], 'exceptions' => false];
 }