PageRenderTime 48ms CodeModel.GetById 33ms app.highlight 8ms RepoModel.GetById 2ms app.codeStats 0ms

/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
 18namespace Google\Auth\Middleware;
 19
 20use Google\Auth\CacheTrait;
 21use Psr\Cache\CacheItemPoolInterface;
 22use Psr\Http\Message\RequestInterface;
 23
 24/**
 25 * ScopedAccessTokenMiddleware is a Guzzle Middleware that adds an Authorization
 26 * header provided by a closure.
 27 *
 28 * The closure returns an access token, taking the scope, either a single
 29 * string or an array of strings, as its value.  If provided, a cache will be
 30 * used to preserve the access token for a given lifetime.
 31 *
 32 * Requests will be accessed with the authorization header:
 33 *
 34 * 'authorization' 'Bearer <value of auth_token>'
 35 */
 36class ScopedAccessTokenMiddleware
 37{
 38    use CacheTrait;
 39
 40    const DEFAULT_CACHE_LIFETIME = 1500;
 41
 42    /**
 43     * @var CacheItemPoolInterface
 44     */
 45    private $cache;
 46
 47    /**
 48     * @var array configuration
 49     */
 50    private $cacheConfig;
 51
 52    /**
 53     * @var callable
 54     */
 55    private $tokenFunc;
 56
 57    /**
 58     * @var array|string
 59     */
 60    private $scopes;
 61
 62    /**
 63     * Creates a new ScopedAccessTokenMiddleware.
 64     *
 65     * @param callable $tokenFunc a token generator function
 66     * @param array|string $scopes the token authentication scopes
 67     * @param array $cacheConfig configuration for the cache when it's present
 68     * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
 69     */
 70    public function __construct(
 71        callable $tokenFunc,
 72        $scopes,
 73        array $cacheConfig = null,
 74        CacheItemPoolInterface $cache = null
 75    ) {
 76        $this->tokenFunc = $tokenFunc;
 77        if (!(is_string($scopes) || is_array($scopes))) {
 78            throw new \InvalidArgumentException(
 79                'wants scope should be string or array');
 80        }
 81        $this->scopes = $scopes;
 82
 83        if (!is_null($cache)) {
 84            $this->cache = $cache;
 85            $this->cacheConfig = array_merge([
 86                'lifetime' => self::DEFAULT_CACHE_LIFETIME,
 87                'prefix' => '',
 88            ], $cacheConfig);
 89        }
 90    }
 91
 92    /**
 93     * Updates the request with an Authorization header when auth is 'scoped'.
 94     *
 95     *   E.g this could be used to authenticate using the AppEngine
 96     *   AppIdentityService.
 97     *
 98     *   use google\appengine\api\app_identity\AppIdentityService;
 99     *   use Google\Auth\Middleware\ScopedAccessTokenMiddleware;
100     *   use GuzzleHttp\Client;
101     *   use GuzzleHttp\HandlerStack;
102     *
103     *   $scope = 'https://www.googleapis.com/auth/taskqueue'
104     *   $middleware = new ScopedAccessTokenMiddleware(
105     *       'AppIdentityService::getAccessToken',
106     *       $scope,
107     *       [ 'prefix' => 'Google\Auth\ScopedAccessToken::' ],
108     *       $cache = new Memcache()
109     *   );
110     *   $stack = HandlerStack::create();
111     *   $stack->push($middleware);
112     *
113     *   $client = new Client([
114     *       'handler' => $stack,
115     *       'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
116     *       'auth' => 'google_auth' // authorize all requests
117     *   ]);
118     *
119     *   $res = $client->get('myproject/taskqueues/myqueue');
120     *
121     * @param callable $handler
122     *
123     * @return \Closure
124     */
125    public function __invoke(callable $handler)
126    {
127        return function (RequestInterface $request, array $options) use ($handler) {
128            // Requests using "auth"="scoped" will be authorized.
129            if (!isset($options['auth']) || $options['auth'] !== 'scoped') {
130                return $handler($request, $options);
131            }
132
133            $request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
134
135            return $handler($request, $options);
136        };
137    }
138
139    /**
140     * @return string
141     */
142    private function getCacheKey()
143    {
144        $key = null;
145
146        if (is_string($this->scopes)) {
147            $key .= $this->scopes;
148        } elseif (is_array($this->scopes)) {
149            $key .= implode(':', $this->scopes);
150        }
151
152        return $key;
153    }
154
155    /**
156     * Determine if token is available in the cache, if not call tokenFunc to
157     * fetch it.
158     *
159     * @return string
160     */
161    private function fetchToken()
162    {
163        $cacheKey = $this->getCacheKey();
164        $cached = $this->getCachedValue($cacheKey);
165
166        if (!empty($cached)) {
167            return $cached;
168        }
169
170        $token = call_user_func($this->tokenFunc, $this->scopes);
171        $this->setCachedValue($cacheKey, $token);
172
173        return $token;
174    }
175}