Completed
Pull Request — master (#736)
by
unknown
59:12 queued 56:55
created

Authorizer::getClientId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of OAuth 2.0 Laravel.
5
 *
6
 * (c) Luca Degasperi <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LucaDegasperi\OAuth2Server;
13
14
use League\OAuth2\Server\AuthorizationServer as Issuer;
15
use League\OAuth2\Server\Exception\AccessDeniedException;
16
use League\OAuth2\Server\ResourceServer as Checker;
17
use League\OAuth2\Server\TokenType\TokenTypeInterface;
18
use League\OAuth2\Server\Util\RedirectUri;
19
use LucaDegasperi\OAuth2Server\Exceptions\NoActiveAccessTokenException;
20
use Symfony\Component\HttpFoundation\Request;
21
22
/**
23
 * This is the authorizer class.
24
 *
25
 * @author Luca Degasperi <[email protected]>
26
 */
27
class Authorizer
28
{
29
    /**
30
     * The authorization server (aka the issuer).
31
     *
32
     * @var \League\OAuth2\Server\AuthorizationServer
33
     */
34
    protected $issuer;
35
36
    /**
37
     * The resource server (aka the checker).
38
     *
39
     * @var \League\OAuth2\Server\ResourceServer
40
     */
41
    protected $checker;
42
43
    /**
44
     * The auth code request parameters.
45
     *
46
     * @var array
47
     */
48
    protected $authCodeRequestParams;
49
50
    /**
51
     * The redirect uri generator.
52
     *
53
     * @var bool|null
54
     */
55
    protected $redirectUriGenerator = null;
56
57
    /**
58
     * Create a new Authorizer instance.
59
     *
60
     * @param \League\OAuth2\Server\AuthorizationServer $issuer
61
     * @param \League\OAuth2\Server\ResourceServer $checker
62
     */
63
    public function __construct(Issuer $issuer, Checker $checker)
64
    {
65
        $this->issuer = $issuer;
66
        $this->checker = $checker;
67
        $this->authCodeRequestParams = [];
68
    }
69
70
    /**
71
     * Get the issuer.
72
     *
73
     * @return \League\OAuth2\Server\AuthorizationServer
74
     */
75
    public function getIssuer()
76
    {
77
        return $this->issuer;
78
    }
79
80
    /**
81
     * Get the checker.
82
     *
83
     * @return \League\OAuth2\Server\ResourceServer
84
     */
85
    public function getChecker()
86
    {
87
        return $this->checker;
88
    }
89
90
    /**
91
     * Get the current access token for the session.
92
     *
93
     * If the session does not have an active access token, an exception will be thrown.
94
     *
95
     * @throws \LucaDegasperi\OAuth2Server\Exceptions\NoActiveAccessTokenException
96
     *
97
     * @return \League\OAuth2\Server\Entity\AccessTokenEntity
98
     */
99
    public function getAccessToken()
100
    {
101
        $accessToken = $this->getChecker()->getAccessToken();
102
103
        if (is_null($accessToken)) {
104
            throw new NoActiveAccessTokenException('Tried to access session data without an active access token');
105
        }
106
107
        return $accessToken;
108
    }
109
110
    /**
111
     * Issue an access token if the request parameters are valid.
112
     *
113
     * @return array a response object for the protocol in use
114
     */
115
    public function issueAccessToken()
116
    {
117
        return $this->issuer->issueAccessToken();
118
    }
119
120
    /**
121
     * Get the Auth Code request parameters.
122
     *
123
     * @return array
124
     */
125
    public function getAuthCodeRequestParams()
126
    {
127
        return $this->authCodeRequestParams;
128
    }
129
130
    /**
131
     * Get a single parameter from the auth code request parameters.
132
     *
133
     * @param $key
134
     * @param null $default
135
     *
136
     * @return mixed
137
     */
138
    public function getAuthCodeRequestParam($key, $default = null)
139
    {
140
        if (array_key_exists($key, $this->authCodeRequestParams)) {
141
            return $this->authCodeRequestParams[$key];
142
        }
143
144
        return $default;
145
    }
146
147
    /**
148
     * Check the validity of the auth code request.
149
     *
150
     * @return null a response appropriate for the protocol in use
151
     */
152
    public function checkAuthCodeRequest()
153
    {
154
        $this->authCodeRequestParams = $this->issuer->getGrantType('authorization_code')->checkAuthorizeParams();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface League\OAuth2\Server\Grant\GrantTypeInterface as the method checkAuthorizeParams() does only exist in the following implementations of said interface: League\OAuth2\Server\Grant\AuthCodeGrant.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
155
    }
156
157
    /**
158
     * Issue an auth code.
159
     *
160
     * @param string $ownerType the auth code owner type
161
     * @param string $ownerId the auth code owner id
162
     * @param array $params additional parameters to merge
163
     *
164
     * @return string the auth code redirect url
165
     */
166
    public function issueAuthCode($ownerType, $ownerId, $params = [])
167
    {
168
        $params = array_merge($this->authCodeRequestParams, $params);
169
170
        return $this->issuer->getGrantType('authorization_code')->newAuthorizeRequest($ownerType, $ownerId, $params);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface League\OAuth2\Server\Grant\GrantTypeInterface as the method newAuthorizeRequest() does only exist in the following implementations of said interface: League\OAuth2\Server\Grant\AuthCodeGrant.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
171
    }
172
173
    /**
174
     * Generate a redirect uri when the auth code request is denied by the user.
175
     *
176
     * @return string a correctly formed url to redirect back to
177
     */
178
    public function authCodeRequestDeniedRedirectUri()
179
    {
180
        $error = new AccessDeniedException();
181
182
        return $this->getRedirectUriGenerator()->make($this->getAuthCodeRequestParam('redirect_uri'), [
183
                        'error' => $error->errorType,
184
                        'error_description' => $error->getMessage(),
185
                ]
186
        );
187
    }
188
189
    /**
190
     * Get the RedirectUri generator instance.
191
     *
192
     * @return RedirectUri
193
     */
194
    public function getRedirectUriGenerator()
195
    {
196
        if (is_null($this->redirectUriGenerator)) {
197
            $this->redirectUriGenerator = new RedirectUri();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \League\OAuth2\Server\Util\RedirectUri() of type object<League\OAuth2\Server\Util\RedirectUri> is incompatible with the declared type boolean|null of property $redirectUriGenerator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
198
        }
199
200
        return $this->redirectUriGenerator;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->redirectUriGenerator; of type League\OAuth2\Server\Util\RedirectUri|boolean adds the type boolean to the return on line 200 which is incompatible with the return type documented by LucaDegasperi\OAuth2Serv...getRedirectUriGenerator of type League\OAuth2\Server\Util\RedirectUri.
Loading history...
201
    }
202
203
    /**
204
     * Set the RedirectUri generator instance.
205
     *
206
     * @param $redirectUri
207
     */
208
    public function setRedirectUriGenerator($redirectUri)
209
    {
210
        $this->redirectUriGenerator = $redirectUri;
211
    }
212
213
    /**
214
     * Validate a request with an access token in it.
215
     *
216
     * @param bool $httpHeadersOnly whether or not to check only the http headers of the request
217
     * @param string|null $accessToken an access token to validate
218
     *
219
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use boolean.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
220
     */
221
    public function validateAccessToken($httpHeadersOnly = false, $accessToken = null)
222
    {
223
        return $this->checker->isValidRequest($httpHeadersOnly, $accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by parameter $accessToken on line 221 can also be of type string; however, League\OAuth2\Server\Res...erver::isValidRequest() does only seem to accept object<League\OAuth2\Ser...AccessTokenEntity>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
224
    }
225
226
    /**
227
     * get the scopes associated with the current request.
228
     *
229
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use \League\OAuth2\Server\Entity\ScopeEntity[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
230
     */
231
    public function getScopes()
232
    {
233
        return $this->getAccessToken()->getScopes();
234
    }
235
236
    /**
237
     * Check if the current request has all the scopes passed.
238
     *
239
     * @param string|array $scope the scope(s) to check for existence
240
     *
241
     * @return bool
242
     */
243
    public function hasScope($scope)
244
    {
245
        if (is_array($scope)) {
246
            foreach ($scope as $s) {
247
                if ($this->hasScope($s) === false) {
248
                    return false;
249
                }
250
            }
251
252
            return true;
253
        }
254
255
        return $this->getAccessToken()->hasScope($scope);
256
    }
257
258
    /**
259
     * Get the resource owner ID of the current request.
260
     *
261
     * @return string
262
     */
263
    public function getResourceOwnerId()
264
    {
265
        return $this->getAccessToken()->getSession()->getOwnerId();
266
    }
267
268
    /**
269
     * Get the resource owner type of the current request (client or user).
270
     *
271
     * @return string
272
     */
273
    public function getResourceOwnerType()
274
    {
275
        return $this->getAccessToken()->getSession()->getOwnerType();
276
    }
277
278
    /**
279
     * Get the client id of the current request.
280
     *
281
     * @return string
282
     */
283
    public function getClientId()
284
    {
285
        return $this->checker->getAccessToken()->getSession()->getClient()->getId();
286
    }
287
288
    /**
289
     * Set the request to use on the issuer and checker.
290
     *
291
     * @param \Symfony\Component\HttpFoundation\Request $request
292
     */
293
    public function setRequest(Request $request)
294
    {
295
        $this->issuer->setRequest($request);
296
        $this->checker->setRequest($request);
297
    }
298
299
    /**
300
     * Set the token type to use.
301
     *
302
     * @param \League\OAuth2\Server\TokenType\TokenTypeInterface $tokenType
303
     */
304
    public function setTokenType(TokenTypeInterface $tokenType)
305
    {
306
        $this->issuer->setTokenType($tokenType);
307
        $this->checker->setTokenType($tokenType);
308
    }
309
}
310