Completed
Push — master ( 6e52f0...d9a404 )
by Alexandre
02:29
created

RefreshTokenGrantType::grant()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 29
nc 10
nop 2
dl 0
loc 45
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: GCC-MED
5
 * Date: 18/01/2018
6
 * Time: 12:00
7
 */
8
9
namespace OAuth2OLD\GrantTypes;
10
11
12
use OAuth2OLD\Config;
13
use OAuth2OLD\EndpointMessages\Token\AccessTokenResponse;
14
use OAuth2OLD\Exceptions\OAuthException;
15
use OAuth2OLD\Repositories\ConfigurationRepository;
16
use OAuth2OLD\Roles\ClientInterface;
17
use OAuth2OLD\Roles\Clients\RegisteredClient;
18
use OAuth2OLD\ScopePolicy\ScopePolicyManager;
19
use OAuth2OLD\Storages\AccessTokenStorageInterface;
20
use OAuth2OLD\Storages\RefreshTokenStorageInterface;
21
use Psr\Http\Message\ResponseInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
class RefreshTokenGrantType implements GrantTypeInterface
25
{
26
    /**
27
     * @var AccessTokenStorageInterface
28
     */
29
    private $accessTokenStorage;
30
    /**
31
     * @var RefreshTokenStorageInterface
32
     */
33
    private $refreshTokenStorage;
34
    /**
35
     * @var ScopePolicyManager
36
     */
37
    private $scopePolicyManager;
38
    /**
39
     * @var ConfigurationRepository
40
     */
41
    private $configurationRepository;
42
43
    public function __construct(ConfigurationRepository $configurationRepository,
44
                                ScopePolicyManager $scopePolicyManager,
45
                                AccessTokenStorageInterface $accessTokenStorage,
46
                                RefreshTokenStorageInterface $refreshTokenStorage)
47
    {
48
        $this->scopePolicyManager = $scopePolicyManager;
49
        $this->accessTokenStorage = $accessTokenStorage;
50
        $this->refreshTokenStorage = $refreshTokenStorage;
51
        $this->configurationRepository = $configurationRepository;
52
    }
53
54
    function getUri(): string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
55
    {
56
        return 'refresh_token';
57
    }
58
59
    function grant(ServerRequestInterface $request, ClientInterface $client): ResponseInterface
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
60
    {
61
        if (!$client instanceof RegisteredClient) {
62
            throw new OAuthException('unauthorized_client',
63
                'Unauthorized client type',
64
                'https://tools.ietf.org/html/rfc6749#section-5.2');
65
        }
66
67
        $refreshToken = $request->getParsedBody()['refresh_token'] ?? '';
68
        if(!$refreshToken) {
69
            throw new OAuthException('invalid_request', 'Missing a required parameter : refresh_token',
70
                'https://tools.ietf.org/html/rfc6749#section-4.3');
71
        }
72
73
        $refreshToken = $this->refreshTokenStorage->get($refreshToken);
74
        if(!$refreshToken || $refreshToken->getClientId() !== $client->getIdentifier()) {
75
            throw new OAuthException('invalid_grant', 'Refresh token is invalid',
76
                'https://tools.ietf.org/html/rfc6749#section-4.3');
77
        }
78
79
        if(!is_null($refreshToken->getExpiresAt()) && $refreshToken->getExpiresAt() < time()) {
80
            $this->refreshTokenStorage->revoke($refreshToken->getToken());
81
82
            throw new OAuthException('invalid_grant', 'Refresh token has expired',
83
                'https://tools.ietf.org/html/rfc6749#section-4.3');
84
        }
85
86
        $includedScopes = isset($request->getParsedBody()['scope']) ? explode(' ', $request->getParsedBody()['scope']) : null;
87
        if(is_array($includedScopes) && !empty(array_diff($includedScopes, explode(' ', $refreshToken->getToken())))) {
88
            throw new OAuthException('invalid_scope',
89
                'Some of scope included are not granted for this token. Scope granted : ' . $refreshToken->getScope(),
90
                'https://tools.ietf.org/html/rfc6749#section-6');
91
        }
92
93
        // issue an access token token and, optionally, a refresh token
94
        $accessToken = $this->accessTokenStorage->create($client->getIdentifier(), $refreshToken->getUserId(), $refreshToken->getScope());
95
        $newRefreshToken = null;
96
        if($this->configurationRepository->getConfig(Config::REGENERATE_REFRESH_TOKENS_AFTER_USE)) {
97
            $this->refreshTokenStorage->revoke($refreshToken->getToken());
98
            $newRefreshToken = $this->refreshTokenStorage->create(
99
                $refreshToken->getClientId(), $refreshToken->getUserId(), $refreshToken->getScope())->getToken();
100
        }
101
102
        return new AccessTokenResponse($accessToken->getToken(), $accessToken->getType(),
103
            $accessToken->getExpiresAt() - time(), $newRefreshToken);
104
    }
105
}