Completed
Pull Request — master (#910)
by Andrew
01:49
created

AbstractGrant::getServerParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 3
crap 2
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 32
    public function setScopeRepository(ScopeRepositoryInterface $scopeRepository)
109
    {
110 32
        $this->scopeRepository = $scopeRepository;
111 32
    }
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 (is_null($clientId)) {
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 $scopes
237
     * @param string $redirectUri
238
     *
239
     * @throws OAuthServerException
240
     *
241
     * @return ScopeEntityInterface[]
242
     */
243 23
    public function validateScopes($scopes, $redirectUri = null)
244
    {
245
        $scopesList = array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
246 23
            return !empty($scope);
247 23
        });
248
249 23
        $validScopes = [];
250
251 23
        foreach ($scopesList as $scopeItem) {
252 17
            $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
253
254 17
            if ($scope instanceof ScopeEntityInterface === false) {
255 1
                throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
256
            }
257
258 16
            $validScopes[] = $scope;
259
        }
260
261 22
        return $validScopes;
262
    }
263
264
    /**
265
     * Retrieve request parameter.
266
     *
267
     * @param string                 $parameter
268
     * @param ServerRequestInterface $request
269
     * @param mixed                  $default
270
     *
271
     * @return null|string
272
     */
273 42
    protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null)
274
    {
275 42
        $requestParameters = (array) $request->getParsedBody();
276
277 42
        return isset($requestParameters[$parameter]) ? $requestParameters[$parameter] : $default;
278
    }
279
280
    /**
281
     * Retrieve HTTP Basic Auth credentials with the Authorization header
282
     * of a request. First index of the returned array is the username,
283
     * second is the password (so list() will work). If the header does
284
     * not exist, or is otherwise an invalid HTTP Basic header, return
285
     * [null, null].
286
     *
287
     * @param ServerRequestInterface $request
288
     *
289
     * @return string[]|null[]
290
     */
291 47
    protected function getBasicAuthCredentials(ServerRequestInterface $request)
292
    {
293 47
        if (!$request->hasHeader('Authorization')) {
294 42
            return [null, null];
295
        }
296
297 5
        $header = $request->getHeader('Authorization')[0];
298 5
        if (strpos($header, 'Basic ') !== 0) {
299 1
            return [null, null];
300
        }
301
302 4
        if (!($decoded = base64_decode(substr($header, 6)))) {
303 1
            return [null, null];
304
        }
305
306 3
        if (strpos($decoded, ':') === false) {
307 1
            return [null, null]; // HTTP Basic header without colon isn't valid
308
        }
309
310 2
        return explode(':', $decoded, 2);
311
    }
312
313
    /**
314
     * Retrieve query string parameter.
315
     *
316
     * @param string                 $parameter
317
     * @param ServerRequestInterface $request
318
     * @param mixed                  $default
319
     *
320
     * @return null|string
321
     */
322 21
    protected function getQueryStringParameter($parameter, ServerRequestInterface $request, $default = null)
323
    {
324 21
        return isset($request->getQueryParams()[$parameter]) ? $request->getQueryParams()[$parameter] : $default;
325
    }
326
327
    /**
328
     * Retrieve cookie parameter.
329
     *
330
     * @param string                 $parameter
331
     * @param ServerRequestInterface $request
332
     * @param mixed                  $default
333
     *
334
     * @return null|string
335
     */
336 1
    protected function getCookieParameter($parameter, ServerRequestInterface $request, $default = null)
337
    {
338 1
        return isset($request->getCookieParams()[$parameter]) ? $request->getCookieParams()[$parameter] : $default;
339
    }
340
341
    /**
342
     * Retrieve server parameter.
343
     *
344
     * @param string                 $parameter
345
     * @param ServerRequestInterface $request
346
     * @param mixed                  $default
347
     *
348
     * @return null|string
349
     */
350 20
    protected function getServerParameter($parameter, ServerRequestInterface $request, $default = null)
351
    {
352 20
        return isset($request->getServerParams()[$parameter]) ? $request->getServerParams()[$parameter] : $default;
353
    }
354
355
    /**
356
     * Issue an access token.
357
     *
358
     * @param \DateInterval          $accessTokenTTL
359
     * @param ClientEntityInterface  $client
360
     * @param string|null            $userIdentifier
361
     * @param ScopeEntityInterface[] $scopes
362
     *
363
     * @throws OAuthServerException
364
     * @throws UniqueTokenIdentifierConstraintViolationException
365
     *
366
     * @return AccessTokenEntityInterface
367
     */
