RefreshTokenGrant   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 105
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 43
c 5
b 1
f 0
dl 0
loc 105
ccs 48
cts 48
cp 1
rs 10
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getIdentifier() 0 3 1
A __construct() 0 5 1
A validateOldRefreshToken() 0 27 5
B respondToAccessTokenRequest() 0 51 6
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