DefaultController   A
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 355
Duplicated Lines 0 %

Importance

Changes 9
Bugs 3 Features 0
Metric Value
wmc 39
eloc 132
c 9
b 3
f 0
dl 0
loc 355
rs 9.28

18 Methods

Rating   Name   Duplication   Size   Complexity  
A getVerb() 0 7 1
A getAccess() 0 18 1
A actionLogin() 0 14 4
A behaviors() 0 5 1
A processSendEmail() 0 7 1
A actionGenerateAuthKey() 0 10 2
A actionSetStatus() 0 11 2
A processGenerateAuthKey() 0 6 1
A processChangeStatus() 0 10 3
A processCheckPermissionLogin() 0 20 2
A actionSendConfirmEmail() 0 12 3
A findModel() 0 6 2
A actionDelete() 0 34 3
A actionLogout() 0 5 1
A actionView() 0 12 2
A actionIndex() 0 9 1
A actionUpdate() 0 13 6
A actionCreate() 0 13 3
1
<?php
2
3
namespace modules\users\controllers\backend;
4
5
use Yii;
6
use yii\base\Exception;
7
use yii\base\InvalidConfigException;
8
use yii\db\StaleObjectException;
9
use yii\web\Response;
10
use yii\web\Controller;
11
use yii\filters\VerbFilter;
12
use yii\filters\AccessControl;
13
use yii\web\NotFoundHttpException;
14
use modules\users\models\LoginForm;
15
use modules\rbac\models\Permission;
16
use modules\rbac\models\Assignment;
17
use modules\users\models\User;
18
use modules\users\models\search\UserSearch;
19
use modules\users\Module;
20
use yii2tech\ar\softdelete\SoftDeleteBehavior;
21
22
/**
23
 * Class DefaultController
24
 * @package modules\users\controllers\backend
25
 *
26
 * @property array $access
27
 * @property  array $verb
28
 */
29
class DefaultController extends Controller
30
{
31
    /**
32
     * @inheritdoc
33
     * @return array
34
     */
35
    public function behaviors()
36
    {
37
        return [
38
            'verbs' => $this->getVerb(),
39
            'access' => $this->getAccess()
40
        ];
41
    }
42
43
    /**
44
     * @return array
45
     */
46
    private function getVerb()
47
    {
48
        return [
49
            'class' => VerbFilter::class,
50
            'actions' => [
51
                'delete' => ['POST'],
52
                'logout' => ['POST']
53
            ]
54
        ];
55
    }
56
57
    /**
58
     * @return array
59
     */
60
    private function getAccess()
61
    {
62
        return [
63
            'class' => AccessControl::class,
64
            'rules' => [
65
                [
66
                    'actions' => ['login'],
67
                    'allow' => true,
68
                    'roles' => ['?']
69
                ],
70
                [
71
                    'actions' => ['logout'],
72
                    'allow' => true,
73
                    'roles' => ['@']
74
                ],
75
                [
76
                    'allow' => true,
77
                    'roles' => [Permission::PERMISSION_MANAGER_USERS]
78
                ]
79
            ]
80
        ];
81
    }
82
83
    /**
84
     * Login action.
85
     *
86
     * @return string|Response
87
     */
88
    public function actionLogin()
89
    {
90
        if (!Yii::$app->user->isGuest) {
91
            return $this->goHome();
92
        }
93
94
        $this->layout = '//login';
95
96
        $model = new LoginForm();
97
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
98
            return $this->processCheckPermissionLogin();
99
        }
100
        return $this->render('login', [
101
            'model' => $model
102
        ]);
103
    }
104
105
    /**
106
     * @return Response
107
     */
108
    protected function processCheckPermissionLogin()
