Completed
Pull Request — master (#953)
by Andrew
02:05
created

AbstractGrant::convertScopesQueryStringToArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * OAuth 2.0 Abstract grant.
4
 *
5
 * @author      Alex Bilbie <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
namespace League\OAuth2\Server\Grant;
12
13
use League\Event\EmitterAwareTrait;
14
use League\OAuth2\Server\CryptKey;
15
use League\OAuth2\Server\CryptTrait;
16
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
17
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
18
use League\OAuth2\Server\Entities\ClientEntityInterface;
19
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
20
use League\OAuth2\Server\Entities\ScopeEntityInterface;
21
use League\OAuth2\Server\Exception\OAuthServerException;
22
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
23
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
24
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
25
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
26
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
27
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
28
use League\OAuth2\Server\Repositories\UserRepositoryInterface;
29
use League\OAuth2\Server\RequestEvent;
30
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
31
use Psr\Http\Message\ServerRequestInterface;
32
33
/**
34
 * Abstract grant class.
35
 */
36
abstract class AbstractGrant implements GrantTypeInterface
37
{
38
    use EmitterAwareTrait, CryptTrait;
39
40
    const SCOPE_DELIMITER_STRING = ' ';
41
42
    const MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS = 10;
43
44
    /**
45
     * @var ClientRepositoryInterface
46
     */
47
    protected $clientRepository;
48
49
    /**
50
     * @var AccessTokenRepositoryInterface
51
     */
52
    protected $accessTokenRepository;
53
54
    /**
55
     * @var ScopeRepositoryInterface
56
     */
57
    protected $scopeRepository;
58
59
    /**
60
     * @var AuthCodeRepositoryInterface
61
     */
62
    protected $authCodeRepository;
63
64
    /**
65
     * @var RefreshTokenRepositoryInterface
66
     */
67
    protected $refreshTokenRepository;
68
69
    /**
70
     * @var UserRepositoryInterface
71
     */
72
    protected $userRepository;
73
74
    /**
75
     * @var \DateInterval
76
     */
77
    protected $refreshTokenTTL;
78
79
    /**
80
     * @var \League\OAuth2\Server\CryptKey
81
     */
82
    protected $privateKey;
83
84
    /**
85
     * @string
86
     */
87
    protected $defaultScope;
88
89
    /**
90
     * @param ClientRepositoryInterface $clientRepository
91
     */
92 64
    public function setClientRepository(ClientRepositoryInterface $clientRepository)
93
    {
94 64
        $this->clientRepository = $clientRepository;
95 64
    }
96
97
    /**
98
     * @param AccessTokenRepositoryInterface $accessTokenRepository
99
     */
100 42
    public function setAccessTokenRepository(AccessTokenRepositoryInterface $accessTokenRepository)
101
    {
102 42
        $this->accessTokenRepository = $accessTokenRepository;
103 42
    }
104
105
    /**
106
     * @param ScopeRepositoryInterface $scopeRepository
107
     */
108 37
    public function setScopeRepository(ScopeRepositoryInterface $scopeRepository)
109
    {
110 37
        $this->scopeRepository = $scopeRepository;
111 37
    }
112
113
    /**
114
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
115
     */
116 56
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository)
117
    {
118 56
        $this->refreshTokenRepository = $refreshTokenRepository;
119 56
    }
120
121
    /**
122
     * @param AuthCodeRepositoryInterface $authCodeRepository
123
     */
124 42
    public function setAuthCodeRepository(AuthCodeRepositoryInterface $authCodeRepository)
125
    {
126 42
        $this->authCodeRepository = $authCodeRepository;
127 42
    }
128
129
    /**
130
     * @param UserRepositoryInterface $userRepository
131
     */
132 5
    public function setUserRepository(UserRepositoryInterface $userRepository)
133
    {
134 5
        $this->userRepository = $userRepository;
135 5
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140 1
    public function setRefreshTokenTTL(\DateInterval $refreshTokenTTL)
141
    {
142 1
        $this->refreshTokenTTL = $refreshTokenTTL;
143 1
    }
144
145
    /**
146
     * Set the private key
147
     *
148
     * @param \League\OAuth2\Server\CryptKey $key
149
     */
150 20
    public function setPrivateKey(CryptKey $key)
151
    {
152 20
        $this->privateKey = $key;
153 20
    }
154
155
    /**
156
     * @param string $scope
157
     */
158 16
    public function setDefaultScope($scope)
159
    {
160 16
        $this->defaultScope = $scope;
161 16
    }
162
163
    /**
164
     * Validate the client.
165
     *
166
     * @param ServerRequestInterface $request
167
     *
168
     * @throws OAuthServerException
169
     *
170
     * @return ClientEntityInterface
171
     */
172 42
    protected function validateClient(ServerRequestInterface $request)
173
    {
174 42
        list($basicAuthUser, $basicAuthPassword) = $this->getBasicAuthCredentials($request);
175
176 42
        $clientId = $this->getRequestParameter('client_id', $request, $basicAuthUser);
177 42
        if ($clientId === null) {
178 1
            throw OAuthServerException::invalidRequest('client_id');
179
        }
180
181
        // If the client is confidential require the client secret
182 41
        $clientSecret = $this->getRequestParameter('client_secret', $request, $basicAuthPassword);
183
184 41
        $client = $this->clientRepository->getClientEntity(
185 41
            $clientId,
186 41
            $this->getIdentifier(),
187 41
            $clientSecret,
188 41
            true
189
        );
190
191 41
        if ($client instanceof ClientEntityInterface === false) {
192 4
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
193 4
            throw OAuthServerException::invalidClient();
194
        }
195
196 37
        $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
197
198 37
        if ($redirectUri !== null) {
199 20
            $this->validateRedirectUri($redirectUri, $client, $request);
200
        }
201
202 35
        return $client;
203
    }
204
205
    /**
206
     * Validate redirectUri from the request.
207
     * If a redirect URI is provided ensure it matches what is pre-registered
208
     *
209
     * @param string                 $redirectUri
210
     * @param ClientEntityInterface  $client
211
     * @param ServerRequestInterface $request
212
     *
213
     * @throws OAuthServerException
214
     */
215 34
    protected function validateRedirectUri(
216
        string $redirectUri,
217
        ClientEntityInterface $client,
218
        ServerRequestInterface $request
219
    ) {
220 34
        if (\is_string($client->getRedirectUri())
221 34
            && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
222
        ) {
223 3
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
224 3
            throw OAuthServerException::invalidClient();
225 31
        } elseif (\is_array($client->getRedirectUri())
226 31
            && \in_array($redirectUri, $client->getRedirectUri(), true) === false
227
        ) {
228 3
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
229 3
            throw OAuthServerException::invalidClient();
230
        }
231 28
    }
232
233
    /**
234
     * Validate scopes in the request.
235
     *
236
     * @param string|array $scopes
237
     * @param string       $redirectUri
238
     *
239
     * @return ScopeEntityInterface[]
240
     * @throws OAuthServerException
241
     */
242 34
    public function validateScopes($scopes, $redirectUri = null)
243
    {
244 34
        if (!\is_array($scopes)) {
245 23
            $scopes = $this->convertScopesQueryStringToArray($scopes);
246
        }
247
248 34
        $validScopes = [];
249
250 34
        foreach ($scopes as $scopeItem) {
251 28
            $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
252
253 28
            if ($scope instanceof ScopeEntityInterface === false) {
254 1
                throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
255
            }
256
257 27
            $validScopes[] = $scope;
258
        }
259
260 33
        return $validScopes;
261
    }
262
263
    /**
264
     * Converts a scopes query string to an array to easily iterate for validation.
265
     *
266
     * @param string $scopes
267
     *
268
     * @return array
269
     */
270
    private function convertScopesQueryStringToArray($scopes)
271
    {
272 23
        return array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
273 23
            return !empty($scope);
274 23
        });
275
    }
