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

Token::authorizationCode()   C

Complexity

Conditions 10
Paths 11

Size

Total Lines 68
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
cc 10
eloc 32
nc 11
nop 1
dl 0
loc 68
rs 6.0995
c 0
b 0
f 0
ccs 0
cts 44
cp 0
crap 110

How to fix   Long Method    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: Alexandre
5
 * Date: 30/12/2017
6
 * Time: 18:50
7
 */
8
9
namespace OAuth2OLD\Endpoint\Server;
10
11
use GuzzleHttp\Psr7\Uri;
12
use OAuth2OLD\Credential\AccessToken;
13
use OAuth2OLD\Credential\RefreshToken;
14
use OAuth2OLD\Credential\TokenType\BearerToken;
15
use OAuth2OLD\Endpoint\Config;
16
use OAuth2OLD\Endpoint\Server\Messages\AccessToken\AccessTokenRequest;
17
use OAuth2OLD\Endpoint\Server\Messages\AccessToken\AccessTokenResponse;
18
use OAuth2OLD\Endpoint\Server\Messages\Authorization\AuthorizationRequest;
19
use OAuth2OLD\Endpoint\Server\Messages\AccessToken\ErrorResponse;
20
use OAuth2OLD\GrantType\AuthorizationCode;
21
use OAuth2OLD\GrantType\InvalidGrantType;
22
use OAuth2OLD\Storage\ClientStorage;
23
use OAuth2OLD\Role\Client;
24
use OAuth2OLD\Role\Client\RegisteredClient;
25
use OAuth2OLD\Role\Client\Type\ClientPassword;
0 ignored issues
show
Bug introduced by
The type OAuth2OLD\Role\Client\Type\ClientPassword was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use Psr\Http\Message\ServerRequestInterface;
27
28
29
/**
30
 * Class Token
31
 * @package OAuth2\endpoints
32
 *
33
 * @see https://tools.ietf.org/html/rfc6749#section-3.2
34
 *
35
 * Token Endpoint
36
 *
37
 *     The token endpoint is used by the client to obtain an access token by
38
 * presenting its authorization grant or refresh token.  The token
39
 * endpoint is used with every authorization grant except for the
40
 * implicit grant type (since an access token is issued directly).
41
 *
42
 * The means through which the client obtains the location of the token
43
 * endpoint are beyond the scope of this specification, but the location
44
 * is typically provided in the service documentation.
45
 *
46
 * The endpoint URI MAY include an "application/x-www-form-urlencoded"
47
 * formatted (per Appendix B) query component ([RFC3986] Section 3.4),
48
 * which MUST be retained when adding additional query parameters.  The
49
 * endpoint URI MUST NOT include a fragment component.
50
 *
51
 * Since requests to the token endpoint result in the transmission of
52
 * clear-text credentials (in the HTTP request and response), the
53
 * authorization server MUST require the use of TLS as described in
54
 * Section 1.6 when sending requests to the token endpoint.
55
 *
56
 * The client MUST use the HTTP "POST" method when making access token
57
 * requests.
58
 *
59
 * Parameters sent without a value MUST be treated as if they were
60
 * omitted from the request.  The authorization server MUST ignore
61
 * unrecognized request parameters.  Request and response parameters
62
 * MUST NOT be included more than once.
63
 */
