Skip to content

Commit

Permalink
add support for guzzle 6
Browse files Browse the repository at this point in the history
  • Loading branch information
dwsupplee authored and bshaffer committed Dec 4, 2015
1 parent b2d0e7b commit 22c51e6
Show file tree
Hide file tree
Showing 42 changed files with 2,294 additions and 622 deletions.
8 changes: 5 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ language: php
sudo: false

php:
- 5.4
- 5.5
- 5.6
- hhvm

env:
- FIREBASE_JWT_VERSION=2.0.0
- FIREBASE_JWT_VERSION=3.0.0
- FIREBASE_JWT_VERSION=2.0.0 GUZZLE_VERSION=5.3
- FIREBASE_JWT_VERSION=2.0.0 GUZZLE_VERSION=~6.0
- FIREBASE_JWT_VERSION=3.0.0 GUZZLE_VERSION=5.3
- FIREBASE_JWT_VERSION=3.0.0 GUZZLE_VERSION=~6.0

before_script:
- composer install
- composer require firebase/php-jwt:$FIREBASE_JWT_VERSION
- composer require guzzlehttp/guzzle:$GUZZLE_VERSION

script:
- vendor/bin/phpunit
Expand Down
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,30 +84,33 @@ As long as you update the environment variable below to point to *your* JSON
credentials file, the following code should output a list of your Drive files.

```php
use GuzzleHttp\Client;
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
'handler' => $stack
'base_url' => 'https://www.googleapis.com',
'defaults' => ['auth' => 'google_auth'] // authorize all requests
'auth' => 'google_auth' // authorize all requests
]);

// attach this library's auth listener
$fetcher = ApplicationDefaultCredentials::getFetcher($scopes);
$client->getEmitter()->attach($fetcher);

// make the request
$response = $client->get('drive/v2/files');

// show the result!
print_r($response->json());
print_r((string) $response->getBody());
```