276
277
    /**
278
     * Retrieve request parameter.
279
     *
280
     * @param string                 $parameter
281
     * @param ServerRequestInterface $request
282
     * @param mixed                  $default
283
     *
284
     * @return null|string
285
     */
286 42
    protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null)
287
    {
288 42
        $requestParameters = (array) $request->getParsedBody();
289
290 42
        return $requestParameters[$parameter] ?? $default;
291
    }
292
293
    /**
294
     * Retrieve HTTP Basic Auth credentials with the Authorization header
295
     * of a request. First index of the returned array is the username,
296
     * second is the password (so list() will work). If the header does
297
     * not exist, or is otherwise an invalid HTTP Basic header, return
298
     * [null, null].
299
     *
300
     * @param ServerRequestInterface $request
301
     *
302
     * @return string[]|null[]
303
     */
304 47
    protected function getBasicAuthCredentials(ServerRequestInterface $request)
305
    {
306 47
        if (!$request->hasHeader('Authorization')) {
307 42
            return [null, null];
308
        }
309
310 5
        $header = $request->getHeader('Authorization')[0];
311 5
        if (strpos($header, 'Basic ') !== 0) {
312 1
            return [null, null];
313
        }
314
315 4
        if (!($decoded = base64_decode(substr($header, 6)))) {
316 1
            return [null, null];
317
        }
318
319 3
        if (strpos($decoded, ':') === false) {
320 1
            return [null, null]; // HTTP Basic header without colon isn't valid
321
        }
322
323 2
        return explode(':', $decoded, 2);
324
    }
