Failed Conditions
Push — ng ( 6dd952...0976bc )
by Florent
16:09
created

createAuthorizationFromRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\AuthorizationEndpoint;
15
16
use OAuth2Framework\Component\AuthorizationEndpoint\ParameterChecker\ParameterCheckerManager;
17
use OAuth2Framework\Component\AuthorizationEndpoint\UserAccount\UserAccountCheckerManager;
18
use Psr\Http\Server\RequestHandlerInterface;
19
use Psr\Http\Server\MiddlewareInterface;
20
use OAuth2Framework\Component\AuthorizationEndpoint\ConsentScreen\ExtensionManager;
21
use OAuth2Framework\Component\AuthorizationEndpoint\Exception\OAuth2AuthorizationException;
22
use OAuth2Framework\Component\AuthorizationEndpoint\UserAccount\UserAccountDiscovery;
23
use OAuth2Framework\Component\Core\Exception\OAuth2Exception;
24
use Psr\Http\Message\ResponseInterface;
25
use Psr\Http\Message\ServerRequestInterface;
26
27
abstract class AuthorizationEndpoint implements MiddlewareInterface
28
{
29
    /**
30
     * @var UserAccountDiscovery
31
     */
32
    private $userAccountDiscovery;
33
34
    /**
35
     * @var UserAccountCheckerManager
36
     */
37
    private $userAccountCheckerManager;
38
39
    /**
40
     * @var ExtensionManager
41
     */
42
    private $consentScreenExtensionManager;
43
44
    /**
45
     * @var AuthorizationRequestLoader
46
     */
47
    private $authorizationRequestLoader;
48
49
    /**
50
     * @var ParameterCheckerManager
51
     */
52
    private $parameterCheckerManager;
53
54
    /**
55
     * AuthorizationEndpoint constructor.
56
     *
57
     * @param AuthorizationRequestLoader $authorizationRequestLoader
58
     * @param ParameterCheckerManager $parameterCheckerManager
59
     * @param UserAccountDiscovery $userAccountDiscovery
60
     * @param UserAccountCheckerManager $userAccountCheckerManager
61
     * @param ExtensionManager $consentScreenExtensionManager
62
     */
63
    public function __construct(AuthorizationRequestLoader $authorizationRequestLoader, ParameterCheckerManager $parameterCheckerManager, UserAccountDiscovery $userAccountDiscovery, UserAccountCheckerManager $userAccountCheckerManager, ExtensionManager $consentScreenExtensionManager)
64
    {
65
        $this->authorizationRequestLoader = $authorizationRequestLoader;
66
        $this->parameterCheckerManager = $parameterCheckerManager;
67
        $this->userAccountDiscovery = $userAccountDiscovery;
68
        $this->userAccountCheckerManager = $userAccountCheckerManager;
69
        $this->consentScreenExtensionManager = $consentScreenExtensionManager;
70
    }
71
72
    /**
73
     * @param ServerRequestInterface $request
74
     * @param Authorization          $authorization
75
     *
76
     * @return ResponseInterface
77
     */
78
    abstract protected function redirectToLoginPage(ServerRequestInterface $request, Authorization $authorization): ResponseInterface;
79
80
    /**
81
     * @param ServerRequestInterface $request
82
     * @param Authorization          $authorization
83
     *
84
     * @return ResponseInterface
85
     */
86
    abstract protected function processConsentScreen(ServerRequestInterface $request, Authorization $authorization): ResponseInterface;
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
92
    {
93
        try {
94
            $authorization = $this->createAuthorizationFromRequest($request);
95
            $isFullyAuthenticated = null;
96
            $userAccount = $this->userAccountDiscovery->find($isFullyAuthenticated);
97
            if (null === $authorization->getUserAccount()) {
98
                return $this->redirectToLoginPage($request, $authorization);
99
            }
100
            $authorization = $authorization->withUserAccount($userAccount, $isFullyAuthenticated);
0 ignored issues
show
Bug introduced by
It seems like $userAccount defined by $this->userAccountDiscov...($isFullyAuthenticated) on line 96 can be null; however, OAuth2Framework\Componen...tion::withUserAccount() 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...
Bug introduced by
It seems like $isFullyAuthenticated defined by null on line 95 can also be of type null; however, OAuth2Framework\Componen...tion::withUserAccount() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
101
            $this->userAccountCheckerManager->check($authorization);
102
            $authorization = $this->consentScreenExtensionManager->processBefore($request, $authorization);
103
104
            return $this->processConsentScreen($request, $authorization);
105
        } catch (OAuth2AuthorizationException $e) {
106
            $data = $e->getData();
0 ignored issues
show
Bug introduced by
The method getData() does not seem to exist on object<OAuth2Framework\C...AuthorizationException>.

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...
107
            if (null !== $e->getAuthorization()) {
108
                $redirectUri = $e->getAuthorization()->getRedirectUri();
109
                $responseMode = $e->getAuthorization()->getResponseMode();
110
                if (null !== $redirectUri && null !== $responseMode) {
111
                    $data['redirect_uri'] = $redirectUri;
112
                    $data['response_mode'] = $responseMode;
113
114
                    throw new OAuth2AuthorizationException(302, $data, $e->getAuthorization(), $e);
0 ignored issues
show
Documentation introduced by
$data is of type array<string,string|obje...eMode\\ResponseMode>"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$e->getAuthorization() is of type object<OAuth2Framework\C...Endpoint\Authorization>, but the function expects a null|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$e is of type object<OAuth2Framework\C...AuthorizationException>, but the function expects a object<OAuth2Framework\C...Endpoint\Authorization>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
115
                }
116
            }
117
118
            throw $e;
119
        } catch (Exception\ProcessAuthorizationException $e) {
120
            $authorization = $e->getAuthorization();
121
            $authorization = $this->consentScreenExtensionManager->processAfter($request, $authorization);
122
            if (false === $authorization->isAuthorized()) {
123
                $this->throwRedirectionException($authorization, OAuth2Exception::ERROR_ACCESS_DENIED, 'The resource owner denied access to your client.');
124
            }
125
126
            $responseType = $authorization->getResponseType();
127
128
            try {
129
                $authorization = $responseType->process($authorization);
130
            } catch (OAuth2Exception $e) {
131
                $this->throwRedirectionException($authorization, $e->getMessage(), $e->getErrorDescription());
132
            }
133
134
            return $this->buildResponse($authorization);
135
        } catch (Exception\CreateRedirectionException $e) {
136
            $this->throwRedirectionException($e->getAuthorization(), $e->getMessage(), $e->getDescription());
137
        } catch (Exception\ShowConsentScreenException $e) {
138
            return $this->processConsentScreen($request, $e->getAuthorization());
139
        } catch (Exception\RedirectToLoginPageException $e) {
140
            return $this->redirectToLoginPage($request, $e->getAuthorization());
141
        }
142
    }
143
144
    /**
145
     * @param Authorization $authorization
146
     *
147
     * @throws OAuth2Exception
148
     *
149
     * @return ResponseInterface
150
     */
151
    private function buildResponse(Authorization $authorization): ResponseInterface
152
    {
153
        if (null === $authorization->getResponseMode() || null === $authorization->getRedirectUri()) {
154
            throw new OAuth2Exception(400, ['error' => 'EEE', 'error_description' => 'FFF']);
0 ignored issues
show
Bug introduced by
The call to OAuth2Exception::__construct() misses a required argument $errorDescription.

This check looks for function calls that miss required arguments.

Loading history...
Documentation introduced by
array('error' => 'EEE', ..._description' => 'FFF') is of type array<string,string,{"er...description":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
155
        }
156
157
        $response = $authorization->getResponseMode()->buildResponse(
158
            $authorization->getRedirectUri(),
159
            $authorization->getResponseParameters()
160
        );
161
        foreach ($authorization->getResponseHeaders() as $k => $v) {
162
            $response = $response->withHeader($k, $v);
163
        }
164
165
        return $response;
166
    }
167
168
    /**
169
     * @param Authorization $authorization
170
     * @param string        $error
171
     * @param string        $error_description
172
     *
173
     * @throws OAuth2Exception
174
     */
175
    private function throwRedirectionException(Authorization $authorization, string $error, string $error_description)
176
    {
177
        $params = $authorization->getResponseParameters();
178
        if (null === $authorization->getResponseMode() || null === $authorization->getRedirectUri()) {
179
            throw new OAuth2Exception(400, $error, $error_description, $params);
0 ignored issues
show
Documentation introduced by
$params is of type array, but the function expects a object<Exception>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
180
        }
181
        $params += [
182
            'response_mode' => $authorization->getResponseMode(),
183
            'redirect_uri' => $authorization->getRedirectUri(),
184
        ];
185
186
        throw new OAuth2Exception(302, $error, $error_description, $params);
0 ignored issues
show
Documentation introduced by
$params is of type array, but the function expects a object<Exception>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
187
    }
188
189
190
    /**
191
     * @param ServerRequestInterface $request
192
     *
193
     * @return Authorization
194
     *
195
     * @throws \Http\Client\Exception
196
     * @throws \OAuth2Framework\Component\Core\Exception\OAuth2Exception
197
     */
198
    public function createAuthorizationFromRequest(ServerRequestInterface $request): Authorization
199
    {
200
        $authorization = $this->authorizationRequestLoader->load($request);
201
        $authorization = $this->parameterCheckerManager->process($authorization);
202
203
        return $authorization;
204
    }
205
}
206