Passed
Pull Request — master (#1470)
by
unknown
33:34
created

RefreshTokenGrant::validateOldRefreshToken()   F

Complexity

Conditions 13
Paths 438

Size

Total Lines 67
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 13

Importance

Changes 0
Metric Value
cc 13
eloc 38
c 0
b 0
f 0
nc 438
nop 2
dl 0
loc 67
ccs 9
cts 9
cp 1
crap 13
rs 3.2305

How to fix   Long Method    Complexity   

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 DateTimeImmutable;
19
use Exception;
20
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
21
use League\OAuth2\Server\Exception\OAuthServerException;
22
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
23
use League\OAuth2\Server\RequestAccessTokenEvent;
24
use League\OAuth2\Server\RequestEvent;
25
use League\OAuth2\Server\RequestRefreshTokenEvent;
26
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
27
use Psr\Http\Message\ServerRequestInterface;
28
29
use function implode;
30
use function in_array;
31
use function json_decode;
32
use function time;
33
34
/**
35
 * Refresh token grant.
36
 */
37 14
class RefreshTokenGrant extends AbstractGrant
38
{
39 14
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
40
    {
41 14
        $this->setRefreshTokenRepository($refreshTokenRepository);
42
43
        $this->refreshTokenTTL = new DateInterval('P1M');
44
    }
45
46
    /**
47 13
     * {@inheritdoc}
48
     */
49
    public function respondToAccessTokenRequest(
50
        ServerRequestInterface $request,
51
        ResponseTypeInterface $responseType,
52
        DateInterval $accessTokenTTL
53 13
    ): ResponseTypeInterface {
54 13
        // Validate request
55
        $client = $this->validateClient($request);
56 8
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
57 8
58 8
        if ($oldRefreshToken == null) {
59 8
            // Probably should throw an exception here instead
60 8
            return $responseType;
61 8
        }
62 8
63
        $originalScopes = $oldRefreshToken->getScopes();
64
        $originalScopeArray = [];
65
        foreach ($originalScopes as $scopeEntity) {
66 8
            $originalScopeArray[$scopeEntity->getIdentifier()] = $scopeEntity->getIdentifier();
67 8
        }
68 1
        $originalScopeArray = array_values($originalScopeArray);
69
70
        $scopes = $this->validateScopes(
71
            $this->getRequestParameter(
72 7
                'scope',
73
                $request,
74
                implode(self::SCOPE_DELIMITER_STRING, $originalScopeArray)
75 7
            )
76 7
        );
77 6
78
        // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
79
        // the request doesn't include any new scopes
80
        foreach ($scopes as $scope) {
81 7
            if (in_array($scope->getIdentifier(), $originalScopeArray, true) === false) {
82 7
                throw OAuthServerException::invalidScope($scope->getIdentifier());
83 1
            }
84
        }
85 7
86 7
        $scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
87 7
88
        // Expire old tokens
89
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken->getAccessToken()->getIdentifier());
90 7
        if ($this->revokeRefreshTokens) {
91
            $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken->getIdentifier());
92 7
        }
93 5
94 5
        // Issue and persist new access token
95
        $userId = $oldRefreshToken->getUserIdentifier();
96
        if (is_int($userId)) {
0 ignored issues
show
introduced by
The condition is_int($userId) is always false.
Loading history...
97 7
            $userId = (string) $userId;
98
        }
99
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $userId, $scopes);
100
        $this->getEmitter()->emit(new RequestAccessTokenEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request, $accessToken));
101
        $responseType->setAccessToken($accessToken);
102
103
        // Issue and persist new refresh token if given
104
        $refreshToken = $this->issueRefreshToken($accessToken);
105 13
106
        if ($refreshToken !== null) {
107 13
            $this->getEmitter()->emit(new RequestRefreshTokenEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request, $refreshToken));
108 1
            $responseType->setRefreshToken($refreshToken);
109
        }
110
111
        return $responseType;
112 12
    }
113 1
114 1
    /**
115
     * @throws OAuthServerException
116
     *
117 11
     * @return RefreshTokenEntityInterface
118 11
     */
119 1
    protected function validateOldRefreshToken(ServerRequestInterface $request, string $clientId): ?RefreshTokenEntityInterface
