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

AbstractGrant::setClientRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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