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

AdminController::actionForcePasswordChange()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.9
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
                        'allow' => true,
109
                        'roles' => ['admin'],
110
                    ],
111
                ],
112
            ],
113
        ];
114
    }
115
116
    public function actionIndex()
117
    {
118
        $searchModel = $this->make(UserSearch::class);
119
        $dataProvider = $searchModel->search(Yii::$app->request->get());
120
121
        return $this->render(
122
            'index',
123
            [
124
                'dataProvider' => $dataProvider,
125
                'searchModel' => $searchModel,
126
            ]
127
        );
128
    }
129
130 1
    public function actionCreate()
131
    {
132
        /** @var User $user */
133 1
        $user = $this->make(User::class, [], ['scenario' => 'create']);
134
135
        /** @var UserEvent $event */
136 1
        $event = $this->make(UserEvent::class, [$user]);
137
138 1
        $this->make(AjaxRequestModelValidator::class, [$user])->validate();
139
140 1
        if ($user->load(Yii::$app->request->post()) && $user->validate()) {
141 1
            $this->trigger(UserEvent::EVENT_BEFORE_CREATE, $event);
142
143 1
            $mailService = MailFactory::makeWelcomeMailerService($user);
144
145 1
            if ($this->make(UserCreateService::class, [$user, $mailService])->run()) {
146 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...
147 1
                $this->trigger(UserEvent::EVENT_AFTER_CREATE, $event);
148 1
                return $this->redirect(['update', 'id' => $user->id]);
149
            }
150
            Yii::$app->session->setFlash('danger', Yii::t('usuario', 'User account could not be created.'));
151
        }
152
153 1
        return $this->render('create', ['user' => $user]);
154
    }
155
156 2
    public function actionUpdate($id)
157
    {
158 2
        $user = $this->userQuery->where(['id' => $id])->one();
159 2
        $user->setScenario('update');
160
        /** @var UserEvent $event */
161 2
        $event = $this->make(UserEvent::class, [$user]);
162
163 2
        $this->make(AjaxRequestModelValidator::class, [$user])->validate();
164
165 2
        if ($user->load(Yii::$app->request->post())) {
166 1
            $this->trigger(UserEvent::EVENT_BEFORE_ACCOUNT_UPDATE, $event);
167
168 1
            if ($user->save()) {
169 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...
170 1
                $this->trigger(UserEvent::EVENT_AFTER_ACCOUNT_UPDATE, $event);
171
172 1
                return $this->refresh();
173
            }
174
        }
175
176 2
        return $this->render('_account', ['user' => $user]);
177
    }
178
179
    public function actionUpdateProfile($id)
180
    {
181
        /** @var User $user */
182
        $user = $this->userQuery->where(['id' => $id])->one();
183
        /** @var Profile $profile */
184
        $profile = $user->profile;
185
        if ($profile === null) {
186
            $profile = $this->make(Profile::class);
187
            $profile->link('user', $user);
188
        }
189
        /** @var UserEvent $event */
190
        $event = $this->make(UserEvent::class, [$user]);
191
192
        $this->make(AjaxRequestModelValidator::class, [$profile])->validate();
193
194
        if ($profile->load(Yii::$app->request->post())) {
195
            if ($profile->save()) {
196
                $this->trigger(UserEvent::EVENT_BEFORE_PROFILE_UPDATE, $event);
197
                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...
198
                $this->trigger(UserEvent::EVENT_AFTER_PROFILE_UPDATE, $event);
199
200
                return $this->refresh();
201
            }
202
        }
203
204
        return $this->render(
205
            '_profile',
206
            [
207
                'user' => $user,
208
                'profile' => $profile,
209
            ]
210
        );
211
    }
212
213
    public function actionInfo($id)
214
    {
215
        /** @var User $user */
216
        $user = $this->userQuery->where(['id' => $id])->one();
217
218
        return $this->render(
219
            '_info',
220
            [
221
                'user' => $user,
222
            ]
223
        );
224
    }
225
226
    public function actionAssignments($id)
227
    {
228
        /** @var User $user */
229
        $user = $this->userQuery->where(['id' => $id])->one();
230
231
        return $this->render(
232
            '_assignments',
233
            [
234
                'user' => $user,
235
                'params' => Yii::$app->request->post(),
236
            ]
237
        );
238
    }
239
240
    public function actionConfirm($id)
