Completed
Push — master ( 2c698e...b8e183 )
by Andrew
18s queued 13s
created

RefreshTokenGrant::respondToAccessTokenRequest()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 47
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 5

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 5
eloc 22
c 3
b 1
f 0
nc 9
nop 3
dl 0
loc 47
ccs 25
cts 25
cp 1
crap 5
rs 9.2568
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 13
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
38
    {
39 13
        $this->setRefreshTokenRepository($refreshTokenRepository);
40
41 13
        $this->refreshTokenTTL = new DateInterval('P1M');
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 12
    public function respondToAccessTokenRequest(
48
        ServerRequestInterface $request,
49
        ResponseTypeInterface $responseType,
50
        DateInterval $accessTokenTTL
51
    ): ResponseTypeInterface {
52
        // Validate request
53 12
        $client = $this->validateClient($request);
54 12
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
55
56 7
        $scopes = $this->validateScopes(
57 7
            $this->getRequestParameter(
58 7
                'scope',
59 7
                $request,
60 7
                implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes'])
61 7
            )
62 7
        );
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 7
        foreach ($scopes as $scope) {
67 7
            if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
68 1
                throw OAuthServerException::invalidScope($scope->getIdentifier());
69
            }
70
        }
71
72 6
        $scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
73
74
        // Expire old tokens
75 6
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
76 6
        if ($this->revokeRefreshTokens) {
77 5
            $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
78
        }
79
80
        // Issue and persist new access token
81 6
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
82 6
        $this->getEmitter()->emit(new RequestAccessTokenEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request, $accessToken));
83 6
        $responseType->setAccessToken($accessToken);
84
85
        // Issue and persist new refresh token if given
86 6
        $refreshToken = $this->issueRefreshToken($accessToken);
87 5
88
        if ($refreshToken !== null) {
89 5
            $this->getEmitter()->emit(new RequestRefreshTokenEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request, $refreshToken));
90 3
            $responseType->setRefreshToken($refreshToken);
91 3
        }
92
93
        return $responseType;
94
    }
95 6
96
    /**
97
     * @throws OAuthServerException
98
     *
99
     * @return array<string, mixed>
100
     */
101
    protected function validateOldRefreshToken(ServerRequestInterface $request, string $clientId): array
102
    {
103 12
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request)
104
            ?? throw OAuthServerException::invalidRequest('refresh_token');
105 12
106 1
        // Validate refresh token
107
        try {
108
            $refreshToken = $this->decrypt($encryptedRefreshToken);
109
        } catch (Exception $e) {
110 11
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e);
111 1
        }
112 1
113
        $refreshTokenData = json_decode($refreshToken, true);
114
        if ($refreshTokenData['client_id'] !== $clientId) {
115 10
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
116 10
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
117 1
        }
118 1
119
        if ($refreshTokenData['expire_time'] < time()) {
120
            throw OAuthServerException::invalidRefreshToken('Token has expired');
121 9
        }
122 1
123
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
124
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
125 8
        }
126 1
127
        return $refreshTokenData;
128
    }
129 7
130
    /**
131
     * {@inheritdoc}
132
     */
133
    public function getIdentifier(): string
134
    {
135 13
        return 'refresh_token';
136
    }
137
}
138