AccountController::actionView()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace inblank\activeuser\controllers;
4
5
use inblank\activeuser\models\forms\ChangePasswordForm;
6
use inblank\activeuser\models\forms\LoginForm;
7
use inblank\activeuser\models\forms\RegisterForm;
8
use inblank\activeuser\models\forms\ResendForm;
9
use inblank\activeuser\models\forms\RestoreForm;
10
use inblank\activeuser\traits\CommonTrait;
11
use yii;
12
use yii\filters\AccessControl;
13
use yii\web\Controller;
14
15
class AccountController extends Controller
16
{
17
18
    use CommonTrait;
19
20
    /**
21
     * @inheritdoc
22
     */
23
    public function behaviors()
24
    {
25
        $authorizedUserAction = ['index', 'update', 'change-password', 'logout'];
26
        return [
27
            'access' => [
28
                'class' => AccessControl::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
29
                'except' => ['confirm', 'view'],
30
                'rules' => [
31
                    [
32
                        'allow' => true,
33
                        'actions' => ['register', 'login', 'resend', 'restore'],
34
                        'roles' => ['?'],
35
                    ],
36
                    [
37
                        'allow' => true,
38
                        'actions' => $authorizedUserAction,
39
                        'roles' => ['@'],
40
                    ],
41
                ],
42
                'denyCallback' => function ($rule, $action) use ($authorizedUserAction) {
43
                    return in_array($action->id, $authorizedUserAction) ?
44
                        $action->controller->redirect(['login']) :
45
                        $action->controller->redirect(['index']);
46
                },
47
            ],
48
        ];
49
    }
50
51
    /**
52
     * General user cabinet page
53
     */
54
    public function actionIndex()
55
    {
56
        $user = $this->findModel(Yii::$app->user->id);
57
        return $this->render('index', [
58
            'user' => $user
59
        ]);
60
    }
61
62
    /**
63
     * User registering action
64
     */
65
    public function actionRegister()
66
    {
67
        if (!$this->module->isRegistrationEnabled()) {
68
            return $this->render('registerDisable');
69
        }
70
        $flashMessageId = 'activeuser_register';
71
72
        $email = Yii::$app->session->getFlash($flashMessageId);
73 View Code Duplication
        if (!empty($email)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
74
            return $this->render('registerAfter', [
75
                'user' => Yii::createObject(self::di('User'))->findOne(['email' => $email]),
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
76
            ]);
77
        }
78
        /** @var RegisterForm $model */
79
        $model = Yii::createObject(RegisterForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
80 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->register()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
81
            // congratulation and instruction
82
            Yii::$app->session->setFlash($flashMessageId, $model->email);
83
            return $this->redirect(['/activeuser/account/register']);
84
        }
85
        return $this->render('register', [
86
            'model' => $model,
87
        ]);
88
    }
89
90
    /**
91
     * User login action
92
     */
93
    public function actionLogin()
94
    {
95
        // TODO filter too many login request
96
        /** @var LoginForm $model */
97
        $model = Yii::createObject(LoginForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
98
        if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
99
            return $this->goBack();
100
        }
101
        return $this->render('login', [
102
            'model' => $model,
103
        ]);
104
    }
105
106
    /**
107
     * User logout action
108
     */
109
    public function actionLogout()
110
    {
111
        Yii::$app->user->logout();
112
        return $this->redirect('/');
113
    }
114
115
    /**
116
     * Request password change
117
     * @return string|yii\web\Response
118
     * @throws yii\base\InvalidConfigException
119
     * @throws yii\web\NotFoundHttpException
120
     */
121
    public function actionRestore()
122
    {
123
        // TODO filter too many restore request and set in Module period for restore
124
        if (!$this->getModule()->enablePasswordRestore) {
125
            throw new yii\web\NotFoundHttpException();
126
        }
127
        $flashMessageId = 'activeuser_restore_sent';
128
        $email = Yii::$app->session->getFlash($flashMessageId);
129
        if ($email !== null) {
130
            // message with instructions sent
131
            return $this->render('restoreSent', [
132
                'email' => $email,
133
            ]);
134
        }
135
136
        /** @var RestoreForm $model */
137
        $model = Yii::createObject(RestoreForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
138
        $model->setScenario($model::SCENARIO_EMAIL);
139 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->restore()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
140
            Yii::$app->session->setFlash($flashMessageId, $model->email);
141
            return $this->redirect(['/activeuser/account/restore']);
142
        }
143
        $error = Yii::$app->session->getFlash('activeuser_error');
144
        if (!empty($error) && !empty($error['token'])) {
145
            $error = $error['token'][0];
146
        } else {
147
            $error = null;
148
        }
149
        return $this->render('restore', [
150
            'model' => $model,
151
            'error' => $error,
152
        ]);
153
    }
154
155
    /**
156
     * Change user password
157
     * @param string $token user token for restore
158
     * @return string|yii\web\Response
159
     * @throws yii\base\InvalidConfigException
160
     * @throws yii\web\NotFoundHttpException
161
     */
162
    public function actionPassword($token = null)
163
    {
164
        $flashMessageId = 'activeuser_restore';
165
166
        $email = Yii::$app->session->getFlash($flashMessageId);
167 View Code Duplication
        if (!empty($email)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
168
            // congratulation message
169
            return $this->render('restoreComplete', [
170
                'user' => Yii::createObject(self::di('User'))->findOne(['email' => $email]),
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
171
            ]);
172
        }
173
174
        /** @var \inblank\activeuser\models\User $user */
175
        if (!$this->getModule()->enablePasswordRestore || $token === null || !($user = Yii::createObject(self::di('User'))->findByToken($token))) {
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
176
            throw new yii\web\NotFoundHttpException();
177
        }
178
179
        if ($user->isRestoreTokenExpired()) {
180
            Yii::$app->session->setFlash('activeuser_error', ['token' => Yii::t('activeuser_general', 'You token was expired')]);
181
            return $this->redirect(['/activeuser/account/restore']);
182
        }
183
184
        /** @var RestoreForm $model */
185
        $model = Yii::createObject(RestoreForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
186
        $model->setScenario($model::SCENARIO_PASSWORD);
187
        if ($this->getModule()->generatePassOnRestore) {
188
            // password auto generation
189
            $changed = $user->changePassword();
190
        } else {
191
            // change to user entered
192
            $model->email = $user->email;
193
            $changed = $model->load(Yii::$app->getRequest()->post()) && $model->changePassword();
194
        }
195
        if ($changed) {
196
            Yii::$app->session->setFlash($flashMessageId, $user->email);
197
            return $this->redirect(['/activeuser/account/password']);
198
        }
199
        return $this->render('restorePass', [
200
            'model' => $model
201
        ]);
202
    }
203
204
    /**
205
     * User resend confirmation message
206
     */
207
    public function actionResend()
208
    {
209
        // TODO filter too many resend request and set in Module period for resend
210
        if (!$this->getModule()->enableConfirmation) {
211
            throw new yii\web\NotFoundHttpException();
212
        }
213
214
        $email = Yii::$app->session->getFlash('resend');
215
        if ($email !== null) {
216
            // already sent
217
            return $this->render('resendComplete', [
218
                'email' => $email,
219
            ]);
220
        }
221
222
        // new resend
223
        /** @var ResendForm $model */
224
        $model = Yii::createObject(ResendForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
225 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->resend()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
226
            // resend complete, even if the user is not found
227
            Yii::$app->session->setFlash('resend', $model->email);
228
            return $this->redirect(['/activeuser/account/resend']);
229
        }
230
        return $this->render('resend', [
231
            'model' => $model,
232
        ]);
233
    }
234
235
    /**
236
     * Confirm email page
237
     * @param string $token user token for confirm email
238
     * @return string
239
     * @throws yii\base\InvalidConfigException
240
     */
241
    public function actionConfirm($token = '')
242
    {
243
        /** @var \inblank\activeuser\models\User $user */
244
        $user = Yii::createObject(self::di('User'))->findByToken($token);
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
245
        if ($user !== null && $user->confirm()) {
246
            return $this->render('confirm', ['user' => $user]);
247
        }
248
        return $this->render('confirmWrong');
249
    }
250
251
    /**
252
     * View user data
253
     * @param int $id user identifier. If null, viewing data of the current logged user
254
     * If null and user is guest will trow yii\web\HttpException exception with 404 status code
255
     * @return string
256
     * @throws yii\web\HttpException
257
     */
258
    public function actionView($id = null)
259
    {
260
        $id || $id = Yii::$app->user->id;
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null 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...
261
        $user = $this->findModel($id);
262
        return $this->render('view', [
263
            'user' => $user
264
        ]);
265
    }
266
267
    /**
268
     * Update data of the current logged user
269
     */
270
    public function actionUpdate()
271
    {
272
        $user = $this->findModel(Yii::$app->user->id);
273 View Code Duplication
        if ($user->load(Yii::$app->request->post()) && $user->save()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
274
            return $this->redirect(['index']);
275
        }
276
        return $this->render('update', [
277
            'user' => $user
278
        ]);
279
    }
280
281
    /**
282
     * Update password of the current logged user
283
     */
284
    public function actionChangePassword()
285
    {
286
        $user = $this->findModel(Yii::$app->user->id);
287
        /** @var ChangePasswordForm $form */
288
        $form = Yii::createObject(ChangePasswordForm::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
289 View Code Duplication
        if ($form->load(Yii::$app->request->post()) && $form->changePassword()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
290
            return $this->redirect(['index']);
291
        }
292
        $form->reset();
293
        return $this->render('changePassword', [
294
            'user' => $user,
295
            'model' => $form,
296
        ]);
297
    }
298
299
    /**
300
     * Find user model
301
     * @param mixed $value value for search
302
     * @param string $field field where search. Default `id`
303
     * @return mixed
304
     * @throws yii\web\HttpException
305
     */
306
    public function findModel($value, $field = 'id')
307
    {
308
        $user = Yii::createObject(self::di('User'))->findOne([$field => $value]);
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
309
        if (!$user) {
310
            throw new yii\web\HttpException(404, Yii::t('activeuser_frontend', 'User not found'));
311
        }
312
        return $user;
313
    }
314
}
315