Module::setUpDi()   F
last analyzed

Complexity

Conditions 14
Paths 3072

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 50.5659

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 15
cts 35
cp 0.4286
rs 2.1
c 0
b 0
f 0
cc 14
nc 3072
nop 1
crap 50.5659

How to fix   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
 * Module.php
4
 *
5
 * PHP version 5.6+
6
 *
7
 * @author Philippe Gaultier <[email protected]>
8
 * @copyright 2010-2017 Philippe Gaultier
9
 * @license http://www.sweelix.net/license license
10
 * @version 1.2.0
11
 * @link http://www.sweelix.net
12
 * @package sweelix\oauth2\server
13
 */
14
15
namespace sweelix\oauth2\server;
16
17
use sweelix\oauth2\server\services\MySql;
18
use sweelix\oauth2\server\services\Oauth;
19
use sweelix\oauth2\server\services\Redis;
20
use yii\base\BootstrapInterface;
21
use yii\base\Module as BaseModule;
22
use yii\console\Application as ConsoleApplication;
23
use Yii;
24
use yii\helpers\ArrayHelper;
25
26
/**
27
 * Oauth2 server Module definition
28
 *
29
 * @author Philippe Gaultier <[email protected]>
30
 * @copyright 2010-2017 Philippe Gaultier
31
 * @license http://www.sweelix.net/license license
32
 * @version 1.2.0
33
 * @link http://www.sweelix.net
34
 * @package sweelix\oauth2\server
35
 * @since 1.0.0
36
 */
