CodeGrantTrait   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 188
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 5
dl 0
loc 188
ccs 61
cts 61
cp 1
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A codeSetIntegration() 0 4 1
A codeGetIntegration() 0 4 1
A codeGetClientId() 0 4 1
A codeGetRedirectUri() 0 4 1
A codeGetScope() 0 6 2
A codeGetState() 0 4 1
A codeGetCode() 0 4 1
B codeAskResourceOwnerForApproval() 0 44 5
B codeIssueToken() 0 35 10
A codeReadStringValue() 0 5 3
1
<?php declare(strict_types=1);
2
3
namespace Limoncello\OAuthServer\GrantTraits;
4
5
/**
6
 * Copyright 2015-2019 [email protected]
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 * http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
use Limoncello\OAuthServer\Contracts\ClientInterface;
22
use Limoncello\OAuthServer\Contracts\Integration\CodeIntegrationInterface;
23
use Limoncello\OAuthServer\Exceptions\OAuthCodeRedirectException;
24
use Limoncello\OAuthServer\Exceptions\OAuthTokenBodyException;
25
use Psr\Http\Message\ResponseInterface;
26
use function array_key_exists;
27
use function explode;
28
use function is_string;
29
use function strlen;
30
31
/**
32
 * @package Limoncello\OAuthServer
33
 *
34
 * @link https://tools.ietf.org/html/rfc6749#section-1.3
35
 */
36
trait CodeGrantTrait
37
{
38
    /**
39
     * @var CodeIntegrationInterface
40
     */
41
    private $codeIntegration;
42 44
43
    /**
44 44
     * @param CodeIntegrationInterface $integration
45
     *
46
     * @return void
47
     */
48
    public function codeSetIntegration(CodeIntegrationInterface $integration): void
49
    {
50 10
        $this->codeIntegration = $integration;
51
    }
52 10
53
    /**
54
     * @return CodeIntegrationInterface
55
     */
56
    protected function codeGetIntegration(): CodeIntegrationInterface
57
    {
58
        return $this->codeIntegration;
59
    }
60 8
61
    /**
62 8
     * @param string[] $parameters
63
     *
64
     * @return string|null
65
     */
66
    protected function codeGetClientId(array $parameters): ?string
67
    {
68
        return $this->codeReadStringValue($parameters, 'client_id');
69
    }
70 11
71
    /**
72 11
     * @param string[] $parameters
73
     *
74
     * @return string|null
75
     */
76
    protected function codeGetRedirectUri(array $parameters): ?string
77
    {
78
        return $this->codeReadStringValue($parameters, 'redirect_uri');
79
    }
80 4
81
    /**
82 4
     * @param string[] $parameters
83
     *
84 4
     * @return string[]|null
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
85
     */
86
    protected function codeGetScope(array $parameters): ?array
87
    {
88
        $scope = $this->codeReadStringValue($parameters, 'scope');
89
90
        return empty($scope) === false ? explode(' ', $scope) : null;
91
    }
92 6
93
    /**
94 6
     * @param string[] $parameters
95
     *
96
     * @return string|null
97
     */
98
    protected function codeGetState(array $parameters): ?string
99
    {
100
        return $this->codeReadStringValue($parameters, 'state');
101
    }
102 6
103
    /**
104 6
     * @param string[] $parameters
105
     *
106
     * @return string|null
107
     */
108
    protected function codeGetCode(array $parameters): ?string
109
    {
110
        return $this->codeReadStringValue($parameters, 'code');
111
    }
112
113
    /**
114
     * @param string[]        $parameters
115 6
     * @param ClientInterface $client
116
     * @param string|null     $redirectUri
117
     * @param int|null        $maxStateLength
118
     *
119
     * @return ResponseInterface
120
     */
121 6
    protected function codeAskResourceOwnerForApproval(
122 6
        array $parameters,
123 1
        ClientInterface $client,
124 1
        string $redirectUri = null,
125 1
        int $maxStateLength = null
126 1
    ): ResponseInterface {
127
        $state = $this->codeGetState($parameters);
128
        if ($maxStateLength !== null && strlen($state) > $maxStateLength) {
129
            throw new OAuthCodeRedirectException(
130 5
                OAuthCodeRedirectException::ERROR_INVALID_REQUEST,
131 1
                $redirectUri,
132 1
                $state
133 1
            );
134 1
        }
135
136
        if ($client->isCodeGrantEnabled() === false) {
137
            throw new OAuthCodeRedirectException(
138 4
                OAuthCodeRedirectException::ERROR_UNAUTHORIZED_CLIENT,
139
                $redirectUri,
140 4
                $state
141 4
            );
142 1
        }
143 1
144 1
        $scope = $this->codeGetScope($parameters);
145 1
        list ($isScopeValid, $scopeList, $isScopeModified) =
146
            $this->codeGetIntegration()->codeValidateScope($client, $scope);
147
        if ($isScopeValid === false) {
148
            throw new OAuthCodeRedirectException(
149 3
                OAuthCodeRedirectException::ERROR_INVALID_SCOPE,
150 3
                $redirectUri,
151 3
                $state
152 3
            );
153 3
        }
154 3
155
        $response = $this->codeGetIntegration()->codeCreateAskResourceOwnerForApprovalResponse(
156
            $client,
157 3
            $redirectUri,
158
            $isScopeModified,
159
            $scopeList,
160
            $state
161
        );
162
163
        return $response;
164
    }
165
166
    /**
167
     * @param string[]             $parameters
168
     * @param ClientInterface|null $determinedClient
169
     *
170 7
     * @return ResponseInterface
171
     *
172
     * @SuppressWarnings(PHPMD.ElseExpression)
173 7
     * @SuppressWarnings(PHPMD.NPathComplexity)
174 1
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
175
     */
176
    protected function codeIssueToken(array $parameters, ClientInterface $determinedClient = null): ResponseInterface
177 6
    {
178 6
        // client_id is required @link https://tools.ietf.org/html/rfc6749#section-4.1.3
179
        if ($determinedClient === null || $determinedClient->isCodeGrantEnabled() === false) {
180 1
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
181
        }
182
183 5
        if (($codeValue = $this->codeGetCode($parameters)) === null ||
184 1
            ($code = $this->codeGetIntegration()->codeReadAuthenticationCode($codeValue)) === null
185 1
        ) {
186
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
187
        }
188 4
189 1
        if ($code->hasBeenUsedEarlier() === true) {
190
            $this->codeGetIntegration()->codeRevokeTokens($code);
191
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
192 3
        }
193
194 3
        if ($code->getClientIdentifier() !== $determinedClient->getIdentifier()) {
195 3
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
196
        }
197 1
198
        if ($code->getRedirectUriString() !== null) {
199
            // REQUIRED, if the "redirect_uri" parameter was included in the authorization request
200
            if (($redirectUri = $this->codeGetRedirectUri($parameters)) === null ||
201 2
                $redirectUri !== $code->getRedirectUriString()
202
            ) {
203 2
                throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
204
            }
205
        }
206
207
        $response = $this->codeGetIntegration()->codeCreateAccessTokenResponse($code, $parameters);
208
209
        return $response;
210
    }
211
212 14
    /**
213
     * @param array  $parameters
214 14
     * @param string $name
215 14
     *
216
     * @return null|string
217
     */
218
    private function codeReadStringValue(array $parameters, string $name): ?string
219
    {
220
        return array_key_exists($name, $parameters) === true && is_string($value = $parameters[$name]) === true ?
221
            $value : null;
0 ignored issues
show
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
222
    }
223
}
224