PageRenderTime 33ms CodeModel.GetById 27ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Google/vendor/google/auth/src/Credentials/ServiceAccountCredentials.php

https://gitlab.com/vangtrangbac123/zinkaiuit.tk
PHP | 177 lines | 76 code | 12 blank | 89 comment | 7 complexity | 9b55e4f94b30e1c4f0f62241f88e7640 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\Credentials;
 19
 20use Google\Auth\CredentialsLoader;
 21use Google\Auth\OAuth2;
 22
 23/**
 24 * ServiceAccountCredentials supports authorization using a Google service
 25 * account.
 26 *
 27 * (cf https://developers.google.com/accounts/docs/OAuth2ServiceAccount)
 28 *
 29 * It's initialized using the json key file that's downloadable from developer
 30 * console, which should contain a private_key and client_email fields that it
 31 * uses.
 32 *
 33 * Use it with AuthTokenMiddleware to authorize http requests:
 34 *
 35 *   use Google\Auth\Credentials\ServiceAccountCredentials;
 36 *   use Google\Auth\Middleware\AuthTokenMiddleware;
 37 *   use GuzzleHttp\Client;
 38 *   use GuzzleHttp\HandlerStack;
 39 *
 40 *   $sa = new ServiceAccountCredentials(
 41 *       'https://www.googleapis.com/auth/taskqueue',
 42 *       '/path/to/your/json/key_file.json'
 43 *   );
 44 *   $middleware = new AuthTokenMiddleware($sa);
 45 *   $stack = HandlerStack::create();
 46 *   $stack->push($middleware);
 47 *
 48 *   $client = new Client([
 49 *       'handler' => $stack,
 50 *       'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
 51 *       'auth' => 'google_auth' // authorize all requests
 52 *   ]);
 53 *
 54 *   $res = $client->get('myproject/taskqueues/myqueue');
 55 */
 56class ServiceAccountCredentials extends CredentialsLoader
 57{
 58    /**
 59     * The OAuth2 instance used to conduct authorization.
 60     *
 61     * @var OAuth2
 62     */
 63    protected $auth;
 64
 65    /**
 66     * Create a new ServiceAccountCredentials.
 67     *
 68     * @param string|array $scope the scope of the access request, expressed
 69     *   either as an Array or as a space-delimited String.
 70     * @param string|array $jsonKey JSON credential file path or JSON credentials
 71     *   as an associative array
 72     * @param string $sub an email address account to impersonate, in situations when
 73     *   the service account has been delegated domain wide access.
 74     */
 75    public function __construct(
 76        $scope,
 77        $jsonKey,
 78        $sub = null
 79    ) {
 80        if (is_string($jsonKey)) {
 81            if (!file_exists($jsonKey)) {
 82                throw new \InvalidArgumentException('file does not exist');
 83            }
 84            $jsonKeyStream = file_get_contents($jsonKey);
 85            if (!$jsonKey = json_decode($jsonKeyStream, true)) {
 86                throw new \LogicException('invalid json for auth config');
 87            }
 88        }
 89        if (!array_key_exists('client_email', $jsonKey)) {
 90            throw new \InvalidArgumentException(
 91                'json key is missing the client_email field');
 92        }
 93        if (!array_key_exists('private_key', $jsonKey)) {
 94            throw new \InvalidArgumentException(
 95                'json key is missing the private_key field');
 96        }
 97        $this->auth = new OAuth2([
 98            'audience' => self::TOKEN_CREDENTIAL_URI,
 99            'issuer' => $jsonKey['client_email'],
100            'scope' => $scope,
101            'signingAlgorithm' => 'RS256',
102            'signingKey' => $jsonKey['private_key'],
103            'sub' => $sub,
104            'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI,
105        ]);
106    }
107
108    /**
109     * @param callable $httpHandler
110     *
111     * @return array
112     */
113    public function fetchAuthToken(callable $httpHandler = null)
114    {
115        return $this->auth->fetchAuthToken($httpHandler);
116    }
117
118    /**
119     * @return string
120     */
121    public function getCacheKey()
122    {
123        $key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey();
124        if ($sub = $this->auth->getSub()) {
125            $key .= ':' . $sub;
126        }
127
128        return $key;
129    }
130
131    /**
132     * @return array
133     */
134    public function getLastReceivedToken()
135    {
136        return $this->auth->getLastReceivedToken();
137    }
138
139    /**
140     * Updates metadata with the authorization token.
141     *
142     * @param array $metadata metadata hashmap
143     * @param string $authUri optional auth uri
144     * @param callable $httpHandler callback which delivers psr7 request
145     *
146     * @return array updated metadata hashmap
147     */
148    public function updateMetadata(
149        $metadata,
150        $authUri = null,
151        callable $httpHandler = null
152    ) {
153        // scope exists. use oauth implementation
154        $scope = $this->auth->getScope();
155        if (!is_null($scope)) {
156            return parent::updateMetadata($metadata, $authUri, $httpHandler);
157        }
158
159        // no scope found. create jwt with the auth uri
160        $credJson = array(
161            'private_key' => $this->auth->getSigningKey(),
162            'client_email' => $this->auth->getIssuer(),
163        );
164        $jwtCreds = new ServiceAccountJwtAccessCredentials($credJson);
165
166        return $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler);
167    }
168
169    /**
170     * @param string $sub an email address account to impersonate, in situations when
171     *   the service account has been delegated domain wide access.
172     */
173    public function setSub($sub)
174    {
175        $this->auth->setSub($sub);
176    }
177}