64
class Token
65
{
66
    /**
67
     * @var Server
68
     */
69
    private $server;
70
71
    /**
72
     * Token constructor.
73
     * @param Server $server
74
     */
75
    public function __construct(Server $server)
76
    {
77
        $this->server = $server;
78
    }
79
80
    protected function getClientByIdentifier(string $identifier)
81
    {
82
        return $this->server->getClientProvider()->getByIdentifier($identifier);
0 ignored issues
show
Bug introduced by
The method getClientProvider() does not exist on OAuth2OLD\Endpoint\Server\Server. Did you maybe mean getClient()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

82
        return $this->server->/** @scrutinizer ignore-call */ getClientProvider()->getByIdentifier($identifier);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
83
    }
84
85
    /**
86
     * @see https://tools.ietf.org/html/rfc6749#section-3.3
87
     *
88
     * Access Token Scope
89
     *
90
     *     The authorization and token endpoints allow the client to specify the
91
     * scope of the access request using the "scope" request parameter.  In
92
     * turn, the authorization server uses the "scope" response parameter to
93
     * inform the client of the scope of the access token issued.
94
     *
95
     * The value of the scope parameter is expressed as a list of space-
96
     * delimited, case-sensitive strings.  The strings are defined by the
97
     * authorization server.  If the value contains multiple space-delimited
98
     * strings, their order does not matter, and each string adds an
99
     * additional access range to the requested scope.
100
     *
101
     * scope       = scope-token *( SP scope-token )
102
     * scope-token = 1*( %x21 / %x23-5B / %x5D-7E )
103
     *
104
     * The authorization server MAY fully or partially ignore the scope
105
     * requested by the client, based on the authorization server policy or
106
     * the resource owner's instructions.  If the issued access token scope
107
     * is different from the one requested by the client, the authorization
108
     * server MUST include the "scope" response parameter to inform the
109
     * client of the actual scope granted.
110
     *
111
     * If the client omits the scope parameter when requesting
112
     * authorization, the authorization server MUST either process the
113
     * request using a pre-defined default value or fail the request
114
     * indicating an invalid scope.  The authorization server SHOULD
115
     * document its scope requirements and default value (if defined).
116
     *
117
     * @param AccessTokenRequest $request
118
     * @return AccessTokenResponse|ErrorResponse
119
     */
120
    public function authorizationCode(AccessTokenRequest $request)
121
    {
122
//        var_dump($request);die;
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
123
        // todo is client in dev mode ?
124
        if (!$this->server->isSecure()) {
125
            return new ErrorResponse('invalid_request', 'Require TLS',
126
                'https://tools.ietf.org/html/rfc6749#section-3.2');
127
        }
128
129
130
        // todo require authentication, even for not confidential client ? own authenticator system ?
131
        $client = $this->server->getClient();
132
        if (!$client) {
133
            if (!$request->getClientId()) {
134
                return new ErrorResponse('invalid_request', 'Missing client_id parameter',
135
                    'https://tools.ietf.org/html/rfc6749#section-4.1.3');
136
            }
137
            $client = $this->getClientByIdentifier($request->getClientId());
138
139
            // todo 401  HTTP 401 (Unauthorized) status code and include the "WWW-Authenticate" response header field
140
            /**
141
             * Client authentication failed (e.g., unknown client, no
142
             * client authentication included, or unsupported
143
             * authentication method).  The authorization server MAY
144
             * return an HTTP 401 (Unauthorized) status code to indicate
145
             * which HTTP authentication schemes are supported.  If the
146
             * client attempted to authenticate via the "Authorization"
147
             * request header field, the authorization server MUST
148
             * respond with an HTTP 401 (Unauthorized) status code and
149
             * include the "WWW-Authenticate" response header field
150
             * matching the authentication scheme used by the client.
151
             */
152
            if (!$client || $this->server->getGuard()->requireAuthentication($client)) {
153
                return new ErrorResponse('invalid_client', 'Client not authenticated',
154
                    'https://tools.ietf.org/html/rfc6749#section-4.1.3', 401, [
155
                        'WWW-Authenticate' => 'Basic'
156
                    ]);
157
            }
158
        }
159
160
        $grantType = $this->server->getGrantType($request->getGrantType());
161
        if (!$grantType) {
162
            return new ErrorResponse('unsupported_grant_type', 'The grant type is not supported by the
163
               authorization server',
164
                'https://tools.ietf.org/html/rfc6749#section-5.2');
165
        }
166
167
        try {
168
            $redirectUri = $grantType->grant($request, $client);
169
        }
170
        catch(InvalidGrantType $e) {
171
            return new ErrorResponse('invalid_grant', $e->getErrorDescription(), $e->getErrorUri());
172
        }
173
174
        if ($redirectUri && $redirectUri !== $request->getRedirectUri()) {
175
            return new ErrorResponse('invalid_request', 'Invalid redirect uri',
176
                'https://tools.ietf.org/html/rfc6749#section-4.1.3');
177
        }
178
179
        $accessToken = AccessToken::generate();
180
        $refreshToken = RefreshToken::generate();
181
182
        $accessToken = new AccessToken($accessToken);
0 ignored issues
show
Bug introduced by
$accessToken of type OAuth2OLD\Credential\AccessToken is incompatible with the type string expected by parameter $token of OAuth2OLD\Credential\AccessToken::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

182
        $accessToken = new AccessToken(/** @scrutinizer ignore-type */ $accessToken);
Loading history...
183
        $this->server->getStorage('access_token')->save($accessToken);
184
        $this->server->getStorage('refresh_token')->save($refreshToken);
185
        $scope = null; // todo get requested scope, if different, change it
186
        return new AccessTokenResponse(new Uri($request->getRedirectUri()),
187
            $accessToken->getToken(), \OAuth2OLD\Credential\Token::TYPE_BEARER, 3600, $refreshToken->getToken(), $scope);
188
    }
189
190
    public function refreshToken()
191
    {
192
193
    }
194
}