Completed
Pull Request — master (#910)
by Andrew
01:49
created

RefreshTokenGrant   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 1
cbo 7
dl 0
loc 103
ccs 41
cts 41
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A respondToAccessTokenRequest() 0 40 3
B validateOldRefreshToken() 0 30 6
A getIdentifier() 0 4 1
1
<?php
2
/**
3
 * OAuth 2.0 Refresh token 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
12
namespace League\OAuth2\Server\Grant;
13
14
use League\OAuth2\Server\Exception\OAuthServerException;
15
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
16
use League\OAuth2\Server\RequestEvent;
17
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
20
/**
21
 * Refresh token grant.
22
 */
23
class RefreshTokenGrant extends AbstractGrant
24
{
25
    /**
26
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
27
     */
28 9
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
29
    {
30 9
        $this->setRefreshTokenRepository($refreshTokenRepository);
31
32 9
        $this->refreshTokenTTL = new \DateInterval('P1M');
33 9
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 8
    public function respondToAccessTokenRequest(
39
        ServerRequestInterface $request,
40
        ResponseTypeInterface $responseType,
41
        \DateInterval $accessTokenTTL
42
    ) {
43
        // Validate request
44 8
        $client = $this->validateClient($request);
45 8
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
46 3
        $scopes = $this->validateScopes($this->getRequestParameter(
47 3
            'scope',
48 3
            $request,
49 3
            implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes']))
50
        );
51
52
        // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
53
        // the request doesn't include any new scopes
54 3
        foreach ($scopes as $scope) {
55 3
            if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
56 3
                throw OAuthServerException::invalidScope($scope->getIdentifier());
57
            }
58
        }
59
60
        // Expire old tokens
61 2
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
62 2
        $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
63
64
        // Issue and persist new tokens
65 2
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
66 2
        $refreshToken = $this->issueRefreshToken($accessToken);
67
68
        // Send events to emitter
69 2
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
70 2
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
71
72
        // Inject tokens into response
73 2
        $responseType->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...en['user_id'], $scopes) on line 65 can be null; however, League\OAuth2\Server\Res...rface::setAccessToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
74 2
        $responseType->setRefreshToken($refreshToken);
0 ignored issues
show
Bug introduced by
It seems like $refreshToken defined by $this->issueRefreshToken($accessToken) on line 66 can be null; however, League\OAuth2\Server\Res...face::setRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
75
76 2
        return $responseType;
77
    }
78
79
    /**
80
     * @param ServerRequestInterface $request
81
     * @param string                 $clientId
82
     *
83
     * @throws OAuthServerException
84
     *
85
     * @return array
86
     */
87 8
    protected function validateOldRefreshToken(ServerRequestInterface $request, $clientId)
88
    {
89 8
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request);
90 8
        if (is_null($encryptedRefreshToken)) {
91 1
            throw OAuthServerException::invalidRequest('refresh_token');
92
        }
93
94
        // Validate refresh token
95
        try {
96 7
            $refreshToken = $this->decrypt($encryptedRefreshToken);
97 1
        } catch (\Exception $e) {
98 1
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token');
99
        }
100
101 6
        $refreshTokenData = json_decode($refreshToken, true);
102 6
        if ($refreshTokenData['client_id'] !== $clientId) {
103 1
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
104 1
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
105
        }
106
107 5
        if ($refreshTokenData['expire_time'] < time()) {
108 1
            throw OAuthServerException::invalidRefreshToken('Token has expired');
109
        }
110
111 4
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
112 1
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
113
        }
114
115 3
        return $refreshTokenData;
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 9
    public function getIdentifier()
122
    {
123 9
        return 'refresh_token';
124
    }
125
}
126