368 17
    protected function issueAccessToken(
369
        \DateInterval $accessTokenTTL,
370
        ClientEntityInterface $client,
371
        $userIdentifier,
372
        array $scopes = []
373
    ) {
374 17
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
375
376 17
        $accessToken = $this->accessTokenRepository->getNewToken($client, $scopes, $userIdentifier);
377 17
        $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
378
379 17
        while ($maxGenerationAttempts-- > 0) {
380 17
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
381
            try {
382 17
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
383
384 15
                return $accessToken;
385 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
386 1
                if ($maxGenerationAttempts === 0) {
387 1
                    throw $e;
388
                }
389
            }
390
        }
391
    }
392
393
    /**
394
     * Issue an auth code.
395
     *
396
     * @param \DateInterval          $authCodeTTL
397
     * @param ClientEntityInterface  $client
398
     * @param string                 $userIdentifier
399
     * @param string|null            $redirectUri
400
     * @param ScopeEntityInterface[] $scopes
401
     *
402
     * @throws OAuthServerException
403
     * @throws UniqueTokenIdentifierConstraintViolationException
404
     *
405
     * @return AuthCodeEntityInterface
406
     */
407 6
    protected function issueAuthCode(
408
        \DateInterval $authCodeTTL,
409
        ClientEntityInterface $client,
410
        $userIdentifier,
411
        $redirectUri,
412
        array $scopes = []
413
    ) {
414 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
415
416 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
417 6
        $authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
418 6
        $authCode->setClient($client);
419 6
        $authCode->setUserIdentifier($userIdentifier);
420
421 6
        if ($redirectUri !== null) {
422 1
            $authCode->setRedirectUri($redirectUri);
423
        }
424
425 6
        foreach ($scopes as $scope) {
426 1
            $authCode->addScope($scope);
427
        }
428
429 6
        while ($maxGenerationAttempts-- > 0) {
430 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
431
            try {
432 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
433
434 4
                return $authCode;
435 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
436 1
                if ($maxGenerationAttempts === 0) {
437 1
                    throw $e;
438
                }
439
            }
440
        }
441
    }
442
443
    /**
444
     * @param AccessTokenEntityInterface $accessToken
445
     *
446
     * @throws OAuthServerException
447
     * @throws UniqueTokenIdentifierConstraintViolationException
448
     *
449
     * @return RefreshTokenEntityInterface
450
     */
451 10
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
452
    {
453 10
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
454
455 10
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
456 10
        $refreshToken->setExpiryDateTime((new \DateTime())->add($this->refreshTokenTTL));
457 10
        $refreshToken->setAccessToken($accessToken);
458
459 10
        while ($maxGenerationAttempts-- > 0) {
460 10
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
461
            try {
462 10
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
463
464 8
                return $refreshToken;
465 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
466 1
                if ($maxGenerationAttempts === 0) {
467 1
                    throw $e;
468
                }
469
            }
470
        }
471
    }
472
473
    /**
474
     * Generate a new unique identifier.
475
     *
476
     * @param int $length
477
     *
478
     * @throws OAuthServerException
479
     *
480
     * @return string
481
     */
482 25
    protected function generateUniqueIdentifier($length = 40)
483
    {
484
        try {
485 25
            return bin2hex(random_bytes($length));
486
            // @codeCoverageIgnoreStart
487
        } catch (\TypeError $e) {
488
            throw OAuthServerException::serverError('An unexpected error has occurred');
489
        } catch (\Error $e) {
490
            throw OAuthServerException::serverError('An unexpected error has occurred');
491
        } catch (\Exception $e) {
492
            // If you get this message, the CSPRNG failed hard.
493
            throw OAuthServerException::serverError('Could not generate a random string');
494
        }
495
        // @codeCoverageIgnoreEnd
496
    }
497
498
    /**
499
     * {@inheritdoc}
500
     */
501 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
502
    {
503 5
        $requestParameters = (array) $request->getParsedBody();
504
505
        return (
506 5
            array_key_exists('grant_type', $requestParameters)
507 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
508
        );
509
    }
510
511
    /**
512
     * {@inheritdoc}
513
     */
514 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
515
    {
516 1
        return false;
517
    }
518
519
    /**
520
     * {@inheritdoc}
521
     */
522 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
523
    {
524 1
        throw new \LogicException('This grant cannot validate an authorization request');
525
    }
526
527
    /**
528
     * {@inheritdoc}
529
     */
530 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
531
    {
532 1
        throw new \LogicException('This grant cannot complete an authorization request');
533
    }
534
}
535