|
| 1 | +<?php |
| 2 | + |
| 3 | +use Google\Auth\CacheInterface; |
| 4 | +use Google\Auth\CredentialsLoader; |
| 5 | +use Google\Auth\HttpHandler\HttpHandlerFactory; |
| 6 | +use Google\Auth\Middleware\AuthTokenMiddleware; |
| 7 | +use Google\Auth\Middleware\ScopedAccessTokenMiddleware; |
| 8 | +use Google\Auth\Middleware\SimpleMiddleware; |
| 9 | +use GuzzleHttp\Client; |
| 10 | +use GuzzleHttp\ClientInterface; |
| 11 | + |
| 12 | +/** |
| 13 | +* |
| 14 | +*/ |
| 15 | +class Google_AuthHandler_Guzzle6AuthHandler |
| 16 | +{ |
| 17 | + protected $cache; |
| 18 | + |
| 19 | + public function __construct(CacheInterface $cache = null) |
| 20 | + { |
| 21 | + $this->cache = $cache; |
| 22 | + } |
| 23 | + |
| 24 | + public function attachCredentials(ClientInterface $http, CredentialsLoader $credentials) |
| 25 | + { |
| 26 | + // if we end up needing to make an HTTP request to retrieve credentials, we |
| 27 | + // can use our existing one, but we need to throw exceptions so the error |
| 28 | + // bubbles up. |
| 29 | + $authHttp = $this->createAuthHttp($http); |
| 30 | + $authHttpHandler = HttpHandlerFactory::build($authHttp); |
| 31 | + $middleware = new AuthTokenMiddleware( |
| 32 | + $credentials, |
| 33 | + [], |
| 34 | + $this->cache, |
| 35 | + $authHttpHandler |
| 36 | + ); |
| 37 | + |
| 38 | + $config = $http->getConfig(); |
| 39 | + $config['handler']->push($middleware); |
| 40 | + $config['auth'] = 'google_auth'; |
| 41 | + $http = new Client($config); |
| 42 | + |
| 43 | + return $http; |
| 44 | + } |
| 45 | + |
| 46 | + public function attachToken(ClientInterface $http, array $token, array $scopes) |
| 47 | + { |
| 48 | + $tokenFunc = function ($scopes) use ($token) { |
| 49 | + return $token['access_token']; |
| 50 | + }; |
| 51 | + |
| 52 | + $middleware = new ScopedAccessTokenMiddleware( |
| 53 | + $tokenFunc, |
| 54 | + $scopes, |
| 55 | + [], |
| 56 | + $this->cache |
| 57 | + ); |
| 58 | + |
| 59 | + $config = $http->getConfig(); |
| 60 | + $config['handler']->push($middleware); |
| 61 | + $config['auth'] = 'scoped'; |
| 62 | + $http = new Client($config); |
| 63 | + |
| 64 | + return $http; |
| 65 | + } |
| 66 | + |
| 67 | + public function attachKey(ClientInterface $http, $key) |
| 68 | + { |
| 69 | + $middleware = new SimpleMiddleware(['key' => $key]); |
| 70 | + |
| 71 | + $config = $http->getConfig(); |
| 72 | + $config['handler']->push($middleware); |
| 73 | + $config['auth'] = 'simple'; |
| 74 | + $http = new Client($config); |
| 75 | + |
| 76 | + return $http; |
| 77 | + } |
| 78 | + |
| 79 | + private function createAuthHttp(ClientInterface $http) |
| 80 | + { |
| 81 | + return new Client( |
| 82 | + [ |
| 83 | + 'base_uri' => $http->getConfig('base_uri'), |
| 84 | + 'exceptions' => true, |
| 85 | + 'verify' => $http->getConfig('verify'), |
| 86 | + 'proxy' => $http->getConfig('proxy'), |
| 87 | + ] |
| 88 | + ); |
| 89 | + } |
| 90 | +} |
0 commit comments