Passed
Push — master ( fe04ef...dd22d8 )
by Andrew
30:17 queued 28:24
created

RefreshTokenGrant::respondToAccessTokenRequest()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 51
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 6

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 6
eloc 25
c 5
b 1
f 0
nc 17
nop 3
dl 0
loc 51
ccs 28
cts 28
cp 1
crap 6
rs 8.8977

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * OAuth 2.0 Refresh token grant.
5
 *
6
 * @author      Alex Bilbie <[email protected]>
7
 * @copyright   Copyright (c) Alex Bilbie
8
 * @license     http://mit-license.org/
9
 *
10
 * @link        https://github.com/thephpleague/oauth2-server
11
 */
12
13
declare(strict_types=1);
14
15
namespace League\OAuth2\Server\Grant;
16
17
use DateInterval;
18
use Exception;
19
use League\OAuth2\Server\Exception\OAuthServerException;
20
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
21
use League\OAuth2\Server\RequestAccessTokenEvent;
22
use League\OAuth2\Server\RequestEvent;
23
use League\OAuth2\Server\RequestRefreshTokenEvent;
24
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
25
use Psr\Http\Message\ServerRequestInterface;
26
27
use function implode;
28
use function in_array;
29
use function json_decode;
30
use function time;
31
32
/**
33
 * Refresh token grant.
34
 */
35
class RefreshTokenGrant extends AbstractGrant
36
{
37 14
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
38
    {
39 14
        $this->setRefreshTokenRepository($refreshTokenRepository);
40
41 14
        $this->refreshTokenTTL = new DateInterval('P1M');
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 13
    public function respondToAccessTokenRequest(
48
        ServerRequestInterface $request,
49
        ResponseTypeInterface $responseType,
50
        DateInterval $accessTokenTTL
51
    ): ResponseTypeInterface {
52
        // Validate request
53 13
        $client = $this->validateClient($request);
54 13
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
55
56 8
        $scopes = $this->validateScopes(
57 8
            $this->getRequestParameter(
58 8
                'scope',
59 8
                $request,
60 8
                implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes'])
61 8
            )
62 8
        );
63
64
        // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
65
        // the request doesn't include any new scopes
66 8
        foreach ($scopes as $scope) {
67 8
            if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
68 1
                throw OAuthServerException::invalidScope($scope->getIdentifier());
69
            }
70
        }
71
72 7
        $scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
73
74
        // Expire old tokens
75 7
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
76 7
        if ($this->revokeRefreshTokens) {
77 6
            $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
78
        }
79
80
        // Issue and persist new access token
81 7
        $userId = $oldRefreshToken['user_id'];
82 7
        if (is_int($userId)) {
83 1
            $userId = (string) $userId;
84
        }
85 7
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $userId, $scopes);
86 7
        $this->getEmitter()->emit(new RequestAccessTokenEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request, $accessToken));
87 7
        $responseType->setAccessToken($accessToken);
88
89
        // Issue and persist new refresh token if given
90 7
        $refreshToken = $this->issueRefreshToken($accessToken);
91
92 7
        if ($refreshToken !== null) {
93 5
            $this->getEmitter()->emit(new RequestRefreshTokenEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request, $refreshToken));
94 5
            $responseType->setRefreshToken($refreshToken);
95
        }
96
97 7
        return $responseType;
98
    }
99
100
    /**
101
     * @throws OAuthServerException
102
     *
103
     * @return array<string, mixed>
104
     */
105 13
    protected function validateOldRefreshToken(ServerRequestInterface $request, string $clientId): array
106
    {
107 13
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request)
108 1
            ?? throw OAuthServerException::invalidRequest('refresh_token');
109
110
        // Validate refresh token
111
        try {
112 12
            $refreshToken = $this->decrypt($encryptedRefreshToken);
113 1
        } catch (Exception $e) {
114 1
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e);
115
        }
116
117 11
        $refreshTokenData = json_decode($refreshToken, true);
118 11
        if ($refreshTokenData['client_id'] !== $clientId) {
119 1
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
120 1
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
121
        }
122
123 10
        if ($refreshTokenData['expire_time'] < time()) {
124 1
            throw OAuthServerException::invalidRefreshToken('Token has expired');
125
        }
126
127 9
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
128 1
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
129
        }
130
131 8
        return $refreshTokenData;
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137 14
    public function getIdentifier(): string
138
    {
139 14
        return 'refresh_token';
140
    }
141
}
142