Completed
Pull Request — master (#924)
by
unknown
02:27
created

RefreshTokenGrant   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

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

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
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
29
    {
30
        $this->setRefreshTokenRepository($refreshTokenRepository);
31
32
        $this->refreshTokenTTL = new \DateInterval('P1M');
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function respondToAccessTokenRequest(
39
        ServerRequestInterface $request,
40
        ResponseTypeInterface $responseType,
41
        \DateInterval $accessTokenTTL
42
    ) {
43
        // Validate request
44
        $client = $this->validateClient($request);
45
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
46
        $scopes = $this->validateScopes($this->getRequestParameter(
47
            'scope',
48
            $request,
49
            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
        foreach ($scopes as $scope) {
55
            if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
56
                throw OAuthServerException::invalidScope($scope->getIdentifier());
57
            }
58
        }
59
60
        // Expire old tokens
61
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
62
        $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
63
64
        // Issue and persist new tokens
65
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
66
        $refreshToken = $this->issueRefreshToken($accessToken);
67
68
        // Send events to emitter
69
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
70
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
71
72
        // Inject tokens into response
73
        $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
        $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
        return $responseType;
77
    }
78
79
    /**
80
     * @param ServerRequestInterface $request
81
     * @param string                 $clientId
82
     *
83
     * @throws OAuthServerException
84
     *
85
     * @return array
86
     */
87
    protected function validateOldRefreshToken(ServerRequestInterface $request, $clientId)
88
    {
89
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request);
90
        if (is_null($encryptedRefreshToken)) {
91
            throw OAuthServerException::invalidRequest('refresh_token');
92
        }
93
94
        // Validate refresh token
95
        try {
96
            $refreshToken = $this->decrypt($encryptedRefreshToken);
97
        } catch (\Exception $e) {
98
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token');
99
        }
100
101
        $refreshTokenData = json_decode($refreshToken, true);
102
        if ($refreshTokenData['client_id'] !== $clientId) {
103
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
104
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
105
        }
106
107
        if ($refreshTokenData['expire_time'] < time()) {
108
            throw OAuthServerException::invalidRefreshToken('Token has expired');
109
        }
110
111
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
112
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
113
        }
114
115
        return $refreshTokenData;
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function getIdentifier()
122
    {
123
        return 'refresh_token';
124
    }
125
}
126