120 1
    {
121
        $refreshTokenParam = $this->getRequestParameter('refresh_token', $request)
122
            ?? throw OAuthServerException::invalidRequest('refresh_token');
123 10
124 1
        // Validate refresh token
125
        if ($this->canUseCrypt()) {
126
            try {
127 9
                $refreshTokenJson = $this->decrypt($refreshTokenParam);
128 1
                $refreshTokenData = json_decode($refreshTokenJson, true);
129
130
                $refreshTokenEntity = $this->refreshTokenRepository->getNewRefreshToken();
131 8
132
                if ($refreshTokenEntity == null) {
133
                    return null;
134
                }
135
136
                if (isset($refreshTokenData['refresh_token_id'])) {
137 14
                    $refreshTokenEntity->setIdentifier($refreshTokenData['refresh_token_id']);
138
                }
139 14
140
                if (isset($refreshTokenData['expire_time'])) {
141
                    $expire = new DateTimeImmutable();
142
                    $expire = $expire->setTimestamp($refreshTokenData['expire_time']);
143
                    $refreshTokenEntity->setExpiryDateTime($expire);
144
                }
145
146
                if (isset($refreshTokenData['client_id'])) {
147
                    $client = $this->getClientEntityOrFail($refreshTokenData['client_id'], $request);
148
                    $refreshTokenEntity->setClient($client);
149
                }
150
151
                if (isset($refreshTokenData['scopes'])) {
152
                    $scopes = $this->validateScopes($refreshTokenData['scopes']);
153
154
                    $refreshTokenEntity->setScopes($scopes);
155
                }
156
157
                if (isset($refreshTokenData['user_id'])) {
158
                    $refreshTokenEntity->setUserIdentifier((string)$refreshTokenData['user_id']);
159
                }
160
161
                if (isset($refreshTokenData['access_token_id'])) {
162
                    $accessToken = $this->accessTokenRepository->getAccessTokenEntity($refreshTokenData['access_token_id']);
163
                    $refreshTokenEntity->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken can also be of type null; however, parameter $accessToken of League\OAuth2\Server\Ent...rface::setAccessToken() does only seem to accept League\OAuth2\Server\Ent...essTokenEntityInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

163
                    $refreshTokenEntity->setAccessToken(/** @scrutinizer ignore-type */ $accessToken);
Loading history...
164
                }
165
            } catch (Exception $e) {
166
                throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e);
167
            }
168
        } else {
169
            $refreshTokenEntity = $this->refreshTokenRepository->getRefreshTokenEntity($refreshTokenParam);
170
        }
171
172
        if ($refreshTokenEntity->getClient()->getIdentifier() !== $clientId) {
0 ignored issues
show
Bug introduced by
The method getClient() does not exist on League\OAuth2\Server\Rep...okenRepositoryInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

172
        if ($refreshTokenEntity->/** @scrutinizer ignore-call */ getClient()->getIdentifier() !== $clientId) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
173
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
174
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
175
        }
176
177
        if ($refreshTokenEntity->getExpiryDateTime()->getTimestamp() < time()) {
0 ignored issues
show
Bug introduced by
The method getExpiryDateTime() does not exist on League\OAuth2\Server\Rep...okenRepositoryInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

177
        if ($refreshTokenEntity->/** @scrutinizer ignore-call */ getExpiryDateTime()->getTimestamp() < time()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
178
            throw OAuthServerException::invalidRefreshToken('Token has expired');
179
        }
180
181
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenEntity->getIdentifier()) === true) {
0 ignored issues
show
Bug introduced by
The method getIdentifier() does not exist on League\OAuth2\Server\Rep...okenRepositoryInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

181
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenEntity->/** @scrutinizer ignore-call */ getIdentifier()) === true) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
182
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
183
        }
184
185
        return $refreshTokenEntity;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $refreshTokenEntity could return the type League\OAuth2\Server\Rep...okenRepositoryInterface which is incompatible with the type-hinted return League\OAuth2\Server\Ent...kenEntityInterface|null. Consider adding an additional type-check to rule them out.
Loading history...
186
    }
187
188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function getIdentifier(): string
192
    {
193
        return 'refresh_token';
194
    }
195
}
196