109
    {
110
        // If access to Backend is denied, reset authorization, write a message to the session
111
        // and move it to the login page
112
        /** @var yii\web\User $user */
113
        $user = Yii::$app->user;
114
        if (!$user->can(Permission::PERMISSION_VIEW_ADMIN_PAGE)) {
115
            $user->logout();
116
            /** @var yii\web\Session $session */
117
            $session = Yii::$app->session;
118
            $session->setFlash(
119
                'error',
120
                Module::translate(
121
                    'module',
122
                    'You do not have rights, access is denied.'
123
                )
124
            );
125
            return $this->goHome();
126
        }
127
        return $this->goBack();
128
    }
129
130
    /**
131
     * Logout action.
132
     *
133
     * @return Response
134
     */
135
    public function actionLogout()
136
    {
137
        $model = new LoginForm();
138
        $model->logout();
139
        return $this->goHome();
140
    }
141
142
    /**
143
     * @return string
144
     * @throws InvalidConfigException
145
     */
146
    public function actionIndex()
147
    {
148
        $searchModel = new UserSearch();
149
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
150
        $assignModel = new Assignment();
151
        return $this->render('index', [
152
            'searchModel' => $searchModel,
153
            'dataProvider' => $dataProvider,
154
            'assignModel' => $assignModel
155
        ]);
156
    }
157
158
    /**
159
     * Displays a single User model.
160
     * @param int|string $id
161
     * @return string|Response
162
     * @throws NotFoundHttpException
163
     */
164
    public function actionView($id)
165
    {
166
        if ($model = $this->findModel($id)) {
167
            $assignModel = new Assignment([
168
                'user' => $model
169
            ]);
170
            return $this->render('view', [
171
                'model' => $model,
172
                'assignModel' => $assignModel
173
            ]);
174
        }
175
        return $this->redirect(['index']);
176
    }
177
178
    /**
179
     * Creates a new User model.
180
     * @return string|Response
181
     * @throws Exception
182
     */
183
    public function actionCreate()
184
    {
185
        $model = new User();
186
        $model->scenario = $model::SCENARIO_ADMIN_CREATE;
187
        $model->status = $model::STATUS_WAIT;
188
        if ($model->load(Yii::$app->request->post())) {
189
            $model->setPassword($model->password);
190
            if ($model->save()) {
191
                return $this->redirect(['view', 'id' => $model->id]);
192
            }
193
        }
194
        return $this->render('create', [
195
            'model' => $model
196
        ]);
197
    }
198
199
    /**
200
     * @param int|string $id
201
     * @return string|Response
202
     * @throws NotFoundHttpException
203
     * @throws Exception
204
     */
205
    public function actionUpdate($id)
206
    {
207
        $model = $this->findModel($id);
208
        if ($model->load(Yii::$app->request->post()) && $model->profile->load(Yii::$app->request->post())) {
209
            if (!empty($model->password)) {
210
                $model->setPassword($model->password);
211
            }
212
            if ($model->save() && $model->profile->save()) {
213
                return $this->redirect(['view', 'id' => $model->id]);
214
            }
215
        }
216
        return $this->render('update', [
217
            'model' => $model
218
        ]);
219
    }
220
221
    /**
222
     * @param int|string $id
223
     * @return array|Response
224
     * @throws NotFoundHttpException
225
     */
226
    public function actionSetStatus($id)
227
    {
228
        if (Yii::$app->request->isAjax) {
229
            Yii::$app->response->format = Response::FORMAT_JSON;
230
            $result = $this->processChangeStatus($id);
231
            return [
232
                'result' => $result->statusLabelName
233
            ];
234
        }
235
        $this->processChangeStatus($id);
236
        return $this->redirect(Yii::$app->request->referrer);
237
    }
238
239
    /**
240
     * @param int|string $id
241
     * @return User
242
     * @throws NotFoundHttpException
243
     */
244
    protected function processChangeStatus($id)
245
    {
246
        $model = $this->findModel($id);
247
        /** @var User $identity */
248
        $identity = Yii::$app->user->identity;
249
        if ($model->id !== $identity->id && !$model->isSuperAdmin($model->id)) {
250
            $model->setStatus();
251
            $model->save(false);
252
        }
253
        return $model;
254
    }