241
    {
242
        /** @var User $user */
243
        $user = $this->userQuery->where(['id' => $id])->one();
244
        /** @var UserEvent $event */
245
        $event = $this->make(UserEvent::class, [$user]);
246
247
        $this->trigger(UserEvent::EVENT_BEFORE_CONFIRMATION, $event);
248
249
        if ($this->make(UserConfirmationService::class, [$user])->run()) {
250
            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...
251
            $this->trigger(UserEvent::EVENT_AFTER_CONFIRMATION, $event);
252
        } else {
253
            Yii::$app->getSession()->setFlash(
254
                'warning',
255
                Yii::t('usuario', 'Unable to confirm user. Please, try again.')
256
            );
257
        }
258
259
        return $this->redirect(Url::previous('actions-redirect'));
260
    }
261
262
    public function actionDelete($id)
263
    {
264
        if ((int)$id === Yii::$app->user->getId()) {
265
            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...
266
        } else {
267
            /** @var User $user */
268
            $user = $this->userQuery->where(['id' => $id])->one();
269
            /** @var UserEvent $event */
270
            $event = $this->make(UserEvent::class, [$user]);
271
            $this->trigger(ActiveRecord::EVENT_BEFORE_DELETE, $event);
272
273
            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...
274
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User has been deleted'));
275
                $this->trigger(ActiveRecord::EVENT_AFTER_DELETE, $event);
276
            } else {
277
                Yii::$app->getSession()->setFlash(
278
                    'warning',
279
                    Yii::t('usuario', 'Unable to delete user. Please, try again later.')
280
                );
281
            }
282
        }
283
284
        return $this->redirect(['index']);
285
    }
286
287
    public function actionBlock($id)
288
    {
289
        if ((int)$id === Yii::$app->user->getId()) {
290
            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...
291
        } else {
292
            /** @var User $user */
293
            $user = $this->userQuery->where(['id' => $id])->one();
294
            /** @var UserEvent $event */
295
            $event = $this->make(UserEvent::class, [$user]);
296
297
            if ($this->make(UserBlockService::class, [$user, $event, $this])->run()) {
298
                Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'User block status has been updated.'));
299
            } else {
300
                Yii::$app->getSession()->setFlash('danger', Yii::t('usuario', 'Unable to update block status.'));
301
            }
302
        }
303
304
        return $this->redirect(Url::previous('actions-redirect'));
305
    }
306
307
    public function actionSwitchIdentity($id = null)
308
    {
309
        if (false === $this->module->enableSwitchIdentities) {
310
            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...
311
312
            return $this->redirect(['index']);
313
        }
314
315
        $this->make(SwitchIdentityService::class, [$this, 2 => $id])->run();
316
317
        return $this->goHome();
318
    }
319
320
    public function actionPasswordReset($id)
321
    {
322
        /** @var User $user */
323
        $user = $this->userQuery->where(['id' => $id])->one();
324
        $mailService = MailFactory::makeRecoveryMailerService($user->email);
325
        if ($this->make(PasswordRecoveryService::class, [$user->email, $mailService])->run()) {
326
            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...
327
        } else {
328
            Yii::$app->getSession()->setFlash(
329
                'danger',
330
                Yii::t('usuario', 'Unable to send recovery message to the user')
331
            );
332
        }
333
334
        return $this->redirect(['index']);
335
    }
336
    
337
    /**
338
     * Forces the user to change password at next login
339
     * @param integer $id
340
     */
341
    public function actionForcePasswordChange($id)
342
    {
343
        /** @var User $user */
344
        $user = $this->userQuery->where(['id' => $id])->one();
345
        if ($this->make(PasswordExpireService::class, [$user])->run()) {
346
            Yii::$app->session->setFlash("success", Yii::t('usuario', 'User will be required to change password at next login'));
347
        } else {
348
            Yii::$app->session->setFlash("danger", Yii::t('usuario', 'There was an error in saving user'));
349
        }
350
        $this->redirect(['index']);
351
    }
352
353
    /**
354
     * Display list session history
355
     */
356
    public function actionSessionHistory($id)
357
    {
358
        $searchModel = new SessionHistorySearch([
359
            'user_id' => $id,
360
        ]);
361
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
362
363
        $user = $this->userQuery->where(['id' => $id])->one();
364
365
        return $this->render('_session-history', [
366
            'searchModel' => $searchModel,
367
            'dataProvider' => $dataProvider,
368
            'user' => $user,
369
        ]);
370
    }
371
372
    /**
373
     * Terminate all session user
374
     */
375
    public function actionTerminateSessions($id)
376
    {
377
        $this->make(TerminateUserSessionsService::class, [$id])->run();
378
379
        return $this->redirect(Url::previous('actions-redirect'));
380
    }
381
}
382