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;
19
 
20
use DomainException;
21
use Google\Auth\Credentials\AppIdentityCredentials;
22
use Google\Auth\Credentials\GCECredentials;
23
use Google\Auth\Middleware\AuthTokenMiddleware;
24
use Google\Auth\Subscriber\AuthTokenSubscriber;
25
use Psr\Cache\CacheItemPoolInterface;
26
 
27
/**
28
 * ApplicationDefaultCredentials obtains the default credentials for
29
 * authorizing a request to a Google service.
30
 *
31
 * Application Default Credentials are described here:
32
 * https://developers.google.com/accounts/docs/application-default-credentials
33
 *
34
 * This class implements the search for the application default credentials as
35
 * described in the link.
36
 *
37
 * It provides three factory methods:
38
 * - #get returns the computed credentials object
39
 * - #getSubscriber returns an AuthTokenSubscriber built from the credentials object
40
 * - #getMiddleware returns an AuthTokenMiddleware built from the credentials object
41
 *
42
 * This allows it to be used as follows with GuzzleHttp\Client:
43
 *
44
 *   use Google\Auth\ApplicationDefaultCredentials;
45
 *   use GuzzleHttp\Client;
46
 *   use GuzzleHttp\HandlerStack;
47
 *
48
 *   $middleware = ApplicationDefaultCredentials::getMiddleware(
49
 *       'https://www.googleapis.com/auth/taskqueue'
50
 *   );
51
 *   $stack = HandlerStack::create();
52
 *   $stack->push($middleware);
53
 *
54
 *   $client = new Client([
55
 *       'handler' => $stack,
56
 *       'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
57
 *       'auth' => 'google_auth' // authorize all requests
58
 *   ]);
59
 *
60
 *   $res = $client->get('myproject/taskqueues/myqueue');
61
 */
62
class ApplicationDefaultCredentials
63
{
64
    /**
65
     * Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface
66
     * implementation to use in this environment.
67
     *
68
     * If supplied, $scope is used to in creating the credentials instance if
69
     * this does not fallback to the compute engine defaults.
70
     *
71
     * @param string|array scope the scope of the access request, expressed
72
     *   either as an Array or as a space-delimited String.
73
     * @param callable $httpHandler callback which delivers psr7 request
74
     * @param array $cacheConfig configuration for the cache when it's present
75
     * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
76
     *
77
     * @return AuthTokenSubscriber
78
     *
79
     * @throws DomainException if no implementation can be obtained.
80
     */
81
    public static function getSubscriber(
82
        $scope = null,
83
        callable $httpHandler = null,
84
        array $cacheConfig = null,
85
        CacheItemPoolInterface $cache = null
86
    ) {
87
        $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
88
 
89
        return new AuthTokenSubscriber($creds, $cacheConfig);
90
    }
91
 
92
    /**
93
     * Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface
94
     * implementation to use in this environment.
95
     *
96
     * If supplied, $scope is used to in creating the credentials instance if
97
     * this does not fallback to the compute engine defaults.
98
     *
99
     * @param string|array scope the scope of the access request, expressed
100
     *   either as an Array or as a space-delimited String.
101
     * @param callable $httpHandler callback which delivers psr7 request
102
     * @param array $cacheConfig configuration for the cache when it's present
103
     * @param CacheItemPoolInterface $cache
104
     *
105
     * @return AuthTokenMiddleware
106
     *
107
     * @throws DomainException if no implementation can be obtained.
108
     */
109
    public static function getMiddleware(
110
        $scope = null,
111
        callable $httpHandler = null,
112
        array $cacheConfig = null,
113
        CacheItemPoolInterface $cache = null
114
    ) {
115
        $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
116
 
117
        return new AuthTokenMiddleware($creds, $cacheConfig);
118
    }
119
 
120
    /**
121
     * Obtains the default FetchAuthTokenInterface implementation to use
122
     * in this environment.
123
     *
124
     * If supplied, $scope is used to in creating the credentials instance if
125
     * this does not fallback to the Compute Engine defaults.
126
     *
127
     * @param string|array scope the scope of the access request, expressed
128
     *   either as an Array or as a space-delimited String.
129
     * @param callable $httpHandler callback which delivers psr7 request
130
     * @param array $cacheConfig configuration for the cache when it's present
131
     * @param CacheItemPoolInterface $cache
132
     *
133
     * @return CredentialsLoader
134
     *
135
     * @throws DomainException if no implementation can be obtained.
136
     */
137
    public static function getCredentials(
138
        $scope = null,
139
        callable $httpHandler = null,
140
        array $cacheConfig = null,
141
        CacheItemPoolInterface $cache = null
142
    ) {
143
        $creds = null;
144
        $jsonKey = CredentialsLoader::fromEnv()
145
            ?: CredentialsLoader::fromWellKnownFile();
146
 
147
        if (!is_null($jsonKey)) {
148
            $creds = CredentialsLoader::makeCredentials($scope, $jsonKey);
149
        } elseif (AppIdentityCredentials::onAppEngine() && !GCECredentials::onAppEngineFlexible()) {
150
            $creds = new AppIdentityCredentials($scope);
151
        } elseif (GCECredentials::onGce($httpHandler)) {
152
            $creds = new GCECredentials();
153
        }
154
 
155
        if (is_null($creds)) {
156
            throw new \DomainException(self::notFound());
157
        }
158
        if (!is_null($cache)) {
159
            $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);
160
        }
161
        return $creds;
162
    }
163
 
164
    private static function notFound()
165
    {
166
        $msg = 'Could not load the default credentials. Browse to ';
167
        $msg .= 'https://developers.google.com';
168
        $msg .= '/accounts/docs/application-default-credentials';
169
        $msg .= ' for more information';
170
 
171
        return $msg;
172
    }
173
}