Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 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
 
18
namespace Google\Auth\Middleware;
19
 
20
use Google\Auth\FetchAuthTokenInterface;
21
use Psr\Http\Message\RequestInterface;
22
 
23
/**
24
 * AuthTokenMiddleware is a Guzzle Middleware that adds an Authorization header
25
 * provided by an object implementing FetchAuthTokenInterface.
26
 *
27
 * The FetchAuthTokenInterface#fetchAuthToken is used to obtain a hash; one of
28
 * the values value in that hash is added as the authorization header.
29
 *
30
 * Requests will be accessed with the authorization header:
31
 *
32
 * 'Authorization' 'Bearer <value of auth_token>'
33
 */
34
class AuthTokenMiddleware
35
{
36
    /**
37
     * @var callback
38
     */
39
    private $httpHandler;
40
 
41
    /**
42
     * @var FetchAuthTokenInterface
43
     */
44
    private $fetcher;
45
 
46
    /**
47
     * @var callable
48
     */
49
    private $tokenCallback;
50
 
51
    /**
52
     * Creates a new AuthTokenMiddleware.
53
     *
54
     * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token
55
     * @param callable $httpHandler (optional) callback which delivers psr7 request
56
     * @param callable $tokenCallback (optional) function to be called when a new token is fetched.
57
     */
58
    public function __construct(
59
        FetchAuthTokenInterface $fetcher,
60
        callable $httpHandler = null,
61
        callable $tokenCallback = null
62
    ) {
63
        $this->fetcher = $fetcher;
64
        $this->httpHandler = $httpHandler;
65
        $this->tokenCallback = $tokenCallback;
66
    }
67
 
68
    /**
69
     * Updates the request with an Authorization header when auth is 'google_auth'.
70
     *
71
     *   use Google\Auth\Middleware\AuthTokenMiddleware;
72
     *   use Google\Auth\OAuth2;
73
     *   use GuzzleHttp\Client;
74
     *   use GuzzleHttp\HandlerStack;
75
     *
76
     *   $config = [..<oauth config param>.];
77
     *   $oauth2 = new OAuth2($config)
78
     *   $middleware = new AuthTokenMiddleware($oauth2);
79
     *   $stack = HandlerStack::create();
80
     *   $stack->push($middleware);
81
     *
82
     *   $client = new Client([
83
     *       'handler' => $stack,
84
     *       'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
85
     *       'auth' => 'google_auth' // authorize all requests
86
     *   ]);
87
     *
88
     *   $res = $client->get('myproject/taskqueues/myqueue');
89
     *
90
     * @param callable $handler
91
     *
92
     * @return \Closure
93
     */
94
    public function __invoke(callable $handler)
95
    {
96
        return function (RequestInterface $request, array $options) use ($handler) {
97
            // Requests using "auth"="google_auth" will be authorized.
98
            if (!isset($options['auth']) || $options['auth'] !== 'google_auth') {
99
                return $handler($request, $options);
100
            }
101
 
102
            $request = $request->withHeader('Authorization', 'Bearer ' . $this->fetchToken());
103
 
104
            return $handler($request, $options);
105
        };
106
    }
107
 
108
    /**
109
     * Call fetcher to fetch the token.
110
     *
111
     * @return string
112
     */
113
    private function fetchToken()
114
    {
115
        $auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler);
116
 
117
        if (array_key_exists('access_token', $auth_tokens)) {
118
            // notify the callback if applicable
119
            if ($this->tokenCallback) {
120
                call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $auth_tokens['access_token']);
121
            }
122
 
123
            return $auth_tokens['access_token'];
124
        }
125
    }
126
}