/library/Google/vendor/google/auth/src/Middleware/ScopedAccessTokenMiddleware.php

https://gitlab.com/vangtrangbac123/zinkaiuit.tk · PHP · 175 lines · 65 code · 20 blank · 90 comment · 7 complexity · bde3281cd9f0dabf544a9996a241ad2b MD5 · raw file

  1. <?php
  2. /*
  3. * Copyright 2015 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Auth\Middleware;
  18. use Google\Auth\CacheTrait;
  19. use Psr\Cache\CacheItemPoolInterface;
  20. use Psr\Http\Message\RequestInterface;
  21. /**
  22. * ScopedAccessTokenMiddleware is a Guzzle Middleware that adds an Authorization
  23. * header provided by a closure.
  24. *
  25. * The closure returns an access token, taking the scope, either a single
  26. * string or an array of strings, as its value. If provided, a cache will be
  27. * used to preserve the access token for a given lifetime.
  28. *
  29. * Requests will be accessed with the authorization header:
  30. *
  31. * 'authorization' 'Bearer <value of auth_token>'
  32. */
  33. class ScopedAccessTokenMiddleware
  34. {
  35. use CacheTrait;
  36. const DEFAULT_CACHE_LIFETIME = 1500;
  37. /**
  38. * @var CacheItemPoolInterface
  39. */
  40. private $cache;
  41. /**
  42. * @var array configuration
  43. */
  44. private $cacheConfig;
  45. /**
  46. * @var callable
  47. */
  48. private $tokenFunc;
  49. /**
  50. * @var array|string
  51. */
  52. private $scopes;
  53. /**
  54. * Creates a new ScopedAccessTokenMiddleware.
  55. *
  56. * @param callable $tokenFunc a token generator function
  57. * @param array|string $scopes the token authentication scopes
  58. * @param array $cacheConfig configuration for the cache when it's present
  59. * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
  60. */
  61. public function __construct(
  62. callable $tokenFunc,
  63. $scopes,
  64. array $cacheConfig = null,
  65. CacheItemPoolInterface $cache = null
  66. ) {
  67. $this->tokenFunc = $tokenFunc;
  68. if (!(is_string($scopes) || is_array($scopes))) {
  69. throw new \InvalidArgumentException(
  70. 'wants scope should be string or array');
  71. }
  72. $this->scopes = $scopes;
  73. if (!is_null($cache)) {
  74. $this->cache = $cache;
  75. $this->cacheConfig = array_merge([
  76. 'lifetime' => self::DEFAULT_CACHE_LIFETIME,
  77. 'prefix' => '',
  78. ], $cacheConfig);
  79. }
  80. }
  81. /**
  82. * Updates the request with an Authorization header when auth is 'scoped'.
  83. *
  84. * E.g this could be used to authenticate using the AppEngine
  85. * AppIdentityService.
  86. *
  87. * use google\appengine\api\app_identity\AppIdentityService;
  88. * use Google\Auth\Middleware\ScopedAccessTokenMiddleware;
  89. * use GuzzleHttp\Client;
  90. * use GuzzleHttp\HandlerStack;
  91. *
  92. * $scope = 'https://www.googleapis.com/auth/taskqueue'
  93. * $middleware = new ScopedAccessTokenMiddleware(
  94. * 'AppIdentityService::getAccessToken',
  95. * $scope,
  96. * [ 'prefix' => 'Google\Auth\ScopedAccessToken::' ],
  97. * $cache = new Memcache()
  98. * );
  99. * $stack = HandlerStack::create();
  100. * $stack->push($middleware);
  101. *
  102. * $client = new Client([
  103. * 'handler' => $stack,
  104. * 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
  105. * 'auth' => 'google_auth' // authorize all requests
  106. * ]);
  107. *
  108. * $res = $client->get('myproject/taskqueues/myqueue');
  109. *
  110. * @param callable $handler
  111. *
  112. * @return \Closure
  113. */
  114. public function __invoke(callable $handler)
  115. {
  116. return function (RequestInterface $request, array $options) use ($handler) {
  117. // Requests using "auth"="scoped" will be authorized.
  118. if (!isset($options['auth']) || $options['auth'] !== 'scoped') {
  119. return $handler($request, $options);
  120. }
  121. $request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
  122. return $handler($request, $options);
  123. };
  124. }
  125. /**
  126. * @return string
  127. */
  128. private function getCacheKey()
  129. {
  130. $key = null;
  131. if (is_string($this->scopes)) {
  132. $key .= $this->scopes;
  133. } elseif (is_array($this->scopes)) {
  134. $key .= implode(':', $this->scopes);
  135. }
  136. return $key;
  137. }
  138. /**
  139. * Determine if token is available in the cache, if not call tokenFunc to
  140. * fetch it.
  141. *
  142. * @return string
  143. */
  144. private function fetchToken()
  145. {
  146. $cacheKey = $this->getCacheKey();
  147. $cached = $this->getCachedValue($cacheKey);
  148. if (!empty($cached)) {
  149. return $cached;
  150. }
  151. $token = call_user_func($this->tokenFunc, $this->scopes);
  152. $this->setCachedValue($cacheKey, $token);
  153. return $token;
  154. }
  155. }