Completed
Push — master ( 8cd5f6...fa17b0 )
by CodexShaper
03:10 queued 11s
created

Manager::enableImplicitGrantType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace CodexShaper\OAuth2\Server;
4
5
use CodexShaper\OAuth2\Server\Repositories\AccessTokenRepository;
6
use CodexShaper\OAuth2\Server\Repositories\AuthCodeRepository;
7
use CodexShaper\OAuth2\Server\Repositories\ClientRepository;
8
use CodexShaper\OAuth2\Server\Repositories\RefreshTokenRepository;
9
use CodexShaper\OAuth2\Server\Repositories\ScopeRepository;
10
use CodexShaper\OAuth2\Server\Repositories\UserRepository;
11
use DateInterval;
12
use Defuse\Crypto\Key;
13
use League\OAuth2\Server\AuthorizationServer;
14
use League\OAuth2\Server\CryptKey;
15
use League\OAuth2\Server\Grant\AuthCodeGrant;
16
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
17
use League\OAuth2\Server\Grant\ImplicitGrant;
18
use League\OAuth2\Server\Grant\PasswordGrant;
19
use League\OAuth2\Server\Grant\RefreshTokenGrant;
20
use League\OAuth2\Server\ResourceServer;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, CodexShaper\OAuth2\Server\ResourceServer.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
21
use phpseclib\Crypt\RSA;
22
23
class Manager
24
{
25
    /**
26
     * Authorization server.
27
     *
28
     * @var string
29
     */
30
    protected $server;
31
32
    /**
33
     * All scopes.
34
     *
35
     * @var string
36
     */
37
    protected static $scopes = [];
38
39
    /**
40
     * Default scope.
41
     *
42
     * @var string
43
     */
44
    protected static $defaultScope;
45
46
    /**
47
     * Enable or didable implicit grant.
48
     *
49
     * @var string
50
     */
51
    protected static $isEnableImplicitGrant = false;
52
53
    /**
54
     * Refresh token expire at.
55
     *
56
     * @var string
57
     */
58
    protected static $refreshTokensExpireAt = 'P1Y';
59
60
    /**
61
     * token exipre at.
62
     *
63
     * @var string
64
     */
65
    protected static $tokensExpireAt = 'P1Y';
66
67
    /**
68
     * Create RSA authorisation keys.
69
     *
70
     * @return void
71
     */
72
    public static function keys($dir = null)
73
    {
74
        if (!$dir) {
75
            $dir = __DIR__.'/../storage/rsa';
76
        }
77
78
        if (!is_dir($dir)) {
79
            mkdir($dir, 0777, true);
80
        }
81
82
        $publicKey = $dir.'/oauth-public.key';
83
        $privateKey = $dir.'/oauth-private.key';
84
        $rsa = new RSA();
85
        $keys = $rsa->createKey(4096);
86
87
        file_put_contents($publicKey, $keys['publickey']);
88
        file_put_contents($privateKey, $keys['privatekey']);
89
    }
90
91
    /**
92
     * Add New scopes.
93
     *
94
     * @return void
95
     */
96
    public static function setScopes(array $scopes = [])
97
    {
98
        if (empty($scopes)) {
99
            return;
100
        }
101
102
        static::$scopes = array_merge(static::$scopes, $scopes);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge(static::$scopes, $scopes) of type array is incompatible with the declared type string of property $scopes.

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...
103
    }
104
105
    /**
106
     * Get all available scopes.
107
     *
108
     * @return array
109
     */
110
    public static function getScopes()
111
    {
112
        return static::$scopes;
113
    }
114
115
    /**
116
     * Given a client, grant type and optional user identifier validate the set of scopes requested are valid and optionally
117
     * append additional scopes or remove requested scopes.
118
     *
119
     * @param \League\OAuth2\Server\Entities\ScopeEntityInterface[] $scopes
120
     * @param string                                                $grantType
121
     * @param \League\OAuth2\Server\Entities\ClientEntityInterface  $clientEntity
0 ignored issues
show
Bug introduced by
There is no parameter named $clientEntity. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
122
     * @param null|string                                           $userIdentifier
0 ignored issues
show
Bug introduced by
There is no parameter named $userIdentifier. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
123
     *
124
     * @return \League\OAuth2\Server\Entities\ScopeEntityInterface[]
125
     */
126
    public static function filterScopes($scopes, $grantType)
127
    {
128
        if (!in_array($grantType, ['password', 'personal_access', 'client_credentials'])) {
129
            $scopes = array_filter($scopes, function ($scope) {
130
                return trim($scope->getIdentifier()) !== '*';
131
            });
132
        }
133
134
        return array_filter($scopes, function ($scope) {
135
            return static::hasScope($scope->getIdentifier());
136
        });
137
    }
138
139
    /**
140
     * Check scope exists or not.
141
     *
142
     * @param string $identifier
143
     *
144
     * @return bool
145
     */
146
    public static function hasScope($identifier)
147
    {
148
        return trim($identifier) === '*' || array_key_exists($identifier, array_flip(static::$scopes));
149
    }
150
151
    /**
152
     * Check is isset a scope or not.
153
     *
154
     * @param string $identifier
155
     *
156
     * @return bool
157
     */
158
    public static function isValidateScope($identifier)
159
    {
160
        return array_key_exists($identifier, array_flip(static::$scopes));
161
    }
162
163
    /**
164
     * Make the authorization service instance.
165
     *
166
     * @return \League\OAuth2\Server\AuthorizationServer
167
     */
168
    public function makeAuthorizationServer()
169
    {
170
        $encryptionKey = 'def00000069ceedc03a1f91fd51a49ce08ebb8580d688f4fbc3774c86aaa4df516eea0f72c1f62e3e577ec9f0c83c773b890222966bf93ac22e84a9eca55638be310665b';
171
172
        $this->server = new AuthorizationServer(
0 ignored issues
show
Documentation Bug introduced by
It seems like new \League\OAuth2\Serve...String($encryptionKey)) of type object<League\OAuth2\Server\AuthorizationServer> is incompatible with the declared type string of property $server.

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...
173
            new ClientRepository(),
174
            new AccessTokenRepository(),
175
            new ScopeRepository(),
176
            $this->makeCryptKey('private'),
177
            Key::loadFromAsciiSafeString($encryptionKey)
178
        );
179
180
        $this->server->setDefaultScope(static::$defaultScope);
181
        $this->enableGrantTypes();
182
183
        return $this->server;
184
    }
