/** * @param array $config [optional] { * Configuration options. Please see * {@see Google\Cloud\RequestWrapperTrait::setCommonDefaults()} for the other * available options. * * @type callable $authHttpHandler A handler used to deliver Psr7 * requests specifically for authentication. * @type CodecInterface $codec A codec used to encode responses. * @type array $grpcOptions gRPC specific configuration options passed * off to the GAX library. * } */ public function __construct(array $config = []) { $this->setCommonDefaults($config); $config += ['authHttpHandler' => null, 'codec' => new PhpArray(), 'grpcOptions' => []]; $this->authHttpHandler = $config['authHttpHandler'] ?: HttpHandlerFactory::build(); $this->codec = $config['codec']; $this->grpcOptions = $config['grpcOptions']; }
/** * @param array $config [optional] { * Configuration options. Please see * {@see Google\Cloud\RequestWrapperTrait::setCommonDefaults()} for the other * available options. * * @type string $accessToken Access token used to sign requests. * @type callable $authHttpHandler A handler used to deliver Psr7 * requests specifically for authentication. * @type callable $httpHandler A handler used to deliver Psr7 requests. * @type array $httpOptions HTTP client specific configuration options. * @type bool $shouldSignRequest Whether to enable request signing. * } */ public function __construct(array $config = []) { $this->setCommonDefaults($config); $config += ['accessToken' => null, 'authHttpHandler' => null, 'httpHandler' => null, 'httpOptions' => [], 'shouldSignRequest' => true]; $this->accessToken = $config['accessToken']; $this->httpHandler = $config['httpHandler'] ?: HttpHandlerFactory::build(); $this->authHttpHandler = $config['authHttpHandler'] ?: $this->httpHandler; $this->httpOptions = $config['httpOptions']; $this->shouldSignRequest = $config['shouldSignRequest']; }
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials) { // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $subscriber = new AuthTokenSubscriber($credentials, [], $this->cache, $authHttpHandler); $http->setDefaultOption('auth', 'google_auth'); $http->getEmitter()->attach($subscriber); return $http; }
/** * Executes a Psr\Http\Message\RequestInterface * * @param GoogleClient $client * @param RequestInterface $request * @return array decoded result * @throws ServiceException on server side error (ie: not authenticated, * invalid or malformed post body, invalid url) */ public static function doExecute(ClientInterface $client, RequestInterface $request, $expectedClass = null) { try { $httpHandler = HttpHandlerFactory::build($client); $response = $httpHandler($request); } catch (RequestException $e) { // if Guzzle throws an exception, catch it and handle the response if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); } return self::decodeHttpResponse($response, $request, $expectedClass); }
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials) { // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $middleware = new AuthTokenMiddleware($credentials, [], $this->cache, $authHttpHandler); $config = $http->getConfig(); $config['handler']->push($middleware); $config['auth'] = 'google_auth'; $http = new Client($config); return $http; }
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials, callable $tokenCallback = null) { // use the provided cache if ($this->cache) { $credentials = new FetchAuthTokenCache($credentials, $this->cacheConfig, $this->cache); } // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $subscriber = new AuthTokenSubscriber($credentials, $authHttpHandler, $tokenCallback); $http->setDefaultOption('auth', 'google_auth'); $http->getEmitter()->attach($subscriber); return $http; }
/** * Revoke an OAuth2 access token or refresh token. This method will revoke the current access * token, if a token isn't provided. * * @param string|null $token The token (access token or a refresh token) that should be revoked. * @return boolean Returns True if the revocation was successful, otherwise False. */ public function revokeToken(array $token) { if (isset($token['refresh_token'])) { $tokenString = $token['refresh_token']; } else { $tokenString = $token['access_token']; } $body = Psr7\stream_for(http_build_query(array('token' => $tokenString))); $request = new Request('POST', Google_Client::OAUTH2_REVOKE_URI, ['Cache-Control' => 'no-store', 'Content-Type' => 'application/x-www-form-urlencoded'], $body); $httpHandler = HttpHandlerFactory::build($this->http); $response = $httpHandler($request); if ($response->getStatusCode() == 200) { return true; } return false; }
/** * Executes a Psr\Http\Message\RequestInterface * * @param Google_Client $client * @param Psr\Http\Message\RequestInterface $request * @return array decoded result * @throws Google_Service_Exception on server side error (ie: not authenticated, * invalid or malformed post body, invalid url) */ public static function doExecute(ClientInterface $client, RequestInterface $request, $expectedClass = null) { try { $httpHandler = HttpHandlerFactory::build($client); $response = $httpHandler($request); } catch (RequestException $e) { // if Guzzle throws an exception, catch it and handle the response if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); // specific checking for Guzzle 5: convert to PSR7 response if ($response instanceof \GuzzleHttp\Message\ResponseInterface) { $response = new Response($response->getStatusCode(), $response->getHeaders() ?: [], $response->getBody(), $response->getProtocolVersion(), $response->getReasonPhrase()); } } return self::decodeHttpResponse($response, $request, $expectedClass); }
public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials, callable $tokenCallback = null) { // use the provided cache if ($this->cache) { $credentials = new FetchAuthTokenCache($credentials, $this->cacheConfig, $this->cache); } // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $middleware = new AuthTokenMiddleware($credentials, $authHttpHandler, $tokenCallback); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'google_auth'; $http = new Client($config); return $http; }
/** * Implements FetchAuthTokenInterface#fetchAuthToken. * * Fetches the auth tokens from the GCE metadata host if it is available. * If $httpHandler is not specified a the default HttpHandler is used. * * @param callable $httpHandler callback which delivers psr7 request * @return array the response */ public function fetchAuthToken(callable $httpHandler = null) { if (is_null($httpHandler)) { $httpHandler = HttpHandlerFactory::build(); } if (!$this->hasCheckedOnGce) { $this->isOnGce = self::onGce($httpHandler); } if (!$this->isOnGce) { return array(); // return an empty array with no access token } $resp = $httpHandler(new Request('GET', self::getTokenUri(), [self::FLAVOR_HEADER => 'Google'])); $body = (string) $resp->getBody(); // Assume it's JSON; if it's not throw an exception if (null === ($json = json_decode($body, true))) { throw new \Exception('Invalid JSON response'); } // store this so we can retrieve it later $this->lastReceivedToken = $json; $this->lastReceivedToken['expires_at'] = time() + $json['expires_in']; return $json; }
public function testBuildsGuzzle6Handler() { $this->onlyGuzzle6(); $handler = HttpHandlerFactory::build(); $this->assertInstanceOf('Google\\Auth\\HttpHandler\\Guzzle6HttpHandler', $handler); }
/** * Fetches a fresh OAuth 2.0 access token with the given refresh token. * @param string $refreshToken * @return array access token */ public function fetchAccessTokenWithRefreshToken($refreshToken = null) { if (is_null($refreshToken)) { if (!isset($this->token['refresh_token'])) { throw new LogicException('refresh token must be passed in or set as part of setAccessToken'); } $refreshToken = $this->token['refresh_token']; } $this->getLogger()->info('OAuth2 access token refresh'); $auth = $this->getOAuth2Service(); $auth->setRefreshToken($refreshToken); $httpHandler = HttpHandlerFactory::build($this->getHttpClient()); $creds = $auth->fetchAuthToken($httpHandler); if ($creds && isset($creds['access_token'])) { $creds['created'] = time(); $this->setAccessToken($creds); } return $creds; }
/** * Fetches the auth tokens based on the current state. * * @param callable $httpHandler callback which delivers psr7 request * * @return array the response */ public function fetchAuthToken(callable $httpHandler = null) { if (is_null($httpHandler)) { $httpHandler = HttpHandlerFactory::build(); } $response = $httpHandler($this->generateCredentialsRequest()); $credentials = $this->parseTokenResponse($response); $this->updateToken($credentials); return $credentials; }
/** * Resolves configuration options. * * @param array $config * @return array */ private function resolveConfig(array $config) { if (!isset($config['httpHandler'])) { $config['httpHandler'] = HttpHandlerFactory::build(); } return $config; }
/** * @param array $options [optional] { * Configuration options. * * @type string $accessToken Access token used to sign requests. * @type callable $authHttpHandler A handler used to deliver Psr7 * requests specifically for authentication. * @type callable $httpHandler A handler used to deliver Psr7 requests. * @type string $keyFile The contents of the service account * credentials .json file retrieved from the Google Developers * Console. * @type array $httpOptions HTTP client specific configuration options. * @type int $retries Number of retries for a failed request. * **Defaults to** `3`. * @type array $scopes Scopes to be used for the request. * @type boolean $shouldSignRequest Whether to enable request signing. * } */ public function __construct(array $config = []) { $config += ['accessToken' => null, 'authHttpHandler' => null, 'credentialsFetcher' => null, 'httpHandler' => null, 'httpOptions' => [], 'keyFile' => null, 'retries' => null, 'scopes' => null, 'shouldSignRequest' => true]; if ($config['credentialsFetcher'] && !$config['credentialsFetcher'] instanceof FetchAuthTokenInterface) { throw new \InvalidArgumentException('credentialsFetcher must implement FetchAuthTokenInterface.'); } $this->accessToken = $config['accessToken']; $this->credentialsFetcher = $config['credentialsFetcher']; $this->httpHandler = $config['httpHandler'] ?: HttpHandlerFactory::build(); $this->authHttpHandler = $config['authHttpHandler'] ?: $this->httpHandler; $this->httpOptions = $config['httpOptions']; $this->retries = $config['retries']; $this->scopes = $config['scopes']; $this->keyFile = $config['keyFile']; $this->shouldSignRequest = $config['shouldSignRequest']; }
public function __construct() { // call parent constructor parent::__construct(); // create the asyncronous curl handler $this->handler = new CurlMultiHandler(); $httpClient = new Client(['handler' => HandlerStack::create($this->handler)]); // have the request wrapper call guzzle asyncronously $this->setRequestWrapper(new RequestWrapper(['scopes' => PubSubClient::FULL_CONTROL_SCOPE, 'httpHandler' => function ($request, $options = []) use($httpClient) { return $httpClient->sendAsync($request, $options); }, 'authHttpHandler' => HttpHandlerFactory::build()])); }