Completed
Pull Request — master (#987)
by
unknown
04:24
created

RefreshTokenGrant::respondToAccessTokenRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 0
cts 27
cp 0
rs 9.28
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 12
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 DateInterval;
15
use Exception;
16
use League\OAuth2\Server\Exception\OAuthServerException;
17
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
18
use League\OAuth2\Server\RequestEvent;
19
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
20
use Psr\Http\Message\ServerRequestInterface;
21
22
/**
23
 * Refresh token grant.
24
 */
25
class RefreshTokenGrant extends AbstractGrant
26
{
27
    /**
28
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
29
     */
30
    public function __construct(RefreshTokenRepositoryInterface $refreshTokenRepository)
31
    {
32
        $this->setRefreshTokenRepository($refreshTokenRepository);
33
34
        $this->refreshTokenTTL = new DateInterval('P1M');
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function respondToAccessTokenRequest(
41
        ServerRequestInterface $request,
42
        ResponseTypeInterface $responseType,
43
        DateInterval $accessTokenTTL
44
    ) {
45
        // Validate request
46
        $client = $this->validateClient($request);
47
        $oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
48
        $scopes = $this->validateScopes($this->getRequestParameter(
49
            'scope',
50
            $request,
51
            implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes']))
52
        );
53
54
        // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
55
        // the request doesn't include any new scopes
56
        foreach ($scopes as $scope) {
57
            if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
58
                throw OAuthServerException::invalidScope($scope->getIdentifier());
59
            }
60
        }
61
62
        // Expire old tokens
63
        $this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
64
        $this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
65
66
        // Issue and persist new tokens
67
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
68
        $refreshToken = $this->issueRefreshToken($accessToken);
69
70
        // Send events to emitter
71
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
72
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
73
74
        // Inject tokens into response
75
        $responseType->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...en['user_id'], $scopes) on line 67 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...
76
        $responseType->setRefreshToken($refreshToken);
0 ignored issues
show
Bug introduced by
It seems like $refreshToken defined by $this->issueRefreshToken($accessToken) on line 68 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...
77
78
        return $responseType;
79
    }
80
81
    /**
82
     * @param ServerRequestInterface $request
83
     * @param string                 $clientId
84
     *
85
     * @throws OAuthServerException
86
     *
87
     * @return array
88
     */
89
    protected function validateOldRefreshToken(ServerRequestInterface $request, $clientId)
90
    {
91
        $encryptedRefreshToken = $this->getRequestParameter('refresh_token', $request);
92
        if (is_null($encryptedRefreshToken)) {
93
            throw OAuthServerException::invalidRequest('refresh_token');
94
        }
95
96
        // Validate refresh token
97
        try {
98
            $refreshToken = $this->decrypt($encryptedRefreshToken);
99
        } catch (Exception $e) {
100
            throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e);
101
        }
102
103
        $refreshTokenData = json_decode($refreshToken, true);
104
        if ($refreshTokenData['client_id'] !== $clientId) {
105
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_CLIENT_FAILED, $request));
106
            throw OAuthServerException::invalidRefreshToken('Token is not linked to client');
107
        }
108
109
        if ($refreshTokenData['expire_time'] < time()) {
110
            throw OAuthServerException::invalidRefreshToken('Token has expired');
111
        }
112
113
        if ($this->refreshTokenRepository->isRefreshTokenRevoked($refreshTokenData['refresh_token_id']) === true) {
114
            throw OAuthServerException::invalidRefreshToken('Token has been revoked');
115
        }
116
117
        return $refreshTokenData;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function getIdentifier()
124
    {
125
        return 'refresh_token';
126
    }
127
}
128