185
186
    /**
187
     * Enable All grant types.
188
     *
189
     * @return void
190
     */
191
    protected function enableGrantTypes()
192
    {
193
        $this->server->enableGrantType(
0 ignored issues
show
Bug introduced by
The method enableGrantType cannot be called on $this->server (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
194
            new ClientCredentialsGrant(),
195
            new DateInterval(static::$tokensExpireAt) // access tokens will expire after 1 hour
196
        );
197
198
        $this->enableAuthCodeGrant();
199
        $this->enablePasswordGrant();
200
        $this->enableRefreshTokenGrant();
201
202
        if (static::$isEnableImplicitGrant) {
203
            $this->server->enableGrantType(
0 ignored issues
show
Bug introduced by
The method enableGrantType cannot be called on $this->server (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
204
                new ImplicitGrant(new DateInterval(static::$tokensExpireAt)),
205
                new DateInterval(static::$tokensExpireAt) // access tokens will expire after 1 hour
206
            );
207
        }
208
    }
209
210
    /**
211
     * Enable Authorization code Grant.
212
     *
213
     * @return void
214
     */
215 View Code Duplication
    protected function enableAuthCodeGrant()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
    {
217
        $authCodeGrant = new AuthCodeGrant(
218
            new AuthCodeRepository(),
219
            new RefreshTokenRepository(),
220
            new DateInterval('PT10M')
221
        );
222
223
        $authCodeGrant->setRefreshTokenTTL(new DateInterval(static::$refreshTokensExpireAt));
224
225
        $this->server->enableGrantType(
0 ignored issues
show
Bug introduced by
The method enableGrantType cannot be called on $this->server (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
226
            $authCodeGrant,
227
            new DateInterval(static::$tokensExpireAt)
228
        );
229
    }
230
231
    /**
232
     * Enable Password Grant.
233
     *
234
     * @return void
235
     */
236 View Code Duplication
    protected function enablePasswordGrant()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237
    {
238
        $passwordGrant = new PasswordGrant(
239
            new UserRepository(),
240
            new RefreshTokenRepository()
241
        );
242
243
        $passwordGrant->setRefreshTokenTTL(new DateInterval(static::$refreshTokensExpireAt)); // refresh tokens will expire after 1 month
244
245
        // Enable the password grant on the server
246
        $this->server->enableGrantType(
0 ignored issues
show
Bug introduced by
The method enableGrantType cannot be called on $this->server (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
247
            $passwordGrant,
248
            new DateInterval(static::$tokensExpireAt) // access tokens will expire after 1 hour
249
        );
250
    }
251
252
    /**
253
     * Enable Refresh token Grant.
254
     *
255
     * @return void
256
     */
257 View Code Duplication
    protected function enableRefreshTokenGrant()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
258
    {
259
        $refreshTokenGrant = new RefreshTokenGrant(new RefreshTokenRepository());
260
        $refreshTokenGrant->setRefreshTokenTTL(new \DateInterval(static::$refreshTokensExpireAt)); // new refresh tokens will expire after 1 month
261
262
        // Enable the refresh token grant on the server
263
        $this->server->enableGrantType(
0 ignored issues
show
Bug introduced by
The method enableGrantType cannot be called on $this->server (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
264
            $refreshTokenGrant,
265
            new \DateInterval(static::$tokensExpireAt) // new access tokens will expire after an hour
266
        );
267
    }
268
269
    /**
270
     * Enable Implicit Grant.
271
     *
272
     * @param bool $isImplicit
273
     *
274
     * @return void
275
     */
276
    protected function enableImplicitGrantType($isImplicit = true)
277
    {
278
        static::$isEnableImplicitGrant = $isImplicit;
0 ignored issues
show
Documentation Bug introduced by
The property $isEnableImplicitGrant was declared of type string, but $isImplicit is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
279
    }
280
281
    /**
282
     * Create a resource server for validation.
283
     *
284
     * @return \League\OAuth2\Server\ResourServer
285
     */
286
    public function getResourceServer()
287
    {
288
        return new ResourceServer(
289
            new AccessTokenRepository(),
290
            $this->makeCryptKey('public')
291
        );
292
    }
293
294
    /**
295
     * Create a CryptKey instance without permissions check.
296
     *
297
     * @param string $key
0 ignored issues
show
Bug introduced by
There is no parameter named $key. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
298
     *
299
     * @return \League\OAuth2\Server\CryptKey
300
     */
301
    protected function makeCryptKey($type)
302
    {
303
        $key = __DIR__.'/../storage/rsa/oauth-'.$type.'.key';
304
305
        return new CryptKey($key, null, false);
306
    }
307
308
    public function validateUserForRequest($request)
309
    {
310
        $token = Model::instance('tokenModel')->find($request->getAttribute('oauth_access_token_id'));
311
        $client = Model::instance('clientModel')->find($request->getAttribute('oauth_client_id'));
312
313
        if (!$token || !$client) {
314
            return null;
315
        }
316
317
        if (!$token->user_id && !$client->user_id) {
318
            return null;
319
        }
320
321
        if ($token->user_id != null) {
322
            return $token->user_id;
323
        }
324
325
        return $client->user_id;
326
    }
327
328
    /**
329
     * Load all routes.
330
     *
331
     * @return void
332
     */
333
    public static function routes()
334
    {
335
        require __DIR__.'/../routes/oauth.php';
336
    }
337
338
    /**
339
     * Migrate tables.
340
     *
341
     * @param string $dir
342
     *
343
     * @return void
344
     */
345 View Code Duplication
    public static function migrate($dir = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
346
    {
347
        if (is_null($dir)) {
348
            $dir = __DIR__.'/../database/migrations';
349
        }
350
351
        foreach (glob($dir.'/*.php') as $file) {
352
            require_once $file;
353
            $table = pathinfo($file)['filename'];
354
            (new $table())->up();
355
        }
356
    }
357
358
    /**
359
     * Drop tables.
360
     *
361
     * @param string $dir
362
     *
363
     * @return void
364
     */
365 View Code Duplication
    public static function rollback($dir = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
366
    {
367
        if (is_null($dir)) {
368
            $dir = __DIR__.'/../database/migrations';
369
        }
370
371
        foreach (glob($dir.'/*.php') as $file) {
372
            require_once $file;
373
            $table = pathinfo($file)['filename'];
374
            (new $table())->down();
375
        }
376
    }
377
378
    /**
379
     * Drop and migrate fresh tables.
380
     *
381
     * @param string $dir
382
     *
383
     * @return void
384
     */
385
    public static function refresh($dir = null)
386
    {
387
        if (is_null($dir)) {
388
            $dir = __DIR__.'/../database/migrations';
389
        }
390
391
        static::rollback($dir);
392
        static::migrate($dir);
393
    }
394
}
395