37
class Module extends BaseModule implements BootstrapInterface
38
{
39
    /**
40
     * @var string backend to use, available backends are 'redis' or 'mysql
41
     */
42
    public $backend;
43
44
    /**
45
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
46
     */
47
    public $db;
48
49
    /**
50
     * @var string override layout. For example @app/views/layouts/oauth2 to use <app>/views/layouts/oauth2.php layout
51
     */
52
    public $overrideLayout;
53
54
    /**
55
     * @var string override view path. For example @app/views/oauth2 to use <app>/views/oauth2/(authorize|login|error) views
56
     */
57
    public $overrideViewPath;
58
59
    /**
60
     * This user class will be used to link oauth2 authorization system with the application.
61
     * The class must implement \sweelix\oauth2\server\interfaces\UserInterface
62
     * If not defined, the Yii::$app->user->identityClass value will be used
63
     * @var string|array user class definition.
64
     */
65
    public $identityClass;
66
67
    /**
68
     * @var string used to separate user session between this module and current application
69
     */
70
    public $webUserParamId = '__oauth2';
71
72
    /**
73
     * @var string used to separate identity cookies between this module and current application
74
     */
75
    public $identityCookieName = 'oauth2';
76
77
    /**
78
     * @var array webUser configuration specific to this module
79
     */
80
    public $webUser = [];
81
82
    /**
83
     * @var string change base end point
84
     */
85
    public $baseEndPoint = '';
86
87
    /**
88
     * @var bool configure oauth server (use_jwt_access_tokens)
89
     */
90
    public $useJwtAccessToken = false; // WARNING: Not sure about the implementation. Use at your own risk !
91
92
    /**
93
     * @var array configure oauth server (allowed_algorithms)
94
     */
95
    public $allowAlgorithm = ['RS256', 'RS384', 'RS512'];
96
97
    /**
98
     * @var string|array jwt audience. Default to token endpoint
99
     */
100
    public $jwtAudience = ['token/index'];
101
102
    /**
103
     * @var bool configure oauth server (store_encrypted_token_string)
104
     */
105
    public $storeEncryptedTokenString = true;
106
107
    /**
108
     * @var bool configure oauth server (use_openid_connect)
109
     */
110
    public $allowOpenIdConnect = false;
111
112
    /**
113
     * @var int configure oauth server (id_lifetime)
114
     */
115
    public $idTTL = 3600;
116
117
    /**
118
     * @var int configure oauth server (access_lifetime)
119
     */
120
    public $accessTokenTTL = 3600;
121
122
    /**
123
     * @var int configure oauth server (refresh_token_lifetime)
124
     */
125
    public $refreshTokenTTL = 1209600;
126
127
    /**
128
     * @var string configure oauth server (www_realm)
129
     */
130
    public $realm = 'Service';
131
132
    /**
133
     * @var string configure oauth server (token_param_name)
134
     */
135
    public $tokenQueryName = 'access_token';
136
137
    /**
138
     * @var string configure oauth server (token_bearer_header_name)
139
     */
140
    public $tokenBearerName = 'Bearer';
141
142
    /**
143
     * @var bool configure oauth server (enforce_state)
144
     */
145
    public $enforceState = true;
146
147
    /**
148
     * @var bool configure oauth server (require_exact_redirect_uri)
149
     */
150
    public $allowOnlyRedirectUri = true;
151
152
    /**
153
     * @var bool configure oauth server (allow_implicit)
154
     */
155
    public $allowImplicit = false;
156
157
    /**
158
     * @var bool allow authorization code grant
159
     */
160
    public $allowAuthorizationCode = true;
161
162
    /**
163
     * @var bool allow client credentials grant
164
     */
165
    public $allowClientCredentials = true;
166
167
    /**
168
     * @var bool allow password grant
169
     */
170
    public $allowPassword = true;
171
172
    /**
173
     * @var bool configure oauth server (allow_credentials_in_request_body)
174
     */
175
    public $allowCredentialsInRequestBody = true;
176
177
    /**
178
     * @var bool configure oauth server (allow_public_clients)
179
     */
180
    public $allowPublicClients = true;
181
182
    /**
183
     * @var bool configure oauth server (always_issue_new_refresh_token)
184
     */
185
    public $alwaysIssueNewRefreshToken = true;
186
187
    /**
188
     * @var bool configure oauth server (unset_refresh_token_after_use)
189
     */
190
    public $unsetRefreshTokenAfterUse = false;
191
192
    /**
193
     * @var int duration of login time for multiple authorize calls
194
     */
195
    public $loginDuration = 60 * 60 * 24 * 30;
196
197
    /**
198
     * @var bool configure authorization code (enforce_redirect)
199
     */
200
    public $enforceRedirect = false;
201
202
    /**
203
     * @var int configure authorization code (auth_code_lifetime)
204
     */
205
    public $authorizationCodeTTL = 30;
206
207
    /**
208
     * @var false|array Cors configuration if allowed @see http://www.yiiframework.com/doc-2.0/yii-filters-cors.html
209
     */
210
    public $cors = false;
211
212
    /**
213
     * @inheritdoc
214 52
     */
215
    public function init()
216 52
    {
217 52
        parent::init();
218
    }
219
220
    /**
221
     * Load dataservices in container
222
     * @param \yii\base\Application $app
223
     * @since 1.0.0
224 52
     */
225
    protected function setUpDi($app)
226 52
    {
227
        if (Yii::$container->has('scope') === false) {
228
            Yii::$container->set('scope', 'sweelix\oauth2\server\validators\ScopeValidator');
229 52
        }
230
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\AccessTokenModelInterface') === false) {
231
            Yii::$container->set('sweelix\oauth2\server\interfaces\AccessTokenModelInterface', 'sweelix\oauth2\server\models\AccessToken');
232 52
        }
233
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\AuthCodeModelInterface') === false) {
234
            Yii::$container->set('sweelix\oauth2\server\interfaces\AuthCodeModelInterface', 'sweelix\oauth2\server\models\AuthCode');
235 52
        }
236
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\ClientModelInterface') === false) {
237
            Yii::$container->set('sweelix\oauth2\server\interfaces\ClientModelInterface', 'sweelix\oauth2\server\models\Client');
238 52
        }
239
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\CypherKeyModelInterface') === false) {
240
            Yii::$container->set('sweelix\oauth2\server\interfaces\CypherKeyModelInterface', 'sweelix\oauth2\server\models\CypherKey');
241 52
        }
242
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\JtiModelInterface') === false) {
243
            Yii::$container->set('sweelix\oauth2\server\interfaces\JtiModelInterface', 'sweelix\oauth2\server\models\Jti');
244 52
        }
245
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\JwtModelInterface') === false) {
246
            Yii::$container->set('sweelix\oauth2\server\interfaces\JwtModelInterface', 'sweelix\oauth2\server\models\Jwt');
247 52
        }
248
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\RefreshTokenModelInterface') === false) {
249
            Yii::$container->set('sweelix\oauth2\server\interfaces\RefreshTokenModelInterface', 'sweelix\oauth2\server\models\RefreshToken');
250 52
        }
