Verzeichnisstruktur phpBB-3.2.0


Veröffentlicht
06.01.2017

So funktioniert es


Auf das letzte Element klicken. Dies geht jeweils ein Schritt zurück

Auf das Icon klicken, dies öffnet das Verzeichnis. Nochmal klicken schließt das Verzeichnis.
Auf den Verzeichnisnamen klicken, dies zeigt nur das Verzeichnis mit Inhalt an

      (Beispiel Datei-Icons)

Auf das Icon klicken um den Quellcode anzuzeigen

AbstractService.php

Zuletzt modifiziert: 09.10.2024, 12:59 - Dateigröße: 11.15 KiB


 001  <?php
 002   
 003  namespace OAuth\OAuth2\Service;
 004   
 005  use OAuth\Common\Consumer\CredentialsInterface;
 006  use OAuth\Common\Exception\Exception;
 007  use OAuth\Common\Service\AbstractService as BaseAbstractService;
 008  use OAuth\Common\Storage\TokenStorageInterface;
 009  use OAuth\Common\Http\Exception\TokenResponseException;
 010  use OAuth\Common\Http\Client\ClientInterface;
 011  use OAuth\Common\Http\Uri\UriInterface;
 012  use OAuth\OAuth2\Service\Exception\InvalidAuthorizationStateException;
 013  use OAuth\OAuth2\Service\Exception\InvalidScopeException;
 014  use OAuth\OAuth2\Service\Exception\MissingRefreshTokenException;
 015  use OAuth\Common\Token\TokenInterface;
 016  use OAuth\Common\Token\Exception\ExpiredTokenException;
 017   
 018  abstract class AbstractService extends BaseAbstractService implements ServiceInterface
 019  {
 020      /** @const OAUTH_VERSION */
 021      const OAUTH_VERSION = 2;
 022   
 023      /** @var array */
 024      protected $scopes;
 025   
 026      /** @var UriInterface|null */
 027      protected $baseApiUri;
 028   
 029      /** @var bool */
 030      protected $stateParameterInAuthUrl;
 031   
 032      /** @var string */
 033      protected $apiVersion;
 034   
 035      /**
 036       * @param CredentialsInterface  $credentials
 037       * @param ClientInterface       $httpClient
 038       * @param TokenStorageInterface $storage
 039       * @param array                 $scopes
 040       * @param UriInterface|null     $baseApiUri
 041       * @param bool $stateParameterInAutUrl
 042       * @param string                $apiVersion
 043       *
 044       * @throws InvalidScopeException
 045       */
 046      public function __construct(
 047          CredentialsInterface $credentials,
 048          ClientInterface $httpClient,
 049          TokenStorageInterface $storage,
 050          $scopes = array(),
 051          UriInterface $baseApiUri = null,
 052          $stateParameterInAutUrl = false,
 053          $apiVersion = ""
 054      ) {
 055          parent::__construct($credentials, $httpClient, $storage);
 056          $this->stateParameterInAuthUrl = $stateParameterInAutUrl;
 057   
 058          foreach ($scopes as $scope) {
 059              if (!$this->isValidScope($scope)) {
 060                  throw new InvalidScopeException('Scope ' . $scope . ' is not valid for service ' . get_class($this));
 061              }
 062          }
 063   
 064          $this->scopes = $scopes;
 065   
 066          $this->baseApiUri = $baseApiUri;
 067   
 068          $this->apiVersion = $apiVersion;
 069      }
 070   
 071      /**
 072       * {@inheritdoc}
 073       */
 074      public function getAuthorizationUri(array $additionalParameters = array())
 075      {
 076          $parameters = array_merge(
 077              $additionalParameters,
 078              array(
 079                  'type'          => 'web_server',
 080                  'client_id'     => $this->credentials->getConsumerId(),
 081                  'redirect_uri'  => $this->credentials->getCallbackUrl(),
 082                  'response_type' => 'code',
 083              )
 084          );
 085   
 086          $parameters['scope'] = implode($this->getScopesDelimiter(), $this->scopes);
 087   
 088          if ($this->needsStateParameterInAuthUrl()) {
 089              if (!isset($parameters['state'])) {
 090                  $parameters['state'] = $this->generateAuthorizationState();
 091              }
 092              $this->storeAuthorizationState($parameters['state']);
 093          }
 094   
 095          // Build the url
 096          $url = clone $this->getAuthorizationEndpoint();
 097          foreach ($parameters as $key => $val) {
 098              $url->addToQuery($key, $val);
 099          }
 100   
 101          return $url;
 102      }
 103   
 104      /**
 105       * {@inheritdoc}
 106       */
 107      public function requestAccessToken($code, $state = null)
 108      {
 109          if (null !== $state) {
 110              $this->validateAuthorizationState($state);
 111          }
 112   
 113          $bodyParams = array(
 114              'code'          => $code,
 115              'client_id'     => $this->credentials->getConsumerId(),
 116              'client_secret' => $this->credentials->getConsumerSecret(),
 117              'redirect_uri'  => $this->credentials->getCallbackUrl(),
 118              'grant_type'    => 'authorization_code',
 119          );
 120   
 121          $responseBody = $this->httpClient->retrieveResponse(
 122              $this->getAccessTokenEndpoint(),
 123              $bodyParams,
 124              $this->getExtraOAuthHeaders()
 125          );
 126   
 127          $token = $this->parseAccessTokenResponse($responseBody);
 128          $this->storage->storeAccessToken($this->service(), $token);
 129   
 130          return $token;
 131      }
 132   
 133      /**
 134       * Sends an authenticated API request to the path provided.
 135       * If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used.
 136       *
 137       * @param string|UriInterface $path
 138       * @param string              $method       HTTP method
 139       * @param array               $body         Request body if applicable.
 140       * @param array               $extraHeaders Extra headers if applicable. These will override service-specific
 141       *                                          any defaults.
 142       *
 143       * @return string
 144       *
 145       * @throws ExpiredTokenException
 146       * @throws Exception
 147       */
 148      public function request($path, $method = 'GET', $body = null, array $extraHeaders = array())
 149      {
 150          $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri);
 151          $token = $this->storage->retrieveAccessToken($this->service());
 152   
 153          if ($token->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES
 154              && $token->getEndOfLife() !== TokenInterface::EOL_UNKNOWN
 155              && time() > $token->getEndOfLife()
 156          ) {
 157              throw new ExpiredTokenException(
 158                  sprintf(
 159                      'Token expired on %s at %s',
 160                      date('m/d/Y', $token->getEndOfLife()),
 161                      date('h:i:s A', $token->getEndOfLife())
 162                  )
 163              );
 164          }
 165   
 166          // add the token where it may be needed
 167          if (static::AUTHORIZATION_METHOD_HEADER_OAUTH === $this->getAuthorizationMethod()) {
 168              $extraHeaders = array_merge(array('Authorization' => 'OAuth ' . $token->getAccessToken()), $extraHeaders);
 169          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING === $this->getAuthorizationMethod()) {
 170              $uri->addToQuery('access_token', $token->getAccessToken());
 171          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V2 === $this->getAuthorizationMethod()) {
 172              $uri->addToQuery('oauth2_access_token', $token->getAccessToken());
 173          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V3 === $this->getAuthorizationMethod()) {
 174              $uri->addToQuery('apikey', $token->getAccessToken());
 175          } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V4 === $this->getAuthorizationMethod()) {
 176              $uri->addToQuery('auth', $token->getAccessToken());
 177          } elseif (static::AUTHORIZATION_METHOD_HEADER_BEARER === $this->getAuthorizationMethod()) {
 178              $extraHeaders = array_merge(array('Authorization' => 'Bearer ' . $token->getAccessToken()), $extraHeaders);
 179          }
 180   
 181          $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders);
 182   
 183          return $this->httpClient->retrieveResponse($uri, $body, $extraHeaders, $method);
 184      }
 185   
 186      /**
 187       * Accessor to the storage adapter to be able to retrieve tokens
 188       *
 189       * @return TokenStorageInterface
 190       */
 191      public function getStorage()
 192      {
 193          return $this->storage;
 194      }
 195   
 196      /**
 197       * Refreshes an OAuth2 access token.
 198       *
 199       * @param TokenInterface $token
 200       *
 201       * @return TokenInterface $token
 202       *
 203       * @throws MissingRefreshTokenException
 204       */
 205      public function refreshAccessToken(TokenInterface $token)
 206      {
 207          $refreshToken = $token->getRefreshToken();
 208   
 209          if (empty($refreshToken)) {
 210              throw new MissingRefreshTokenException();
 211          }
 212   
 213          $parameters = array(
 214              'grant_type'    => 'refresh_token',
 215              'type'          => 'web_server',
 216              'client_id'     => $this->credentials->getConsumerId(),
 217              'client_secret' => $this->credentials->getConsumerSecret(),
 218              'refresh_token' => $refreshToken,
 219          );
 220   
 221          $responseBody = $this->httpClient->retrieveResponse(
 222              $this->getAccessTokenEndpoint(),
 223              $parameters,
 224              $this->getExtraOAuthHeaders()
 225          );
 226          $token = $this->parseAccessTokenResponse($responseBody);
 227          $this->storage->storeAccessToken($this->service(), $token);
 228   
 229          return $token;
 230      }
 231   
 232      /**
 233       * Return whether or not the passed scope value is valid.
 234       *
 235       * @param string $scope
 236       *
 237       * @return bool
 238       */
 239      public function isValidScope($scope)
 240      {
 241          $reflectionClass = new \ReflectionClass(get_class($this));
 242   
 243          return in_array($scope, $reflectionClass->getConstants(), true);
 244      }
 245   
 246      /**
 247       * Check if the given service need to generate a unique state token to build the authorization url
 248       *
 249       * @return bool
 250       */
 251      public function needsStateParameterInAuthUrl()
 252      {
 253          return $this->stateParameterInAuthUrl;
 254      }
 255   
 256      /**
 257       * Validates the authorization state against a given one
 258       *
 259       * @param string $state
 260       * @throws InvalidAuthorizationStateException
 261       */
 262      protected function validateAuthorizationState($state)
 263      {
 264          if ($this->retrieveAuthorizationState() !== $state) {
 265              throw new InvalidAuthorizationStateException();
 266          }
 267      }
 268   
 269      /**
 270       * Generates a random string to be used as state
 271       *
 272       * @return string
 273       */
 274      protected function generateAuthorizationState()
 275      {
 276          return md5(rand());
 277      }
 278   
 279      /**
 280       * Retrieves the authorization state for the current service
 281       *
 282       * @return string
 283       */
 284      protected function retrieveAuthorizationState()
 285      {
 286          return $this->storage->retrieveAuthorizationState($this->service());
 287      }
 288   
 289      /**
 290       * Stores a given authorization state into the storage
 291       *
 292       * @param string $state
 293       */
 294      protected function storeAuthorizationState($state)
 295      {
 296          $this->storage->storeAuthorizationState($this->service(), $state);
 297      }
 298   
 299      /**
 300       * Return any additional headers always needed for this service implementation's OAuth calls.
 301       *
 302       * @return array
 303       */
 304      protected function getExtraOAuthHeaders()
 305      {
 306          return array();
 307      }
 308   
 309      /**
 310       * Return any additional headers always needed for this service implementation's API calls.
 311       *
 312       * @return array
 313       */
 314      protected function getExtraApiHeaders()
 315      {
 316          return array();
 317      }
 318   
 319      /**
 320       * Parses the access token response and returns a TokenInterface.
 321       *
 322       * @abstract
 323       *
 324       * @param string $responseBody
 325       *
 326       * @return TokenInterface
 327       *
 328       * @throws TokenResponseException
 329       */
 330      abstract protected function parseAccessTokenResponse($responseBody);
 331   
 332      /**
 333       * Returns a class constant from ServiceInterface defining the authorization method used for the API
 334       * Header is the sane default.
 335       *
 336       * @return int
 337       */
 338      protected function getAuthorizationMethod()
 339      {
 340          return static::AUTHORIZATION_METHOD_HEADER_OAUTH;
 341      }
 342   
 343      /**
 344       * Returns api version string if is set else retrun empty string
 345       *
 346       * @return string
 347       */
 348      protected function getApiVersionString()
 349      {
 350          return !(empty($this->apiVersion)) ? "/".$this->apiVersion : "" ;
 351      }
 352   
 353      /**
 354       * Returns delimiter to scopes in getAuthorizationUri
 355       * For services that do not fully respect the Oauth's RFC,
 356       * and use scopes with commas as delimiter
 357       *
 358       * @return string
 359       */
 360      protected function getScopesDelimiter()
 361      {
 362          return ' ';
 363      }
 364  }
 365