325
326
    /**
327
     * Retrieve query string parameter.
328
     *
329
     * @param string                 $parameter
330
     * @param ServerRequestInterface $request
331
     * @param mixed                  $default
332
     *
333
     * @return null|string
334
     */
335 21
    protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
336
    {
337 21
        return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default;
338
    }
339
340
    /**
341
     * Retrieve cookie parameter.
342
     *
343
     * @param string                 $parameter
344
     * @param ServerRequestInterface $request
345
     * @param mixed                  $default
346
     *
347
     * @return null|string
348
     */
349 1
    protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null)
350
    {
351 1
        return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default;
352
    }
353
354
    /**
355
     * Retrieve server parameter.
356
     *
357
     * @param string                 $parameter
358
     * @param ServerRequestInterface $request
359
     * @param mixed                  $default
360
     *
361
     * @return null|string
362
     */
363 20
    protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
364
    {
365 20
        return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default;
366
    }
367
368
    /**
369
     * Issue an access token.
370
     *
371
     * @param \DateInterval          $accessTokenTTL
372
     * @param ClientEntityInterface  $client
373
     * @param string|null            $userIdentifier
374
     * @param ScopeEntityInterface[] $scopes
375
     *
376
     * @return AccessTokenEntityInterface
377
     * @throws OAuthServerException
378
     * @throws UniqueTokenIdentifierConstraintViolationException
379
     */
380 17
    protected function issueAccessToken(
381
        \DateInterval $accessTokenTTL,
382
        ClientEntityInterface $client,
383
        $userIdentifier,
384
        array $scopes = []
385
    ) {
386 17
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
387
388 17
        $accessToken = $this->accessTokenRepository->getNewToken($client, $scopes, $userIdentifier);
389 17
        $accessToken->setClient($client);
390 17
        $accessToken->setUserIdentifier($userIdentifier);
391 17
        $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
392
393 17
        foreach ($scopes as $scope) {
394 13
            $accessToken->addScope($scope);
395
        }
396
397 17
        while ($maxGenerationAttempts-- > 0) {
398 17
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
399
            try {
400 17
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
401
402 15
                return $accessToken;
403 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
404 1
                if ($maxGenerationAttempts === 0) {
405 1
                    throw $e;
406
                }
407
            }
408
        }
409
    }
