Passed
Branch master (c0ae7d)
by Rutger
02:34
created

Oauth2AuthorizeAction::run()   F

Complexity

Conditions 41
Paths 3727

Size

Total Lines 278
Code Lines 165

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 117
CRAP Score 41.0262

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 165
c 1
b 0
f 0
dl 0
loc 278
ccs 117
cts 120
cp 0.975
rs 0
cc 41
nc 3727
nop 1
crap 41.0262

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
namespace rhertogh\Yii2Oauth2Server\controllers\web\server;
4
5
use GuzzleHttp\Psr7\Response as Psr7Response;
6
use League\OAuth2\Server\Exception\OAuthServerException;
7
use rhertogh\Yii2Oauth2Server\controllers\web\Oauth2ServerController;
8
use rhertogh\Yii2Oauth2Server\controllers\web\server\base\Oauth2BaseServerAction;
9
use rhertogh\Yii2Oauth2Server\exceptions\Oauth2OidcServerException;
10
use rhertogh\Yii2Oauth2Server\helpers\Psr7Helper;
11
use rhertogh\Yii2Oauth2Server\helpers\UrlHelper;
12
use rhertogh\Yii2Oauth2Server\interfaces\components\authorization\Oauth2ClientAuthorizationRequestInterface;
13
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\request\Oauth2OidcAuthenticationRequestInterface;
14
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\scope\Oauth2OidcScopeInterface;
15
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\user\Oauth2OidcUserComponentInterface;
16
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface;
17
use rhertogh\Yii2Oauth2Server\Oauth2Module;
18
use Yii;
19
use yii\base\InvalidConfigException;
20
use yii\web\BadRequestHttpException;
21
use yii\web\HttpException;
22
use yii\web\Request;
23
use yii\web\UnauthorizedHttpException;
24
25
/**
26
 * @property Oauth2ServerController $controller
27
 */
