[ Index ]

PHP Cross Reference of phpBB-3.1.12-deutsch

title

Body

[close]

/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/ -> AbstractService.php (source)

   1  <?php
   2  
   3  namespace OAuth\OAuth2\Service;
   4  
   5  use OAuth\Common\Consumer\CredentialsInterface;
   6  use OAuth\Common\Exception\Exception;
   7  use OAuth\Common\Service\AbstractService as BaseAbstractService;
   8  use OAuth\Common\Storage\TokenStorageInterface;
   9  use OAuth\Common\Http\Exception\TokenResponseException;
  10  use OAuth\Common\Http\Client\ClientInterface;
  11  use OAuth\Common\Http\Uri\UriInterface;
  12  use OAuth\OAuth2\Service\Exception\InvalidScopeException;
  13  use OAuth\OAuth2\Service\Exception\MissingRefreshTokenException;
  14  use OAuth\Common\Token\TokenInterface;
  15  use OAuth\Common\Token\Exception\ExpiredTokenException;
  16  
  17  abstract class AbstractService extends BaseAbstractService implements ServiceInterface
  18  {
  19      /** @const OAUTH_VERSION */
  20      const OAUTH_VERSION = 2;
  21  
  22      /** @var array */
  23      protected $scopes;
  24  
  25      /** @var UriInterface|null */
  26      protected $baseApiUri;
  27  
  28      /**
  29       * @param Credentials           $credentials
  30       * @param ClientInterface       $httpClient
  31       * @param TokenStorageInterface $storage
  32       * @param array                 $scopes
  33       * @param UriInterface|null     $baseApiUri
  34       *
  35       * @throws InvalidScopeException
  36       */
  37      public function __construct(
  38          CredentialsInterface $credentials,
  39          ClientInterface $httpClient,
  40          TokenStorageInterface $storage,
  41          $scopes = array(),
  42          UriInterface $baseApiUri = null
  43      ) {
  44          parent::__construct($credentials, $httpClient, $storage);
  45  
  46          foreach ($scopes as $scope) {
  47              if (!$this->isValidScope($scope)) {
  48                  throw new InvalidScopeException('Scope ' . $scope . ' is not valid for service ' . get_class($this));
  49              }
  50          }
  51  
  52          $this->scopes = $scopes;
  53  
  54          $this->baseApiUri = $baseApiUri;
  55      }
  56  
  57      /**
  58       * {@inheritdoc}
  59       */
  60      public function getAuthorizationUri(array $additionalParameters = array())
  61      {
  62          $parameters = array_merge(
  63              $additionalParameters,
  64              array(
  65                  'type'          => 'web_server',
  66                  'client_id'     => $this->credentials->getConsumerId(),
  67                  'redirect_uri'  => $this->credentials->getCallbackUrl(),
  68                  'response_type' => 'code',
  69              )
  70          );
  71  
  72          $parameters['scope'] = implode(' ', $this->scopes);
  73  
  74          // Build the url
  75          $url = clone $this->getAuthorizationEndpoint();
  76          foreach ($parameters as $key => $val) {
  77              $url->addToQuery($key, $val);
  78          }
  79  
  80          return $url;
  81      }
  82  
  83      /**
  84       * {@inheritdoc}
  85       */
  86      public function requestAccessToken($code)
  87      {
  88          $bodyParams = array(
  89              'code'          => $code,
  90              'client_id'     => $this->credentials->getConsumerId(),
  91              'client_secret' => $this->credentials->getConsumerSecret(),
  92              'redirect_uri'  => $this->credentials->getCallbackUrl(),
  93              'grant_type'    => 'authorization_code',
  94          );
  95  
  96          $responseBody = $this->httpClient->retrieveResponse(
  97              $this->getAccessTokenEndpoint(),
  98              $bodyParams,
  99              $this->getExtraOAuthHeaders()
 100          );
 101          $token = $this->parseAccessTokenResponse($responseBody);
 102          $this->storage->storeAccessToken($this->service(), $token);
 103  
 104          return $token;
 105      }
 106  
 107      /**
 108       * Sends an authenticated API request to the path provided.
 109       * If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used.
 110       *
 111       * @param string|UriInterface $path
 112       * @param string              $method       HTTP method
 113       * @param array               $body         Request body if applicable.
 114       * @param array               $extraHeaders Extra headers if applicable. These will override service-specific
 115       *                                          any defaults.
 116       *
 117       * @return string
 118       *
 119       * @throws ExpiredTokenException
 120       * @throws Exception
 121       */
 122      public function request($path, $method = 'GET', $body = null, array $extraHeaders = array())
 123      {
 124          $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri);
 125          $token = $this->storage->retrieveAccessToken($this->service());
 126  
 127          if ($token->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES
 128              && $token->getEndOfLife() !== TokenInterface::EOL_UNKNOWN
 129              && time() > $token->getEndOfLife()
 130          ) {
 131              throw new ExpiredTokenException(
 132                  sprintf(
 133                      'Token expired on %s at %s',
 134                      date('m/d/Y', $token->getEndOfLife()),
 135                      date('h:i:s A', $token->getEndOfLife())
 136                  )
 137              );
 138          }
 139  
 140          // add the token where it may be needed
 141          if (static::AUTHORIZATION_METHOD_HEADER_OAUTH === $this->getAuthorizationMethod()) {
 142              $extraHeaders = array_merge(array('Authorization' => 'OAuth ' . $token->getAccessToken()), $extraHeaders);
 143          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING === $this->getAuthorizationMethod()) {
 144              $uri->addToQuery('access_token', $token->getAccessToken());
 145          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V2 === $this->getAuthorizationMethod()) {
 146              $uri->addToQuery('oauth2_access_token', $token->getAccessToken());
 147          } elseif (static::AUTHORIZATION_METHOD_HEADER_BEARER === $this->getAuthorizationMethod()) {
 148              $extraHeaders = array_merge(array('Authorization' => 'Bearer ' . $token->getAccessToken()), $extraHeaders);
 149          }
 150  
 151          $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders);
 152  
 153          return $this->httpClient->retrieveResponse($uri, $body, $extraHeaders, $method);
 154      }
 155  
 156      /**
 157       * Accessor to the storage adapter to be able to retrieve tokens
 158       *
 159       * @return TokenStorageInterface
 160       */
 161      public function getStorage()
 162      {
 163          return $this->storage;
 164      }
 165  
 166      /**
 167       * Refreshes an OAuth2 access token.
 168       *
 169       * @param TokenInterface $token
 170       *
 171       * @return TokenInterface $token
 172       *
 173       * @throws MissingRefreshTokenException
 174       */
 175      public function refreshAccessToken(TokenInterface $token)
 176      {
 177          $refreshToken = $token->getRefreshToken();
 178  
 179          if (empty($refreshToken)) {
 180              throw new MissingRefreshTokenException();
 181          }
 182  
 183          $parameters = array(
 184              'grant_type'    => 'refresh_token',
 185              'type'          => 'web_server',
 186              'client_id'     => $this->credentials->getConsumerId(),
 187              'client_secret' => $this->credentials->getConsumerSecret(),
 188              'refresh_token' => $refreshToken,
 189          );
 190  
 191          $responseBody = $this->httpClient->retrieveResponse(
 192              $this->getAccessTokenEndpoint(),
 193              $parameters,
 194              $this->getExtraOAuthHeaders()
 195          );
 196          $token = $this->parseAccessTokenResponse($responseBody);
 197          $this->storage->storeAccessToken($this->service(), $token);
 198  
 199          return $token;
 200      }
 201  
 202      /**
 203       * Return whether or not the passed scope value is valid.
 204       *
 205       * @param string $scope
 206       *
 207       * @return bool
 208       */
 209      public function isValidScope($scope)
 210      {
 211          $reflectionClass = new \ReflectionClass(get_class($this));
 212  
 213          return in_array($scope, $reflectionClass->getConstants(), true);
 214      }
 215  
 216      /**
 217       * Return any additional headers always needed for this service implementation's OAuth calls.
 218       *
 219       * @return array
 220       */
 221      protected function getExtraOAuthHeaders()
 222      {
 223          return array();
 224      }
 225  
 226      /**
 227       * Return any additional headers always needed for this service implementation's API calls.
 228       *
 229       * @return array
 230       */
 231      protected function getExtraApiHeaders()
 232      {
 233          return array();
 234      }
 235  
 236      /**
 237       * Parses the access token response and returns a TokenInterface.
 238       *
 239       * @abstract
 240       *
 241       * @param string $responseBody
 242       *
 243       * @return TokenInterface
 244       *
 245       * @throws TokenResponseException
 246       */
 247      abstract protected function parseAccessTokenResponse($responseBody);
 248  
 249      /**
 250       * Returns a class constant from ServiceInterface defining the authorization method used for the API
 251       * Header is the sane default.
 252       *
 253       * @return int
 254       */
 255      protected function getAuthorizationMethod()
 256      {
 257          return static::AUTHORIZATION_METHOD_HEADER_OAUTH;
 258      }
 259  }


Generated: Thu Jan 11 00:25:41 2018 Cross-referenced by PHPXref 0.7.1