410
411
    /**
412
     * Issue an auth code.
413
     *
414
     * @param \DateInterval          $authCodeTTL
415
     * @param ClientEntityInterface  $client
416
     * @param string                 $userIdentifier
417
     * @param string|null            $redirectUri
418
     * @param ScopeEntityInterface[] $scopes
419
     *
420
     * @throws OAuthServerException
421
     * @throws UniqueTokenIdentifierConstraintViolationException
422
     *
423
     * @return AuthCodeEntityInterface
424
     */
425 6
    protected function issueAuthCode(
426
        \DateInterval $authCodeTTL,
427
        ClientEntityInterface $client,
428
        $userIdentifier,
429
        $redirectUri,
430
        array $scopes = []
431
    ) {
432 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
433
434 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
435 6
        $authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
436 6
        $authCode->setClient($client);
437 6
        $authCode->setUserIdentifier($userIdentifier);
438
439 6
        if ($redirectUri !== null) {
440 1
            $authCode->setRedirectUri($redirectUri);
441
        }
442
443 6
        foreach ($scopes as $scope) {
444 1
            $authCode->addScope($scope);
445
        }
446
447 6
        while ($maxGenerationAttempts-- > 0) {
448 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
449
            try {
450 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
451
452 4
                return $authCode;
453 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
454 1
                if ($maxGenerationAttempts === 0) {
455 1
                    throw $e;
456
                }
457
            }
458
        }
459
    }
460
461
    /**
462
     * @param AccessTokenEntityInterface $accessToken
463
     *
464
     * @throws OAuthServerException
465
     * @throws UniqueTokenIdentifierConstraintViolationException
466
     *
467
     * @return RefreshTokenEntityInterface
468
     */
469 10
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
470
    {
471 10
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
472
473 10
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
474 10
        $refreshToken->setExpiryDateTime((new \DateTime())->add($this->refreshTokenTTL));
475 10
        $refreshToken->setAccessToken($accessToken);
476
477 10
        while ($maxGenerationAttempts-- > 0) {
478 10
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
479
            try {
480 10
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
481
482 8
                return $refreshToken;
483 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
484 1
                if ($maxGenerationAttempts === 0) {
485 1
                    throw $e;
486
                }
487
            }
488
        }
489
    }
490
491
    /**
492
     * Generate a new unique identifier.
493
     *
494
     * @param int $length
495
     *
496
     * @return string
497
     * @throws OAuthServerException
498
     */
499 25
    protected function generateUniqueIdentifier($length = 40)
500
    {
501
        try {
502 25
            return bin2hex(random_bytes($length));
503
            // @codeCoverageIgnoreStart
504
        } catch (\TypeError $e) {
505
            throw OAuthServerException::serverError('An unexpected error has occurred');
506
        } catch (\Error $e) {
507
            throw OAuthServerException::serverError('An unexpected error has occurred');
508
        } catch (\Exception $e) {
509
            // If you get this message, the CSPRNG failed hard.
510
            throw OAuthServerException::serverError('Could not generate a random string');
511
        }
512
        // @codeCoverageIgnoreEnd
513
    }
514
515
    /**
516
     * {@inheritdoc}
517
     */
518 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
519
    {
520 5
        $requestParameters = (array) $request->getParsedBody();
521
522
        return (
523 5
            array_key_exists('grant_type', $requestParameters)
524 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
525
        );
526
    }
527
528
    /**
529
     * {@inheritdoc}
530
     */
531 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
532
    {
533 1
        return false;
534
    }
535
536
    /**
537
     * {@inheritdoc}
538
     */
539 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
540
    {
541 1
        throw new \LogicException('This grant cannot validate an authorization request');
542
    }
543
544
    /**
545
     * {@inheritdoc}
546
     */
547 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
548
    {
549 1
        throw new \LogicException('This grant cannot complete an authorization request');
550
    }
551
}
552