28
class Oauth2AuthorizeAction extends Oauth2BaseServerAction
29
{
30 38
    public function run($clientAuthorizationRequestId = null)
31
    {
32
        try {
33 38
            $request = Yii::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->request can also be of type yii\web\Request. However, the property $request is declared as type yii\console\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
34
            /** @var yii\web\User $user */
35 38
            $user = Yii::$app->user;
36 38
            $module = $this->controller->module;
37
38 38
            if ($module->enableOpenIdConnect) {
39 38
                if (!($user instanceof Oauth2OidcUserComponentInterface)) {
40 1
                    throw new InvalidConfigException(
41
                        'OpenId Connect is enabled but user component does not implement '
42
                        . Oauth2OidcUserComponentInterface::class
43
                    );
44
                }
45
46 37
                $oidcRequest = $this->getRequestParam(
47
                    $request,
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type yii\console\Request; however, parameter $request of rhertogh\Yii2Oauth2Serve...tion::getRequestParam() does only seem to accept yii\web\Request, maybe add an additional type check? ( Ignorable by Annotation )

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

47
                    /** @scrutinizer ignore-type */ $request,
Loading history...
48
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_REQUEST
49
                );
50 37
                if ($oidcRequest !== null) {
51 1
                    throw Oauth2OidcServerException::requestParameterNotSupported();
52
                }
53
54 36
                $oidcRequestUri = $this->getRequestParam(
55
                    $request,
56
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_REQUEST_URI
57
                );
58 36
                if ($oidcRequestUri !== null) {
59 1
                    throw Oauth2OidcServerException::requestUriParameterNotSupported();
60
                }
61
            }
62
63 35
            $server = $module->getAuthorizationServer();
64 33
            $psr7Request = Psr7Helper::yiiToPsr7Request($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type yii\console\Request; however, parameter $request of rhertogh\Yii2Oauth2Serve...per::yiiToPsr7Request() does only seem to accept yii\web\Request, maybe add an additional type check? ( Ignorable by Annotation )

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

64
            $psr7Request = Psr7Helper::yiiToPsr7Request(/** @scrutinizer ignore-type */ $request);
Loading history...
65 33
            $authRequest = $server->validateAuthorizationRequest($psr7Request);
66
67 33
            $requestedScopeIdentifiers = array_map(fn($scope) => $scope->getIdentifier(), $authRequest->getScopes());
68
69
            /** @var Oauth2ClientInterface $client */
70 33
            $client = $authRequest->getClient();
71
72 33
            if (!$client->validateAuthRequestScopes($requestedScopeIdentifiers, $unauthorizedScopes)) {
73 1
                throw OAuthServerException::invalidScope(
74 1
                    array_shift($unauthorizedScopes),
75 1
                    $authRequest->getRedirectUri()
76
                );
77
            }
78
79
            if (
80 32
                !$client->isAuthCodeWithoutPkceAllowed()
81
                // PKCE is not supported in the implicit flow.
82 32
                && $authRequest->getGrantTypeId() != Oauth2Module::GRANT_TYPE_IDENTIFIER_IMPLICIT
83
            ) {
84 31
                if (empty($request->get('code_challenge'))) {
85 2
                    throw new BadRequestHttpException(
86
                        'PKCE is required for this client when using grant type "'
87 2
                            . $authRequest->getGrantTypeId() . '".'
88
                    );
89 29
                } elseif ($request->get('code_challenge_method', 'plain') === 'plain') {
90 1
                    throw new BadRequestHttpException('PKCE code challenge mode "plain" is not allowed.');
91
                }
92
            }
93
94 29
            if ($clientAuthorizationRequestId) {
95 11
                $clientAuthorizationRequest = $module->getClientAuthReqSession($clientAuthorizationRequestId);
96
                if (
97 11
                    $clientAuthorizationRequest
98 11
                    && $clientAuthorizationRequest->getState()
99 10
                    && !Yii::$app->security->compareString(
100 10
                        $clientAuthorizationRequest->getState(),
101 11
                        $authRequest->getState()
102
                    )
103
                ) {
104 1
                    throw new UnauthorizedHttpException('Invalid state.');
105
                }
106
            }
107
108 28
            if (empty($clientAuthorizationRequest)) {
109 24
                $prompts = explode(
110
                    ' ',
111 24
                    $this->getRequestParam(
0 ignored issues
show
Bug introduced by
It seems like $this->getRequestParam($...QUEST_PARAMETER_PROMPT) can also be of type array; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

111
                    /** @scrutinizer ignore-type */ $this->getRequestParam(
Loading history...
112
                        $request,
113
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT
114
                    )
115
                )
116 24
                    ?? [];
117
118
                if (
119 24
                    in_array(Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE, $prompts)
120 24
                    && (count($prompts) > 1)
121
                ) {
122 1
                    throw new BadRequestHttpException(
123
                        'When the "prompt" parameter contains "none" other values are not allowed.'
124
                    );
125
                }
126
127
                // Ignore `offline_access` scope if prompt doesn't contain 'consent' (or pre-approved via config).
128
                // See https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess.
129
                if (
130 23
                    in_array(Oauth2OidcScopeInterface::OPENID_CONNECT_SCOPE_OFFLINE_ACCESS, $requestedScopeIdentifiers)
131 23
                    && !in_array(Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_CONSENT, $prompts)
132 23
                    && !$client->getOpenIdConnectAllowOfflineAccessWithoutConsent()
133
                ) {
134 1
                    $requestedScopeIdentifiers = array_diff(
135
                        $requestedScopeIdentifiers,
136 1
                        [Oauth2OidcScopeInterface::OPENID_CONNECT_SCOPE_OFFLINE_ACCESS]
137
                    );
138
                }
139
140 23
                $maxAge = $this->getRequestParam(
141
                    $request,
142
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_MAX_AGE
143
                );
144 23
                if ($maxAge === '') {
145 1
                    $maxAge = null;
146 22
                } elseif ($maxAge !== null) {
147 4
                    $maxAge = (int)$maxAge;
148
                }
149
150
                /** @var Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest */
151 23
                $clientAuthorizationRequest = Yii::createObject([
152
                    'class' => Oauth2ClientAuthorizationRequestInterface::class,
153
                    'module' => $module,
154 23
                    'userAuthenticatedBeforeRequest' => !$user->isGuest,
155 23
                    'clientIdentifier' => $authRequest->getClient()->getIdentifier(),
156 23
                    'state' => $authRequest->getState(),
157
                    'requestedScopeIdentifiers' => $requestedScopeIdentifiers,
158 23
                    'grantType' => $authRequest->getGrantTypeId(),
159 23
                    'authorizeUrl' => $request->absoluteUrl,
160 23
                    'redirectUri' => $authRequest->getRedirectUri(),
161
                    'prompts' => $prompts,
162
                    'maxAge' => $maxAge,
163
                ]);
164
            }
165
166 27
            if ($user->isGuest) {
167
                if (
168 4
                    in_array(
169
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
170 4
                        $clientAuthorizationRequest->getPrompts()
171
                    )
172
                ) {
173
                    // User authentication disallowed by OpenID Connect.
174 1
                    throw Oauth2OidcServerException::loginRequired($authRequest->getRedirectUri());
175
                }
176
177 3
                $module->setClientAuthReqSession($clientAuthorizationRequest);
178 3
                $user->setReturnUrl($clientAuthorizationRequest->getAuthorizationRequestUrl());
179
//                $user->setReturnUrl(UrlHelper::addQueryParams($request->absoluteUrl, [
180
//                    'clientAuthorizationRequestId' => $clientAuthorizationRequest->getRequestId(),
181
//                ]));
182
183 3
                return Yii::$app->response->redirect($user->loginUrl);
184
            }
185
186
            // Check if reauthentication is required.
187
            if (
188
                (
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (in_array(rhertogh\Yii2O...nticatedDuringRequest(), Probably Intended Meaning: in_array(rhertogh\Yii2Oa...ticatedDuringRequest())
Loading history...
189
                    (// true in case user was authenticated before request and oidc prompt requires login.
190 25
                        in_array(
191
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_LOGIN,
192 25
                            $clientAuthorizationRequest->getPrompts()
193
                        )
194 2
                        && $clientAuthorizationRequest->wasUserAuthenticatedBeforeRequest()
195
                    )
196
                    ||
197
                    (// true in case oidc max_age is set and the user was authenticated before the maximum time allowed.
198 24
                        $clientAuthorizationRequest->getMaxAge() !== null
199
                        && (
200 4
                            (time() - $module->getUserIdentity()->getLatestAuthenticatedAt()->getTimestamp())
0 ignored issues
show
Bug introduced by
Are you sure the usage of $module->getUserIdentity() targeting rhertogh\Yii2Oauth2Serve...dule::getUserIdentity() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
201 25
                            > $clientAuthorizationRequest->getMaxAge()
202
                        )
203
                    )
204
                )
205 25
                && !$clientAuthorizationRequest->wasUserAthenticatedDuringRequest()
206
            ) {
207
                // Prevent redirect loop.
208 4
                $redirectAttempt = (int)$request->get('redirectAttempt', 0);
209 4
                if ($redirectAttempt > 3) {
210
                    // This error most likely occurs if the User Controller does not correctly performs
211
                    // user reauthentication and redirect back to this action without calling
212
                    // `setUserAuthenticatedDuringRequest(true)` on the $clientAuthorizationRequest.
213
                    throw new HttpException(
214
                        501,
215
                        'Reauthentication not correctly implemented, aborting due to redirect loop.'
216
                    );
217
                }
218
219 4
                $module->setClientAuthReqSession($clientAuthorizationRequest);
220 4
                $user->setReturnUrl(
221 4
                    UrlHelper::addQueryParams($clientAuthorizationRequest->getAuthorizationRequestUrl(), [
222 4
                        'redirectAttempt' => $redirectAttempt + 1,
223
                    ])
224
                );
225 4
                return $user->reauthenticationRequired($clientAuthorizationRequest);
226
            }
227
228 22
            $userAccountSelection = $client->getUserAccountSelection() ?? $module->defaultUserAccountSelection;
229
230 22
            if (empty($clientAuthorizationRequest->getUserIdentity())) {
231
                if (
232 18
                    ($userAccountSelection === Oauth2Module::USER_ACCOUNT_SELECTION_ALWAYS)
233
                    || (
234 16
                        $userAccountSelection === Oauth2Module::USER_ACCOUNT_SELECTION_UPON_CLIENT_REQUEST
235 16
                        && in_array(
236
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_SELECT_ACCOUNT,
237 18
                            $clientAuthorizationRequest->getPrompts()
238
                        )
239
                    )
240
                ) {
241
                    if (
242 4
                        in_array(
243
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
244 4
                            $clientAuthorizationRequest->getPrompts()
245
                        )
246
                    ) {
247 2
                        throw Oauth2OidcServerException::accountSelectionRequired(
248
                            'User account selection is required but the "prompt" parameter is set to "none".',
249 2
                            $authRequest->getRedirectUri()
250
                        );
251
                    }
252 2
                    $accountSelectionRequiredResponse = $user->accountSelectionRequired($clientAuthorizationRequest);
253 2
                    if ($accountSelectionRequiredResponse === false) {
254
                        throw Oauth2OidcServerException::accountSelectionRequired(
255
                            'User account selection is not supported by the server.',
256
                            $authRequest->getRedirectUri(),
257
                        );
258
                    }
259 2
                    $module->setClientAuthReqSession($clientAuthorizationRequest);
260 2
                    $user->setReturnUrl($clientAuthorizationRequest->getAuthorizationRequestUrl());
261 2
                    return $accountSelectionRequiredResponse;
262
                } else {
263 14
                    $clientAuthorizationRequest->setUserIdentity($module->getUserIdentity());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $module->getUserIdentity() targeting rhertogh\Yii2Oauth2Serve...dule::getUserIdentity() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
264
                }
265
            }
266
267
            if (
268 19
                $clientAuthorizationRequest->isAuthorizationNeeded()
269 2
                || in_array(
270
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_CONSENT,
271 19
                    $clientAuthorizationRequest->getPrompts()
272
                )
273
            ) {
274
                if (
275 18
                    in_array(
276
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
277 18
                        $clientAuthorizationRequest->getPrompts()
278
                    )
279
                ) {
280
                    // User consent is disallowed by OpenID Connect.
281 1
                    throw Oauth2OidcServerException::consentRequired($authRequest->getRedirectUri());
282
                }
283 17
                if ($clientAuthorizationRequest->isCompleted()) {
284 6
                    $authorizationApproved = $clientAuthorizationRequest->isApproved();
285
                    // Cleanup session data.
286 6
                    $module->removeClientAuthReqSession($clientAuthorizationRequest->getRequestId());
287
                } else {
288 17
                    return $module->generateClientAuthReqRedirectResponse($clientAuthorizationRequest);
289
                }
290
            } else {
291
                // All scopes are already approved (or are default).
292 2
                $authorizationApproved = true;
293
            }
294
295 8
            $authRequest->setUser($clientAuthorizationRequest->getUserIdentity());
296 8
            $authRequest->setAuthorizationApproved($authorizationApproved);
297
298 8
            $psr7Response = Psr7Helper::yiiToPsr7Response(Yii::$app->response);
0 ignored issues
show
Bug introduced by
It seems like Yii::app->response can also be of type yii\console\Response; however, parameter $response of rhertogh\Yii2Oauth2Serve...er::yiiToPsr7Response() does only seem to accept yii\web\Response, maybe add an additional type check? ( Ignorable by Annotation )

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

298
            $psr7Response = Psr7Helper::yiiToPsr7Response(/** @scrutinizer ignore-type */ Yii::$app->response);
Loading history...
299 8
            $psr7Response = $server->completeAuthorizationRequest($authRequest, $psr7Response);
300
301 7
            return Psr7Helper::psr7ToYiiResponse($psr7Response);
302
303
//        } catch (OAuthServerException $e) {
304
//            return $this->processOAuthServerException($e);
305 16
        } catch (\Exception $e) {
306 16
            Yii::error((string)$e, __METHOD__);
307 16
            return $this->processException($e);
308
//            $message = Yii::t('oauth2', 'Unable to respond to authorization request.');
309
//            throw Oauth2ServerHttpException::createFromException($message, $e);
310
        }
311
    }
312
313
    /**
314
     * @param Request $request
315
     * @param string $name
316
     * @return mixed
317
     */
318 37
    protected function getRequestParam($request, $name, $defaultValue = null)
319
    {
320 37
        return $request->post($name) ?? $request->get($name, $defaultValue);
321
    }
322
}
323