Completed
Pull Request — master (#361)
by
unknown
03:02
created

AdminController::actionSwitchIdentity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 6
cp 0
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Controller;
13
14
use Da\User\Event\UserEvent;
15
use Da\User\Factory\MailFactory;
16
use Da\User\Filter\AccessRuleFilter;
17
use Da\User\Model\Profile;
18
use Da\User\Model\User;
19
use Da\User\Query\UserQuery;
20
use Da\User\Search\SessionHistorySearch;
21
use Da\User\Search\UserSearch;
22
use Da\User\Service\PasswordExpireService;
23
use Da\User\Service\PasswordRecoveryService;
24
use Da\User\Service\SessionHistory\TerminateUserSessionsService;
25
use Da\User\Service\SwitchIdentityService;
26
use Da\User\Service\UserBlockService;
27
use Da\User\Service\UserConfirmationService;
28
use Da\User\Service\UserCreateService;
29
use Da\User\Traits\ContainerAwareTrait;
30
use Da\User\Traits\ModuleAwareTrait;
31
use Da\User\Validator\AjaxRequestModelValidator;
32
use Yii;
33
use yii\base\Module;
34
use yii\db\ActiveRecord;
35
use yii\filters\AccessControl;
36
use yii\filters\VerbFilter;
37
use yii\helpers\Url;
38
use yii\web\Controller;
39
40
class AdminController extends Controller
41
{
42
    use ContainerAwareTrait;
43
    use ModuleAwareTrait;
44
45
    /**
46
     * @var UserQuery
47
     */
48
    protected $userQuery;
49
50
    /**
51
     * AdminController constructor.
52
     *
53
     * @param string    $id
54
     * @param Module    $module
55
     * @param UserQuery $userQuery
56
     * @param array     $config
57
     */
58 2
    public function __construct($id, Module $module, UserQuery $userQuery, array $config = [])
59
    {
60 2
        $this->userQuery = $userQuery;
61 2
        parent::__construct($id, $module, $config);
62 2
    }
63
64
    /**
65
     * @param \yii\base\Action $action
66
     *
67
     * @return bool
68
     */
69 2
    public function beforeAction($action)
70
    {
71 2
        if (in_array($action->id, ['index', 'update', 'update-profile', 'info', 'assignments', 'session-history'], true)) {
72 2
            Url::remember('', 'actions-redirect');
73
        }
74
75 2
        return parent::beforeAction($action);
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 2
    public function behaviors()
82
    {
83
        return [
84 2
            'verbs' => [
85
                'class' => VerbFilter::class,
86
                'actions' => [
87
                    'delete' => ['post'],
88
                    'confirm' => ['post'],
89
                    'block' => ['post'],
90
                    'switch-identity' => ['post'],
91
                    'password-reset' => ['post'],
92
                    'force-password-change' => ['post'],
93
                    'terminate-sessions' => ['post'],
94
                ],
95
            ],
96
            'access' => [
97
                'class' => AccessControl::class,
98
                'ruleConfig' => [
99
                    'class' => AccessRuleFilter::class,
100
                ],
101
                'rules' => [
102
                    [
103
                        'allow' => true,
104
                        'actions' => ['switch-identity'],
105
                        'roles' => ['@'],
106
                    ],
107
                    [
108 2
                        'allow' => $this->getModule()->enableSessionHistory,
109
                        'actions' => ['session-history', 'terminate-sessions'],
110
                        'roles' => ['admin'],
111
                    ],
112
                    [
113
                        'allow' => true,
114
                        'roles' => ['admin'],
115
                    ],
116
                ],
117
            ],
118
        ];
119
    }
120
121
    public function actionIndex()
122
    {
123
        $searchModel = $this->make(UserSearch::class);
124
        $dataProvider = $searchModel->search(Yii::$app->request->get());
125
126
        return $this->render(
127
            'index',
128
            [
129
                'dataProvider' => $dataProvider,
130
                'searchModel' => $searchModel,
131
            ]
132
        );
133
    }
134
135 1
    public function actionCreate()
136
    {
137
        /** @var User $user */
138 1
        $user = $this->make(User::class, [], ['scenario' => 'create']);
139
140
        /** @var UserEvent $event */
141 1
        $event = $this->make(UserEvent::class, [$user]);
142
143 1
        $this->make(AjaxRequestModelValidator::class, [$user])->validate();
144
145 1
        if ($user->load(Yii::$app->request->post()) && $user->validate()) {
146 1
            $this->trigger(UserEvent::EVENT_BEFORE_CREATE, $event);
147
148 1
            $mailService = MailFactory::makeWelcomeMailerService($user);
149
150 1
            if ($this->make(UserCreateService::class, [$user, $mailService])->run()) {
151 1
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User has been created'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
152 1
                $this->trigger(UserEvent::EVENT_AFTER_CREATE, $event);
153 1
                return $this->redirect(['update', 'id' => $user->id]);
154
            }
155
            Yii::$app->session->setFlash('danger', Yii::t('usuario', 'User account could not be created.'));
156
        }
157
158 1
        return $this->render('create', ['user' => $user]);
159
    }
160
161 2
    public function actionUpdate($id)
162
    {
163 2
        $user = $this->userQuery->where(['id' => $id])->one();
164 2
        $user->setScenario('update');
165
        /** @var UserEvent $event */
166 2
        $event = $this->make(UserEvent::class, [$user]);
167
168 2
        $this->make(AjaxRequestModelValidator::class, [$user])->validate();
169
170 2
        if ($user->load(Yii::$app->request->post())) {
171 1
            $this->trigger(UserEvent::EVENT_BEFORE_ACCOUNT_UPDATE, $event);
172
173 1
            if ($user->save()) {
174 1
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Account details have been updated'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
175 1
                $this->trigger(UserEvent::EVENT_AFTER_ACCOUNT_UPDATE, $event);
176
177 1
                return $this->refresh();
178
            }
179
        }
180
181 2
        return $this->render('_account', ['user' => $user]);
182
    }
183
184
    public function actionUpdateProfile($id)
185
    {
186
        /** @var User $user */
187
        $user = $this->userQuery->where(['id' => $id])->one();
188
        /** @var Profile $profile */
189
        $profile = $user->profile;
190
        if ($profile === null) {
191
            $profile = $this->make(Profile::class);
192
            $profile->link('user', $user);
193
        }
194
        /** @var UserEvent $event */
195
        $event = $this->make(UserEvent::class, [$user]);
196
197
        $this->make(AjaxRequestModelValidator::class, [$profile])->validate();
198
199
        if ($profile->load(Yii::$app->request->post())) {
200
            if ($profile->save()) {
201
                $this->trigger(UserEvent::EVENT_BEFORE_PROFILE_UPDATE, $event);
202
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Profile details have been updated'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
203
                $this->trigger(UserEvent::EVENT_AFTER_PROFILE_UPDATE, $event);
204
205
                return $this->refresh();
206
            }
207
        }
208
209
        return $this->render(
210
            '_profile',
211
            [
212
                'user' => $user,
213
                'profile' => $profile,
214
            ]
215
        );
216
    }
217
218
    public function actionInfo($id)
219
    {
220
        /** @var User $user */
221
        $user = $this->userQuery->where(['id' => $id])->one();
222
223
        return $this->render(
224
            '_info',
225
            [
226
                'user' => $user,
227
            ]
228
        );
229
    }
230
231
    public function actionAssignments($id)
232
    {
233
        /** @var User $user */
234
        $user = $this->userQuery->where(['id' => $id])->one();
235
236
        return $this->render(
237
            '_assignments',
238
            [
239
                'user' => $user,
240
                'params' => Yii::$app->request->post(),
241
            ]
242
        );
243
    }
244
245
    public function actionConfirm($id)
246
    {
247
        /** @var User $user */
248
        $user = $this->userQuery->where(['id' => $id])->one();
249
        /** @var UserEvent $event */
250
        $event = $this->make(UserEvent::class, [$user]);
251
252
        $this->trigger(UserEvent::EVENT_BEFORE_CONFIRMATION, $event);
253
254
        if ($this->make(UserConfirmationService::class, [$user])->run()) {
255
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User has been confirmed'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
256
            $this->trigger(UserEvent::EVENT_AFTER_CONFIRMATION, $event);
257
        } else {
258
            Yii::$app->getSession()->setFlash(
259
                'warning',
260
                Yii::t('usuario', 'Unable to confirm user. Please, try again.')
261
            );
262
        }
263
264
        return $this->redirect(Url::previous('actions-redirect'));
265
    }
266
267
    public function actionDelete($id)
268
    {
269
        if ((int)$id === Yii::$app->user->getId()) {
270
            Yii::$app->getSession()->setFlash('danger', Yii::t('usuario', 'You cannot remove your own account'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
271
        } else {
272
            /** @var User $user */
273
            $user = $this->userQuery->where(['id' => $id])->one();
274
            /** @var UserEvent $event */
275
            $event = $this->make(UserEvent::class, [$user]);
276
            $this->trigger(ActiveRecord::EVENT_BEFORE_DELETE, $event);
277
278
            if ($user->delete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user->delete() of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
279
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User has been deleted'));
280
                $this->trigger(ActiveRecord::EVENT_AFTER_DELETE, $event);
281
            } else {
282
                Yii::$app->getSession()->setFlash(
283
                    'warning',
284
                    Yii::t('usuario', 'Unable to delete user. Please, try again later.')
285
                );
286
            }
287
        }
288
289
        return $this->redirect(['index']);
290
    }
291
292
    public function actionBlock($id)
293
    {
294
        if ((int)$id === Yii::$app->user->getId()) {
295
            Yii::$app->getSession()->setFlash('danger', Yii::t('usuario', 'You cannot remove your own account'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
296
        } else {
297
            /** @var User $user */
298
            $user = $this->userQuery->where(['id' => $id])->one();
299
            /** @var UserEvent $event */
300
            $event = $this->make(UserEvent::class, [$user]);
301
302
            if ($this->make(UserBlockService::class, [$user, $event, $this])->run()) {
303
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User block status has been updated.'));
304
            } else {
305
                Yii::$app->getSession()->setFlash('danger', Yii::t('usuario', 'Unable to update block status.'));
306
            }
307
        }
308
309
        return $this->redirect(Url::previous('actions-redirect'));
310
    }
311
312
    public function actionSwitchIdentity($id = null)
313
    {
314
        if (false === $this->module->enableSwitchIdentities) {
315
            Yii::$app->getSession()->setFlash('danger', Yii::t('usuario', 'Switch identities is disabled.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
316
317
            return $this->redirect(['index']);
318
        }
319
320
        $this->make(SwitchIdentityService::class, [$this, 2 => $id])->run();
321
322
        return $this->goHome();
323
    }
324
325
    public function actionPasswordReset($id)
326
    {
327
        /** @var User $user */
328
        $user = $this->userQuery->where(['id' => $id])->one();
329
        $mailService = MailFactory::makeRecoveryMailerService($user->email);
330
        if ($this->make(PasswordRecoveryService::class, [$user->email, $mailService])->run()) {
331
            Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Recovery message sent'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
332
        } else {
333
            Yii::$app->getSession()->setFlash(
334
                'danger',
335
                Yii::t('usuario', 'Unable to send recovery message to the user')
336
            );
337
        }
338
339
        return $this->redirect(['index']);
340
    }
341
    
342
    /**
343
     * Forces the user to change password at next login
344
     * @param integer $id
345
     */
346
    public function actionForcePasswordChange($id)
347
    {
348
        /** @var User $user */
349
        $user = $this->userQuery->where(['id' => $id])->one();
350
        if ($this->make(PasswordExpireService::class, [$user])->run()) {
351
            Yii::$app->session->setFlash("success", Yii::t('usuario', 'User will be required to change password at next login'));
352
        } else {
353
            Yii::$app->session->setFlash("danger", Yii::t('usuario', 'There was an error in saving user'));
354
        }
355
        $this->redirect(['index']);
356
    }
357
358
    /**
359
     * Display list session history
360
     */
361
    public function actionSessionHistory($id)
362
    {
363
        $searchModel = new SessionHistorySearch([
364
            'user_id' => $id,
365
        ]);
366
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
367
368
        $user = $this->userQuery->where(['id' => $id])->one();
369
370
        return $this->render('_session-history', [
371
            'searchModel' => $searchModel,
372
            'dataProvider' => $dataProvider,
373
            'user' => $user,
374
        ]);
375
    }
376
377
    /**
378
     * Terminate all session user
379
     */
380
    public function actionTerminateSessions($id)
381
    {
382
        $this->make(TerminateUserSessionsService::class, [$id])->run();
383
384
        return $this->redirect(Url::previous('actions-redirect'));
385
    }
386
}
387