-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathBootstrap.php
More file actions
executable file
·456 lines (420 loc) · 16.4 KB
/
Copy pathBootstrap.php
File metadata and controls
executable file
·456 lines (420 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<?php
/*
* This file is part of the 2amigos/yii2-usuario project.
*
* (c) 2amigOS! <http://2amigos.us/>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Da\User;
use Da\User\Component\AuthDbManagerComponent;
use Da\User\Contracts\AuthManagerInterface;
use Da\User\Controller\SecurityController;
use Da\User\Event\FormEvent;
use Da\User\Helper\ClassMapHelper;
use Da\User\Model\SessionHistory;
use Da\User\Model\User;
use Da\User\Search\SessionHistorySearch;
use Yii;
use yii\authclient\Collection;
use yii\base\Application;
use yii\base\BootstrapInterface;
use yii\base\Event as YiiEvent;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\console\Application as ConsoleApplication;
use yii\helpers\ArrayHelper;
use yii\i18n\PhpMessageSource;
use yii\web\Application as WebApplication;
/**
* Bootstrap class of the yii2-usuario extension. Configures container services, initializes translations,
* builds class map, and does the other setup actions participating in the application bootstrap process.
*/
class Bootstrap implements BootstrapInterface
{
/**
* {@inheritdoc}
*
* @throws InvalidConfigException
*/
public function bootstrap($app)
{
if ($app->hasModule('user') && $app->getModule('user') instanceof Module) {
$map = $this->buildClassMap($app->getModule('user')->classMap);
$this->initTranslations($app);
$this->initContainer($app, $map);
$this->initMailServiceConfiguration($app, $app->getModule('user'));
if ($app instanceof WebApplication) {
$this->initControllerNamespace($app);
$this->initUrlRoutes($app);
$this->initUrlRestRoutes($app);
$this->initAuthCollection($app);
$this->initAuthManager($app);
} else {
/* @var $app ConsoleApplication */
$this->initConsoleCommands($app);
$this->initAuthManager($app);
}
}
}
/**
* Initialize container with module classes.
*
* @param \yii\base\Application $app
* @param array $map the previously built class map list
*/
protected function initContainer($app, $map)
{
$di = Yii::$container;
try {
// events
$di->set(Event\FormEvent::class);
$di->set(Event\ProfileEvent::class);
$di->set(Event\ResetPasswordEvent::class);
$di->set(Event\SocialNetworkAuthEvent::class);
$di->set(Event\SocialNetworkConnectEvent::class);
$di->set(Event\UserEvent::class);
$di->set(Event\GdprEvent::class);
// forms
$di->set(Form\LoginForm::class);
$di->set(Form\RecoveryForm::class);
$di->set(Form\RegistrationForm::class);
$di->set(Form\ResendForm::class);
$di->set(Form\SettingsForm::class);
$di->set(Form\GdprDeleteForm::class);
// helpers
$di->set(Helper\AuthHelper::class);
$di->set(Helper\GravatarHelper::class);
$di->set(Helper\SecurityHelper::class);
$di->set(Helper\TimezoneHelper::class);
// services
$di->set(Service\AccountConfirmationService::class);
$di->set(Service\EmailChangeService::class);
$di->set(Service\PasswordExpireService::class);
$di->set(Service\PasswordRecoveryService::class);
$di->set(Service\ResendConfirmationService::class);
$di->set(Service\ResetPasswordService::class);
$di->set(Service\SocialNetworkAccountConnectService::class);
$di->set(Service\SocialNetworkAuthenticateService::class);
$di->set(Service\UserBlockService::class);
$di->set(Service\UserCreateService::class);
$di->set(Service\UserRegisterService::class);
$di->set(Service\UserConfirmationService::class);
$di->set(Service\AuthItemEditionService::class);
$di->set(Service\UpdateAuthAssignmentsService::class);
$di->set(Service\SwitchIdentityService::class);
$di->set(Service\TwoFactorQrCodeUriGeneratorService::class);
// email change strategy
$di->set(Strategy\DefaultEmailChangeStrategy::class);
$di->set(Strategy\InsecureEmailChangeStrategy::class);
$di->set(Strategy\SecureEmailChangeStrategy::class);
// validators
$di->set(Validator\AjaxRequestModelValidator::class);
$di->set(Validator\TimeZoneValidator::class);
$di->set(Validator\TwoFactorCodeValidator::class);
// class map models + query classes
$modelClassMap = [];
foreach ($map as $class => $definition) {
$di->set($class, $definition);
$model = is_array($definition) ? $definition['class'] : $definition;
$name = substr($class, strrpos($class, '\\') + 1);
$modelClassMap[$class] = $model;
if (in_array($name, ['User', 'Profile', 'Token', 'SocialNetworkAccount', 'SessionHistory'])) {
$di->set(
"Da\\User\\Query\\{$name}Query",
function () use ($model) {
return $model::find();
}
);
}
}
$di->setSingleton(ClassMapHelper::class, ClassMapHelper::class, [$modelClassMap]);
// search classes
if (!$di->has(Search\UserSearch::class)) {
$di->set(Search\UserSearch::class, [$di->get(Query\UserQuery::class)]);
}
if (!$di->has(Search\PermissionSearch::class)) {
$di->set(Search\PermissionSearch::class);
}
if (!$di->has(Search\RoleSearch::class)) {
$di->set(Search\RoleSearch::class);
}
if (Yii::$app->getModule('user')->searchUsersInLdap) {
if (!class_exists('kartik\typeahead\Typeahead')) {
throw new InvalidConfigException('The kartik-v/yii2-widget-typeahead library must be installed when searchUsersInLdap is true.');
}
}
// Attach an event to check if the password has expired
if (null !== Yii::$app->getModule('user')->maxPasswordAge) {
YiiEvent::on(SecurityController::class, FormEvent::EVENT_AFTER_LOGIN, function (FormEvent $event) {
$user = $event->form->user;
if ($user->password_age >= Yii::$app->getModule('user')->maxPasswordAge) {
// Force password change
Yii::$app->session->setFlash('warning', Yii::t('usuario', 'Your password has expired, you must change it now'));
Yii::$app->response->redirect(['/user/settings/account'])->send();
}
});
}
// Initialize array of two factor authentication validators available
$defaultTwoFactorAuthenticationValidators =
[
'google-authenticator' => [
'class' => \Da\User\Validator\TwoFactorCodeValidator::class,
'description' => Yii::t('usuario', 'Google Authenticator'),
'configurationUrl' => 'user/settings/two-factor',
'enabled' => true
],
'email' => [
'class' => \Da\User\Validator\TwoFactorEmailValidator::class,
'description' => Yii::t('usuario', 'Email'),
'configurationUrl' => 'user/settings/two-factor-email',
// Time duration of the code in seconds
'codeDurationTime' => 300,
'enabled' => true
],
'sms' => [
'class' => \Da\User\Validator\TwoFactorTextMessageValidator::class,
'description' => Yii::t('usuario', 'Text message'),
'configurationUrl' => 'user/settings/two-factor-sms',
// component for sending sms
'smsSender' => 'smsSender',
// Time duration of the code in seconds
'codeDurationTime' => 300,
'enabled' => true
]
];
$app->getModule('user')->twoFactorAuthenticationValidators = ArrayHelper::merge(
$defaultTwoFactorAuthenticationValidators,
$app->getModule('user')->twoFactorAuthenticationValidators
);
if ($app instanceof WebApplication) {
// override Yii
$di->set(
'yii\web\User',
[
'enableAutoLogin' => $app->getModule('user')->enableAutoLogin,
'loginUrl' => ['/user/security/login'],
'identityClass' => $di->get(ClassMapHelper::class)->get(User::class),
]
);
}
} catch (Exception $e) {
die($e);
}
}
/**
* Registers module translation messages.
*
* @param Application $app
*
* @throws InvalidConfigException
*/
protected function initTranslations(Application $app)
{
if (!isset($app->get('i18n')->translations['usuario*'])) {
$app->get('i18n')->translations['usuario*'] = [
'class' => PhpMessageSource::class,
'basePath' => __DIR__ . '/resources/i18n',
'sourceLanguage' => 'en-US',
];
}
}
/**
* Ensures the auth manager is the one provided by the library.
*
* @param Application $app
*
* @throws InvalidConfigException
*/
protected function initAuthManager(Application $app)
{
if (!($app->getAuthManager() instanceof AuthManagerInterface)) {
$app->set(
'authManager',
[
'class' => AuthDbManagerComponent::class,
]
);
}
}
/**
* Initializes web url routes (rules in Yii2).
*
* @param WebApplication $app
*
* @throws InvalidConfigException
*/
protected function initUrlRoutes(WebApplication $app)
{
/** @var $module Module */
$module = $app->getModule('user');
$config = [
'class' => 'yii\web\GroupUrlRule',
'prefix' => $module->prefix,
'rules' => $module->routes,
];
if ($module->prefix !== 'user') {
$config['routePrefix'] = 'user';
}
$rule = Yii::createObject($config);
$app->getUrlManager()->addRules([$rule], false);
}
/**
* Initializes web url for rest routes.
* @param WebApplication $app
* @throws InvalidConfigException
*/
protected function initUrlRestRoutes(WebApplication $app)
{
/** @var Module $module */
$module = $app->getModule('user');
$rules = $module->adminRestRoutes;
$config = [
'class' => 'yii\web\GroupUrlRule',
'prefix' => $module->adminRestPrefix,
'routePrefix' => $module->adminRestRoutePrefix,
'rules' => $rules,
];
$rule = Yii::createObject($config);
$app->getUrlManager()->addRules([$rule], false);
}
/**
* Ensures required mail parameters needed for the mail service.
*
* @param Application $app
* @param Module|\yii\base\Module $module
*/
protected function initMailServiceConfiguration(Application $app, Module $module)
{
$defaults = [
'fromEmail' => 'no-reply@example.com',
'welcomeMailSubject' => Yii::t('usuario', 'Welcome to {0}', $app->name),
'confirmationMailSubject' => Yii::t('usuario', 'Confirm account on {0}', $app->name),
'reconfirmationMailSubject' => Yii::t('usuario', 'Confirm email change on {0}', $app->name),
'recoveryMailSubject' => Yii::t('usuario', 'Complete password reset on {0}', $app->name),
'twoFactorMailSubject' => Yii::t('usuario', 'Code for two factor authentication on {0}', $app->name),
];
$module->mailParams = array_merge($defaults, $module->mailParams);
}
/**
* Ensures the authCollection component is configured.
*
* @param WebApplication $app
*
* @throws InvalidConfigException
*/
protected function initAuthCollection(WebApplication $app)
{
if (!$app->has('authClientCollection')) {
$app->set('authClientCollection', Collection::class);
}
}
/**
* Registers console commands to main app.
*
* @param ConsoleApplication $app
*/
protected function initConsoleCommands(ConsoleApplication $app)
{
$app->getModule('user')->controllerNamespace = $app->getModule('user')->consoleControllerNamespace;
}
/**
* Registers controllers.
*
* @param WebApplication $app
*/
protected function initControllerNamespace(WebApplication $app)
{
$app->getModule('user')->controllerNamespace = $app->getModule('user')->controllerNamespace;
$app->getModule('user')->setViewPath($app->getModule('user')->viewPath);
}
/**
* Builds class map according to user configuration.
*
* @param array $userClassMap user configuration on the module
*
* @throws Exception
* @return array
*/
protected function buildClassMap(array $userClassMap)
{
$map = [];
$defaults = [
// --- models
'User' => 'Da\User\Model\User',
'SocialNetworkAccount' => 'Da\User\Model\SocialNetworkAccount',
'Profile' => 'Da\User\Model\Profile',
'Token' => 'Da\User\Model\Token',
'Assignment' => 'Da\User\Model\Assignment',
'Permission' => 'Da\User\Model\Permission',
'Role' => 'Da\User\Model\Role',
'SessionHistory' => SessionHistory::class,
// --- search
'UserSearch' => 'Da\User\Search\UserSearch',
'PermissionSearch' => 'Da\User\Search\PermissionSearch',
'RoleSearch' => 'Da\User\Search\RoleSearch',
'SessionHistorySearch' => SessionHistorySearch::class,
// --- forms
'RegistrationForm' => 'Da\User\Form\RegistrationForm',
'ResendForm' => 'Da\User\Form\ResendForm',
'LoginForm' => 'Da\User\Form\LoginForm',
'SettingsForm' => 'Da\User\Form\SettingsForm',
'RecoveryForm' => 'Da\User\Form\RecoveryForm',
// --- services
'MailService' => 'Da\User\Service\MailService',
];
$routes = [
'Da\User\Model' => [
'User',
'SocialNetworkAccount',
'Profile',
'Token',
'Assignment',
'Permission',
'Role',
'SessionHistory'
],
'Da\User\Search' => [
'UserSearch',
'PermissionSearch',
'RoleSearch',
'SessionHistorySearch',
],
'Da\User\Form' => [
'RegistrationForm',
'ResendForm',
'LoginForm',
'SettingsForm',
'RecoveryForm',
],
'Da\User\Service' => [
'MailService',
],
];
$mapping = array_merge($defaults, $userClassMap);
foreach ($mapping as $name => $definition) {
$map[$this->getRoute($routes, $name) . "\\{$name}"] = $definition;
}
return $map;
}
/**
* Returns the parent class name route of a short class name.
*
* @param array $routes class name routes
* @param string $name
*
* @throws Exception
* @return int|string
*
*/
protected function getRoute(array $routes, $name)
{
foreach ($routes as $route => $names) {
if (in_array($name, $names, false)) {
return $route;
}
}
throw new Exception("Unknown configuration class name '{$name}'");
}
}