Completed
Push — master ( a339d9...a77732 )
by Andrew
24s
created

AbstractGrant::validateRedirectUri()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 3
nop 3
crap 5
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->setClient($client);
378 17
        $accessToken->setUserIdentifier($userIdentifier);
379 17
        $accessToken->setExpiryDateTime((new \DateTime())->add($accessTokenTTL));
380
381 17
        foreach ($scopes as $scope) {
382 13
            $accessToken->addScope($scope);
383
        }
384
385 17
        while ($maxGenerationAttempts-- > 0) {
386 17
            $accessToken->setIdentifier($this->generateUniqueIdentifier());
387
            try {
388 17
                $this->accessTokenRepository->persistNewAccessToken($accessToken);
389
390 15
                return $accessToken;
391 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
392 1
                if ($maxGenerationAttempts === 0) {
393 1
                    throw $e;
394
                }
395
            }
396
        }
397
    }
398
399
    /**
400
     * Issue an auth code.
401
     *
402
     * @param \DateInterval          $authCodeTTL
403
     * @param ClientEntityInterface  $client
404
     * @param string                 $userIdentifier
405
     * @param string|null            $redirectUri
406
     * @param ScopeEntityInterface[] $scopes
407
     *
408
     * @throws OAuthServerException
409
     * @throws UniqueTokenIdentifierConstraintViolationException
410
     *
411
     * @return AuthCodeEntityInterface
412
     */
413 6
    protected function issueAuthCode(
414
        \DateInterval $authCodeTTL,
415
        ClientEntityInterface $client,
416
        $userIdentifier,
417
        $redirectUri,
418
        array $scopes = []
419
    ) {
420 6
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
421
422 6
        $authCode = $this->authCodeRepository->getNewAuthCode();
423 6
        $authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
424 6
        $authCode->setClient($client);
425 6
        $authCode->setUserIdentifier($userIdentifier);
426
427 6
        if ($redirectUri !== null) {
428 1
            $authCode->setRedirectUri($redirectUri);
429
        }
430
431 6
        foreach ($scopes as $scope) {
432 1
            $authCode->addScope($scope);
433
        }
434
435 6
        while ($maxGenerationAttempts-- > 0) {
436 6
            $authCode->setIdentifier($this->generateUniqueIdentifier());
437
            try {
438 6
                $this->authCodeRepository->persistNewAuthCode($authCode);
439
440 4
                return $authCode;
441 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
442 1
                if ($maxGenerationAttempts === 0) {
443 1
                    throw $e;
444
                }
445
            }
446
        }
447
    }
448
449
    /**
450
     * @param AccessTokenEntityInterface $accessToken
451
     *
452
     * @throws OAuthServerException
453
     * @throws UniqueTokenIdentifierConstraintViolationException
454
     *
455
     * @return RefreshTokenEntityInterface
456
     */
457 10
    protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
458
    {
459 10
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
460
461 10
        $refreshToken = $this->refreshTokenRepository->getNewRefreshToken();
462 10
        $refreshToken->setExpiryDateTime((new \DateTime())->add($this->refreshTokenTTL));
463 10
        $refreshToken->setAccessToken($accessToken);
464
465 10
        while ($maxGenerationAttempts-- > 0) {
466 10
            $refreshToken->setIdentifier($this->generateUniqueIdentifier());
467
            try {
468 10
                $this->refreshTokenRepository->persistNewRefreshToken($refreshToken);
469
470 8
                return $refreshToken;
471 2
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
472 1
                if ($maxGenerationAttempts === 0) {
473 1
                    throw $e;
474
                }
475
            }
476
        }
477
    }
478
479
    /**
480
     * Generate a new unique identifier.
481
     *
482
     * @param int $length
483
     *
484
     * @throws OAuthServerException
485
     *
486
     * @return string
487
     */
488 25
    protected function generateUniqueIdentifier($length = 40)
489
    {
490
        try {
491 25
            return bin2hex(random_bytes($length));
492
            // @codeCoverageIgnoreStart
493
        } catch (\TypeError $e) {
494
            throw OAuthServerException::serverError('An unexpected error has occurred');
495
        } catch (\Error $e) {
496
            throw OAuthServerException::serverError('An unexpected error has occurred');
497
        } catch (\Exception $e) {
498
            // If you get this message, the CSPRNG failed hard.
499
            throw OAuthServerException::serverError('Could not generate a random string');
500
        }
501
        // @codeCoverageIgnoreEnd
502
    }
503
504
    /**
505
     * {@inheritdoc}
506
     */
507 5
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
508
    {
509 5
        $requestParameters = (array) $request->getParsedBody();
510
511
        return (
512 5
            array_key_exists('grant_type', $requestParameters)
513 5
            && $requestParameters['grant_type'] === $this->getIdentifier()
514
        );
515
    }
516
517
    /**
518
     * {@inheritdoc}
519
     */
520 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
521
    {
522 1
        return false;
523
    }
524
525
    /**
526
     * {@inheritdoc}
527
     */
528 1
    public function validateAuthorizationRequest(ServerRequestInterface $request)
529
    {
530 1
        throw new \LogicException('This grant cannot validate an authorization request');
531
    }
532
533
    /**
534
     * {@inheritdoc}
535
     */
536 1
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
537
    {
538 1
        throw new \LogicException('This grant cannot complete an authorization request');
539
    }
540
}
541