255
256
    /**
257
     * @param $id
258
     * @return array|Response
259
     * @throws Exception
260
     * @throws NotFoundHttpException
261
     */
262
    public function actionSendConfirmEmail($id)
263
    {
264
        if (Yii::$app->request->isAjax) {
265
            Yii::$app->response->format = Response::FORMAT_JSON;
266
            $result = $this->processSendEmail($id);
267
            $name = (!$result->errors) ? 'success' : 'danger';
268
            return [
269
                'result' => $result->getLabelMailConfirm($name)
270
            ];
271
        }
272
        $this->processSendEmail($id);
273
        return $this->redirect(Yii::$app->request->referrer);
274
    }
275
276
    /**
277
     * @param $id
278
     * @return User
279
     * @throws Exception
280
     * @throws NotFoundHttpException
281
     */
282
    protected function processSendEmail($id)
283
    {
284
        $model = $this->findModel($id);
285
        $model->generateEmailConfirmToken();
286
        $model->save(false);
287
        $model->sendConfirmEmail();
288
        return $model;
289
    }
290
291
    /**
292
     * Action Generate new auth key
293
     * @param $id
294
     * @return array|Response
295
     * @throws Exception
296
     * @throws NotFoundHttpException
297
     */
298
    public function actionGenerateAuthKey($id)
299
    {
300
        $model = $this->processGenerateAuthKey($id);
301
        if (Yii::$app->request->isAjax) {
302
            Yii::$app->response->format = Response::FORMAT_JSON;
303
            return [
304
                'success' => $model->auth_key
305
            ];
306
        }
307
        return $this->redirect(['index']);
308
    }
309
310
    /**
311
     * Generate new auth key
312
     * @param $id
313
     * @return User
314
     * @throws Exception
315
     * @throws NotFoundHttpException
316
     */
317
    private function processGenerateAuthKey($id)
318
    {
319
        $model = $this->findModel($id);
320
        $model->generateAuthKey();
321
        $model->save();
322
        return $model;
323
    }
324
325
    /**
326
     * Deletes an existing User model.
327
     * If deletion is successful, the browser will be redirected to the 'index' page.
328
     * @param int|string $id
329
     * @return Response
330
     * @throws NotFoundHttpException
331
     * @throws Exception
332
     * @throws \Throwable
333
     * @throws StaleObjectException
334
     */
335
    public function actionDelete($id)
336
    {
337
        $model = $this->findModel($id);
338
        if (!$model->isSuperAdmin()) {
339
            /** @var yii\web\Session $session */
340
            $session = Yii::$app->session;
341
            if ($model->isDeleted()) {
342
                $model->delete();
343
                $session->setFlash(
344
                    'success',
345
                    Module::translate(
346
                        'module',
347
                        'The user "{:name}" have been successfully deleted.',
348
                        [
349
                            ':name' => $model->username
350
                        ]
351
                    )
352
                );
353
            } else {
354
                /** @var $model SoftDeleteBehavior */
355
                $model->softDelete();
356
                $session->setFlash(
357
                    'success',
358
                    Module::translate(
359
                        'module',
360
                        'The user "{:name}" are marked as deleted.',
361
                        [
362
                            ':name' => $model->username
363
                        ]
364
                    )
365
                );
366
            }
367
        }
368
        return $this->redirect(['index']);
369
    }
370
371
    /**
372
     * Finds the User model based on its primary key value.
373
     * If the model is not found, a 404 HTTP exception will be thrown.
374
     * @param int|string $id
375
     * @return User the loaded model
376
     * @throws NotFoundHttpException if the model cannot be found
377
     */
378
    protected function findModel($id)
379
    {
380
        if (($model = User::findOne($id)) !== null) {
381
            return $model;
382
        }
383
        throw new NotFoundHttpException(Module::translate('module', 'The requested page does not exist.'));
384
    }
385
}
386