|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Bookboon\ApiBundle\Client; |
| 4 | + |
| 5 | +use Bookboon\OauthClient\BookboonProvider; |
| 6 | +use Bookboon\OauthClient\OauthGrants; |
| 7 | +use Bookboon\ApiBundle\Exception\ApiAuthenticationException; |
| 8 | +use Bookboon\ApiBundle\Exception\ApiInvalidStateException; |
| 9 | +use Bookboon\ApiBundle\Exception\UsageException; |
| 10 | +use GuzzleHttp\TransferStats; |
| 11 | +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; |
| 12 | +use League\OAuth2\Client\Token\AccessTokenInterface; |
| 13 | +use Psr\Log\LoggerInterface; |
| 14 | +use Psr\SimpleCache\CacheInterface; |
| 15 | + |
| 16 | +class AccessTokenClient |
| 17 | +{ |
| 18 | + protected string $_apiUri; |
| 19 | + private ?AccessTokenInterface $accessToken; |
| 20 | + protected ?string $act; |
| 21 | + protected BookboonProvider $provider; |
| 22 | + protected array $requestOptions = []; |
| 23 | + protected string $apiId; |
| 24 | + protected Headers $headers; |
| 25 | + protected ?CacheInterface $cache; |
| 26 | + |
| 27 | + public function __construct( |
| 28 | + string $apiId, |
| 29 | + string $apiSecret, |
| 30 | + Headers $headers, |
| 31 | + array $scopes, |
| 32 | + CacheInterface $cache = null, |
| 33 | + ?string $redirectUri = null, |
| 34 | + ?string $appUserId = null, |
| 35 | + ?string $authServiceUri = null, |
| 36 | + ?string $apiUri = null, |
| 37 | + LoggerInterface $logger = null, |
| 38 | + array $clientOptions = [] |
| 39 | + ) { |
| 40 | + if (empty($apiId)) { |
| 41 | + throw new UsageException("Client id is required"); |
| 42 | + } |
| 43 | + |
| 44 | + $clientOptions = array_merge( |
| 45 | + $clientOptions, |
| 46 | + [ |
| 47 | + 'clientId' => $apiId, |
| 48 | + 'clientSecret' => $apiSecret, |
| 49 | + 'scope' => $scopes, |
| 50 | + 'redirectUri' => $redirectUri, |
| 51 | + 'baseUri' => $authServiceUri, |
| 52 | + ] |
| 53 | + ); |
| 54 | + |
| 55 | + if ($logger !== null) { |
| 56 | + $this->requestOptions = [ |
| 57 | + 'on_stats' => function (TransferStats $stats) use ($logger) { |
| 58 | + if ($stats->hasResponse()) { |
| 59 | + $size = $stats->getHandlerStat('size_download') ?? 0; |
| 60 | + $statusCode = $stats->getResponse() ? $stats->getResponse()->getStatusCode() : 0; |
| 61 | + |
| 62 | + $logger->info( |
| 63 | + "Api request \"{$stats->getRequest()->getMethod()} {$stats->getRequest()->getRequestTarget()} HTTP/{$stats->getRequest()->getProtocolVersion()}\" {$statusCode} - {$size} - {$stats->getTransferTime()}" |
| 64 | + ); |
| 65 | + } else { |
| 66 | + $logger->error( |
| 67 | + "Api request: No response received with error {$stats->getHandlerErrorData()}" |
| 68 | + ); |
| 69 | + } |
| 70 | + } |
| 71 | + ]; |
| 72 | + } |
| 73 | + |
| 74 | + $clientOptions['requestOptions'] = $this->requestOptions; |
| 75 | + $this->provider = new BookboonProvider($clientOptions); |
| 76 | + |
| 77 | + $this->apiId = $apiId; |
| 78 | + $this->cache = $cache; |
| 79 | + $this->headers = $headers; |
| 80 | + $this->act = $appUserId; |
| 81 | + |
| 82 | + $this->_apiUri = $this->parseUriOrDefault($apiUri); |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * @param array $options |
| 87 | + * @param string $type |
| 88 | + * @return AccessTokenInterface |
| 89 | + * @throws ApiAuthenticationException |
| 90 | + * @throws UsageException |
| 91 | + */ |
| 92 | + public function requestAccessToken( |
| 93 | + array $options = [], |
| 94 | + string $type = OauthGrants::AUTHORIZATION_CODE |
| 95 | + ) : AccessTokenInterface { |
| 96 | + $provider = $this->provider; |
| 97 | + |
| 98 | + if ($type == OauthGrants::AUTHORIZATION_CODE && !isset($options["code"])) { |
| 99 | + throw new UsageException("This oauth flow requires a code"); |
| 100 | + } |
| 101 | + |
| 102 | + try { |
| 103 | + $this->accessToken = $provider->getAccessToken($type, $options); |
| 104 | + } |
| 105 | + |
| 106 | + catch (IdentityProviderException $e) { |
| 107 | + //TODO: Parse and send this with exception (string) $e->getResponseBody()->getBody() |
| 108 | + throw new ApiAuthenticationException("Authorization Failed"); |
| 109 | + } |
| 110 | + |
| 111 | + return $this->accessToken; |
| 112 | + } |
| 113 | + |
| 114 | + public function refreshAccessToken(AccessTokenInterface $accessToken) : AccessTokenInterface |
| 115 | + { |
| 116 | + $this->accessToken = $this->provider->getAccessToken('refresh_token', [ |
| 117 | + 'refresh_token' => $accessToken->getRefreshToken() |
| 118 | + ]); |
| 119 | + |
| 120 | + return $accessToken; |
| 121 | + } |
| 122 | + |
| 123 | + public function generateState(): string |
| 124 | + { |
| 125 | + return $this->provider->generateRandomState(); |
| 126 | + } |
| 127 | + |
| 128 | + public function isCorrectState(string $stateParameter, string $stateSession) : bool |
| 129 | + { |
| 130 | + if (empty($stateParameter) || ($stateParameter !== $stateSession)) { |
| 131 | + throw new ApiInvalidStateException("State is invalid"); |
| 132 | + } |
| 133 | + |
| 134 | + return true; |
| 135 | + } |
| 136 | + |
| 137 | + public function getAuthorizationUrl(array $options = []): string |
| 138 | + { |
| 139 | + $provider = $this->provider; |
| 140 | + |
| 141 | + if (null != $this->act && false === isset($options['act'])) { |
| 142 | + $options['act'] = $this->act; |
| 143 | + } |
| 144 | + |
| 145 | + return $provider->getAuthorizationUrl($options); |
| 146 | + } |
| 147 | + |
| 148 | + protected function parseUriOrDefault(?string $uri) : string |
| 149 | + { |
| 150 | + $protocol = ClientConstants::API_PROTOCOL; |
| 151 | + $host = ClientConstants::API_HOST; |
| 152 | + $path = ClientConstants::API_PATH; |
| 153 | + |
| 154 | + if (!empty($uri)) { |
| 155 | + $parts = explode('://', $uri); |
| 156 | + $protocol = $parts[0]; |
| 157 | + $host = $parts[1]; |
| 158 | + if (strpos($host, '/') !== false) { |
| 159 | + throw new UsageException('URI must not contain forward slashes'); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + if ($protocol !== 'http' && $protocol !== 'https') { |
| 164 | + throw new UsageException('Invalid protocol specified in URI'); |
| 165 | + } |
| 166 | + |
| 167 | + return "${protocol}://${host}${path}"; |
| 168 | + } |
| 169 | + |
| 170 | + public function getAct(): ?string { |
| 171 | + return $this->act; |
| 172 | + } |
| 173 | +} |
0 commit comments