251
        if (Yii::$container->has('sweelix\oauth2\server\interfaces\ScopeModelInterface') === false) {
252
            Yii::$container->set('sweelix\oauth2\server\interfaces\ScopeModelInterface', 'sweelix\oauth2\server\models\Scope');
253 52
        }
254
        if ((Yii::$container->has('sweelix\oauth2\server\interfaces\UserModelInterface') === false) && ($this->identityClass !== null)) {
255
            Yii::$container->set('sweelix\oauth2\server\interfaces\UserModelInterface', $this->identityClass);
256 52
        }
257 52
        if ($this->backend === 'redis') {
258 52
            Redis::register($app);
259 52
        } else if ($this->backend === 'mysql') {
260
            MySql::register($app);
261 52
        }
262
        Oauth::register($app);
263
    }
264
265
    /**
266 52
     * @inheritdoc
267
     */
268
    public function bootstrap($app)
269 52
    {
270 12
        // use the registered identity class if not overloaded
271 12
        if (($this->identityClass === null) && (isset($app->user) === true)) {
272 52
            $this->identityClass = $app->user->identityClass;
273 52
        }
274
        $this->setUpDi($app);
275
        if (empty($this->baseEndPoint) === false) {
276
            $this->baseEndPoint = trim($this->baseEndPoint, '/') . '/';
277 52
        }
278 40
279 40
        if ($app instanceof ConsoleApplication) {
280 12
            $this->mapConsoleControllers($app);
281 12
        } else {
282 12
            $app->getUrlManager()->addRules([
283 12
                ['verb' => 'POST', 'pattern' => $this->baseEndPoint . 'token', 'route' => $this->id . '/token/index'],
284 12
                ['verb' => 'OPTIONS', 'pattern' => $this->baseEndPoint . 'token', 'route' => $this->id . '/token/options'],
285 12
                ['verb' => 'GET', 'pattern' => $this->baseEndPoint . 'authorize', 'route' => $this->id . '/authorize/index'],
286 12
                ['pattern' => $this->baseEndPoint . 'authorize-login', 'route' => $this->id . '/authorize/login'],
287 12
                ['pattern' => $this->baseEndPoint . 'authorize-application', 'route' => $this->id . '/authorize/authorize'],
288
                ['pattern' => $this->baseEndPoint . 'authorize-error', 'route' => $this->id . '/authorize/error'],
289 52
            ]);
290
        }
291
    }
292
293
    /**
294 17
     * @inheritdoc
295
     */
296 17
    public function beforeAction($action)
297
    {
298 17
        $status = parent::beforeAction($action);
299
        // override web user to avoid conflicts only when routing into this module
300 17
        if ($status === true) {
301 17
            $userConfig = [
302 17
                'class' => 'yii\web\User',
303 17
                'identityClass' => $this->identityClass,
304 17
                'enableAutoLogin' => true,
305 17
                'enableSession' => true,
306 17
                'identityCookie' => ['name' => $this->identityCookieName, 'httpOnly' => true],
307 17
                'idParam' => $this->webUserParamId,
308
            ];
309 17
            $userConfig = ArrayHelper::merge($userConfig, $this->webUser);
310 17
311 17
            Yii::$app->set('user', $userConfig);
312
        }
313
        return $status;
314
    }
315
316
    /**
317
     * Update controllers map to add console commands
318
     * @param ConsoleApplication $app
319 40
     * @since 1.0.0
320
     */
321 40
    protected function mapConsoleControllers(ConsoleApplication $app)
322 40
    {
323
        $app->controllerMap['oauth2:client'] = [
324 40
            'class' => 'sweelix\oauth2\server\commands\ClientController',
325 40
        ];
326
        $app->controllerMap['oauth2:scope'] = [
327 40
            'class' => 'sweelix\oauth2\server\commands\ScopeController',
328 40
        ];
329
        $app->controllerMap['oauth2:key'] = [
330
            'class' => 'sweelix\oauth2\server\commands\KeyController',
331 40
        ];
332
        $app->controllerMap['oauth2:cronjob'] = [
333
            'class' => 'sweelix\oauth2\server\commands\CronJobController',
334
        ];
335
        $app->controllerMap['oauth2:jwt'] = [
336
            'class' => 'sweelix\oauth2\server\commands\JwtController',
337
        ];
338
        $app->controllerMap['oauth2:migrate-redis'] = [
339
            'class' => 'sweelix\oauth2\server\commands\MigrateRedisController',
340
        ];
341
    }
342
}
343