## What about auth in google-apis-php-client?
Expand Down
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
"license": "Apache-2.0",
"require": {
"firebase/php-jwt": "~2.0|~3.0",
"guzzlehttp/guzzle": "5.2.*",
"php": ">=5.4"
"guzzlehttp/guzzle": "5.3|~6.0",
"php": ">=5.5",
"guzzlehttp/psr7": "1.2.*",
"psr/http-message": "1.0.*"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
Expand Down
81 changes: 58 additions & 23 deletions src/ApplicationDefaultCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

namespace Google\Auth;

use GuzzleHttp\Stream\Stream;
use GuzzleHttp\ClientInterface;
use Google\Auth\Credentials\AppIdentityCredentials;
use Google\Auth\Credentials\GCECredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Auth\Subscriber\AuthTokenSubscriber;

/**
* ApplicationDefaultCredentials obtains the default credentials for
Expand All @@ -30,50 +32,83 @@
* This class implements the search for the application default credentials as
* described in the link.
*
* It provides two factory methods:
* It provides three factory methods:
* - #get returns the computed credentials object
* - #getFetcher returns an AuthTokenFetcher built from the credentials object
* - #getSubscriber returns an AuthTokenSubscriber built from the credentials object
* - #getMiddleware returns an AuthTokenMiddleware built from the credentials object
*
* This allows it to be used as follows with GuzzleHttp\Client:
*
* use GuzzleHttp\Client;
* use Google\Auth\ApplicationDefaultCredentials;
* use GuzzleHttp\Client;
* use GuzzleHttp\HandlerStack;
*
* $middleware = ApplicationDefaultCredentials::getMiddleware(
* 'https://www.googleapis.com/auth/taskqueue'
* );
* $stack = HandlerStack::create();
* $stack->push($middleware);
*
* $client = new Client([
* 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'defaults' => ['auth' => 'google_auth'] // authorize all requests
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth' // authorize all requests
* ]);
* $fetcher = ApplicationDefaultCredentials::getFetcher(
* 'https://www.googleapis.com/auth/taskqueue');
* $client->getEmitter()->attach($fetcher);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*/
class ApplicationDefaultCredentials
{
/**
* Obtains an AuthTokenFetcher that uses the default FetchAuthTokenInterface
* Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface
* implementation to use in this environment.
*
* If supplied, $scope is used to in creating the credentials instance if
* this does not fallback to the compute engine defaults.
*
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param callable $httpHandler callback which delivers psr7 request
* @param array $cacheConfig configuration for the cache when it's present
* @param object $cache an implementation of CacheInterface
*
* @throws DomainException if no implementation can be obtained.
*/
public static function getSubscriber(
$scope = null,
callable $httpHandler = null,
array $cacheConfig = null,
CacheInterface $cache = null
) {
$creds = self::getCredentials($scope, $httpHandler);

return new AuthTokenSubscriber($creds, $cacheConfig, $cache, $httpHandler);
}

/**
* Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface
* implementation to use in this environment.
*
* If supplied, $scope is used to in creating the credentials instance if
* this does not fallback to the compute engine defaults.
*
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param $client GuzzleHttp\ClientInterface optional client.
* @param callable $httpHandler callback which delivers psr7 request
* @param cacheConfig configuration for the cache when it's present
* @param object $cache an implementation of CacheInterface
*
* @throws DomainException if no implementation can be obtained.
*/
public static function getFetcher(
$scope = null,
ClientInterface $client = null,
array $cacheConfig = null,
CacheInterface $cache = null)
{
$creds = self::getCredentials($scope, $client);
return new AuthTokenFetcher($creds, $cacheConfig, $cache, $client);
public static function getMiddleware(
$scope = null,
callable $httpHandler = null,
array $cacheConfig = null,
CacheInterface $cache = null
) {
$creds = self::getCredentials($scope, $httpHandler);

return new AuthTokenMiddleware($creds, $cacheConfig, $cache, $httpHandler);
}

/**
Expand All @@ -86,10 +121,10 @@ public static function getFetcher(
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
*
* @param $client GuzzleHttp\ClientInterface optional client.
* @param callable $httpHandler callback which delivers psr7 request
* @throws DomainException if no implementation can be obtained.
*/
public static function getCredentials($scope = null, $client = null)
public static function getCredentials($scope = null, callable $httpHandler = null)
{
$creds = CredentialsLoader::fromEnv($scope);
if (!is_null($creds)) {
Expand All @@ -102,7 +137,7 @@ public static function getCredentials($scope = null, $client = null)
if (AppIdentityCredentials::onAppEngine()) {
return new AppIdentityCredentials($scope);
}
if (GCECredentials::onGce($client)) {
if (GCECredentials::onGce($httpHandler)) {
return new GCECredentials();
}
throw new \DomainException(self::notFound());
Expand Down
3 changes: 1 addition & 2 deletions src/CacheInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,4 @@ public function set($key, $value);
* @param String $key
*/
public function delete($key);

}
}
68 changes: 68 additions & 0 deletions src/CacheTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Auth;

trait CacheTrait
{
/**
* Gets the cached value if it is present in the cache when that is
* available.
*/
private function getCachedValue()
{
if (is_null($this->cache)) {
return null;
}

if (isset($this->fetcher)) {
$fetcherKey = $this->fetcher->getCacheKey();
} else {
$fetcherKey = $this->getCacheKey();
}

if (is_null($fetcherKey)) {
return null;
}

$key = $this->cacheConfig['prefix'] . $fetcherKey;
return $this->cache->get($key, $this->cacheConfig['lifetime']);
}

/**
* Saves the value in the cache when that is available.
*/
private function setCachedValue($v)
{
if (is_null($this->cache)) {
return;
}

if (isset($this->fetcher)) {
$fetcherKey = $this->fetcher->getCacheKey();
} else {
$fetcherKey = $this->getCacheKey();
}

if (is_null($fetcherKey)) {
return;
}
$key = $this->cacheConfig['prefix'] . $fetcherKey;
$this->cache->set($key, $v);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@
* limitations under the License.
*/

namespace Google\Auth;
namespace Google\Auth\Credentials;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Client;
use Google\Auth\CredentialsLoader;

/**
* The AppIdentityService class is automatically defined on App Engine,
Expand All @@ -30,27 +29,26 @@
/**
* AppIdentityCredentials supports authorization on Google App Engine.
*
* It can be used to authorize requests using the AuthTokenFetcher, but will
* only succeed if being run on App Engine:
* It can be used to authorize requests using the AuthTokenMiddleware or
* AuthTokenSubscriber, but will only succeed if being run on App Engine:
*
* use Google\Auth\Credentials\AppIdentityCredentials;
* use Google\Auth\Middleware\AuthTokenMiddleware;
* use GuzzleHttp\Client;
* use Google\Auth\AppIdentityCredentials;
* use Google\Auth\AuthTokenFetcher;
* use GuzzleHttp\HandlerStack;
*
* $gae = new AppIdentityCredentials('https://www.googleapis.com/auth/books');
* $subscriber = new AuthTokenFetcher($gae);
* $middleware = new AuthTokenMiddleware($gae);
* $stack = HandlerStack::create();
* $stack->push($middleware);
*
* $client = new Client([
* 'base_url' => 'https://www.googleapis.com/books/v1',
* 'defaults' => ['auth' => 'google_auth']
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/books/v1',
* 'auth' => 'google_auth'
* ]);
* $client->setDefaultOption('verify', '/etc/ca-certificates.crt');
* $client->getEmitter()->attach($subscriber);
* $res = $client->get('volumes?q=Henry+David+Thoreau&country=US');
*
* In Guzzle 5 and below, the App Engine certificates need to be set on the
* guzzle client in order for SSL requests to succeed.
*
* $client->setDefaultOption('verify', '/etc/ca-certificates.crt');
* $res = $client->get('volumes?q=Henry+David+Thoreau&country=US');
*/
class AppIdentityCredentials extends CredentialsLoader
{
Expand Down Expand Up @@ -80,7 +78,7 @@ public static function onAppEngine()
* As the AppIdentityService uses protobufs to fetch the access token,
* the GuzzleHttp\ClientInterface instance passed in will not be used.
*
* @param $client GuzzleHttp\ClientInterface optional client.
* @param callable $httpHandler callback which delivers psr7 request
* @return array the auth metadata:
* array(2) {
* ["access_token"]=>
Expand All @@ -89,7 +87,7 @@ public static function onAppEngine()
* string(10) "1444339905"
* }
*/
public function fetchAuthToken(ClientInterface $unusedClient = null)
public function fetchAuthToken(callable $httpHandler = null)
{
if (!self::onAppEngine()) {
return array();
Expand Down
Loading

0 comments on commit 22c51e6

Please sign in to comment.