Passed
Push — master ( d3f2d9...c04c68 )
by Alexey
02:27
created

DefaultController::findModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace modules\users\controllers\backend;
4
5
use Yii;
6
use yii\web\Response;
7
use yii\web\Controller;
8
use yii\filters\VerbFilter;
9
use yii\filters\AccessControl;
10
use yii\web\NotFoundHttpException;
11
use modules\users\models\LoginForm;
12
use modules\rbac\models\Permission;
13
use modules\rbac\models\Assignment;
14
use modules\users\models\User;
15
use modules\users\models\search\UserSearch;
16
use modules\users\Module;
17
18
/**
19
 * Class DefaultController
20
 * @package modules\users\controllers\backend
21
 *
22
 * @property array $access
23
 * @property  array $verb
24
 */
25
class DefaultController extends Controller
26
{
27
    /**
28
     * @inheritdoc
29
     * @return array
30
     */
31
    public function behaviors()
32
    {
33
        return [
34
            'verbs' => $this->getVerb(),
35
            'access' => $this->getAccess()
36
        ];
37
    }
38
39
    /**
40
     * @return array
41
     */
42
    private function getVerb()
43
    {
44
        return [
45
            'class' => VerbFilter::class,
46
            'actions' => [
47
                'delete' => ['POST'],
48
                'logout' => ['POST'],
49
            ],
50
        ];
51
    }
52
53
    /**
54
     * @return array
55
     */
56
    private function getAccess()
57
    {
58
        return [
59
            'class' => AccessControl::class,
60
            'rules' => [
61
                [
62
                    'actions' => ['login'],
63
                    'allow' => true,
64
                    'roles' => ['?']
65
                ],
66
                [
67
                    'actions' => ['logout'],
68
                    'allow' => true,
69
                    'roles' => ['@']
70
                ],
71
                [
72
                    'allow' => true,
73
                    'roles' => [Permission::PERMISSION_MANAGER_USERS]
74
                ],
75
            ],
76
        ];
77
    }
78
79
    /**
80
     * Login action.
81
     *
82
     * @return string|\yii\web\Response
83
     */
84
    public function actionLogin()
85
    {
86
        if (!Yii::$app->user->isGuest) {
87
            return $this->goHome();
88
        }
89
90
        $this->layout = '//login';
91
92
        $model = new LoginForm();
93
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
94
            return $this->processCheckPermissionLogin();
95
        }
96
        return $this->render('login', [
97
            'model' => $model,
98
        ]);
99
    }
100
101
    /**
102
     * @return \yii\web\Response
103
     */
104
    protected function processCheckPermissionLogin()
105
    {
106
        // If access to Backend is denied, reset authorization, write a message to the session
107
        // and move it to the login page
108
        if (!Yii::$app->user->can(Permission::PERMISSION_VIEW_ADMIN_PAGE)) {
0 ignored issues
show
Bug introduced by
The method can() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
        if (!Yii::$app->user->/** @scrutinizer ignore-call */ can(Permission::PERMISSION_VIEW_ADMIN_PAGE)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
109
            Yii::$app->user->logout();
110
            Yii::$app->session->setFlash('error', Module::t('module', 'You do not have rights, access is denied.'));
0 ignored issues
show
Bug introduced by
The method setFlash() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

110
            Yii::$app->session->/** @scrutinizer ignore-call */ 
111
                                setFlash('error', Module::t('module', 'You do not have rights, access is denied.'));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
111
            return $this->goHome();
112
        }
113
        return $this->goBack();
114
    }
115
116
    /**
117
     * Logout action.
118
     *
119
     * @return \yii\web\Response
120
     */
121
    public function actionLogout()
122
    {
123
        $model = new LoginForm();
124
        $model->logout();
125
        return $this->goHome();
126
    }
127
128
    /**
129
     * @return string
130
     * @throws \yii\base\InvalidConfigException
131
     */
132
    public function actionIndex()
133
    {
134
        $searchModel = new UserSearch();
135
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
136
        $assignModel = new Assignment();
137
        return $this->render('index', [
138
            'searchModel' => $searchModel,
139
            'dataProvider' => $dataProvider,
140
            'assignModel' => $assignModel,
141
        ]);
142
    }
143
144
    /**
145
     * Displays a single User model.
146
     * @param int|string $id
147
     * @return string|\yii\web\Response
148
     * @throws NotFoundHttpException
149
     */
150
    public function actionView($id)
151
    {
152
        if ($model = $this->findModel($id)) {
153
            $assignModel = new Assignment([
154
                'user' => $model
155
            ]);
156
            return $this->render('view', [
157
                'model' => $model,
158
                'assignModel' => $assignModel,
159
            ]);
160
        }
161
        return $this->redirect(['index']);
162
    }
163
164
    /**
165
     * Creates a new User model.
166
     * @return string|Response
167
     * @throws \yii\base\Exception
168
     */
169
    public function actionCreate()
170
    {
171
        $model = new User();
172
        $model->scenario = $model::SCENARIO_ADMIN_CREATE;
173
        $model->status = $model::STATUS_WAIT;
174
        if ($model->load(Yii::$app->request->post())) {
175
            $model->setPassword($model->password);
176
            if ($model->save()) {
177
                return $this->redirect(['view', 'id' => $model->id]);
178
            }
179
        }
180
        return $this->render('create', [
181
            'model' => $model,
182
        ]);
183
    }
184
185
    /**
186
     * @param int|string $id
187
     * @return string|Response
188
     * @throws NotFoundHttpException
189
     * @throws \yii\base\Exception
190
     */
191
    public function actionUpdate($id)
192
    {
193
        $model = $this->findModel($id);
194
        if ($model->load(Yii::$app->request->post()) && $model->profile->load(Yii::$app->request->post())) {
195
            if (!empty($model->password)) {
196
                $model->setPassword($model->password);
197
            }
198
            if ($model->save() && $model->profile->save()) {
199
                return $this->redirect(['view', 'id' => $model->id]);
200
            }
201
        }
202
        return $this->render('update', [
203
            'model' => $model,
204
        ]);
205
    }
206
207
    /**
208
     * @param int|string $id
209
     * @return array|Response
210
     * @throws NotFoundHttpException
211
     */
212
    public function actionSetStatus($id)
213
    {
214
        if (Yii::$app->request->isAjax) {
215
            Yii::$app->response->format = Response::FORMAT_JSON;
216
            $result = $this->processChangeStatus($id);
217
            return [
218
                'result' => $result->statusLabelName,
219
            ];
220
        }
221
        $this->processChangeStatus($id);
222
        return $this->redirect(Yii::$app->request->referrer);
223
    }
224
225
    /**
226
     * @param int|string $id
227
     * @return User
228
     * @throws NotFoundHttpException
229
     */
230
    protected function processChangeStatus($id)
231
    {
232
        $model = $this->findModel($id);
233
        /** @var User $identity */
234
        $identity = Yii::$app->user->identity;
235
        if ($model->id !== $identity->id && !$model->isSuperAdmin($model->id)) {
236
            $model->setStatus();
237
            $model->save(false);
238
        }
239
        return $model;
240
    }
241
242
    /**
243
     * @param int|string $id
244
     * @return array|Response
245
     * @throws NotFoundHttpException
246
     */
247
    public function actionSendConfirmEmail($id)
248
    {
249
        if (Yii::$app->request->isAjax) {
250
            Yii::$app->response->format = Response::FORMAT_JSON;
251
            $result = $this->processSendEmail($id);
252
            $name = (!$result->errors) ? 'success' : 'danger';
253
            return [
254
                'result' => $result->getLabelMailConfirm($name),
255
            ];
256
        }
257
        $this->processSendEmail($id);
258
        return $this->redirect(Yii::$app->request->referrer);
259
    }
260
261
    /**
262
     * @param int|string $id
263
     * @return array|User|null
264
     * @throws NotFoundHttpException
265
     */
266
    protected function processSendEmail($id)
267
    {
268
        $model = $this->findModel($id);
269
        $model->generateEmailConfirmToken();
270
        $model->save(false);
271
        $model->sendConfirmEmail();
272
        return $model;
273
    }
274
275
    /**
276
     * Action Generate new auth key
277
     * @param int|string $id
278
     * @return array|Response
279
     * @throws NotFoundHttpException
280
     */
281
    public function actionGenerateAuthKey($id)
282
    {
283
        $model = $this->processGenerateAuthKey($id);
284
        if (Yii::$app->request->isAjax) {
285
            Yii::$app->response->format = Response::FORMAT_JSON;
286
            return [
287
                'success' => $model->auth_key,
288
            ];
289
        }
290
        return $this->redirect(['index']);
291
    }
292
293
    /**
294
     * Generate new auth key
295
     * @param int|string $id
296
     * @return User|null
297
     * @throws NotFoundHttpException
298
     */
299
    private function processGenerateAuthKey($id)
300
    {
301
        $model = $this->findModel($id);
302
        $model->generateAuthKey();
303
        $model->save();
304
        return $model;
305
    }
306
307
    /**
308
     * Deletes an existing User model.
309
     * If deletion is successful, the browser will be redirected to the 'index' page.
310
     * @param int|string $id
311
     * @return \yii\web\Response
312
     * @throws NotFoundHttpException
313
     * @throws \Exception
314
     * @throws \Throwable
315
     * @throws \yii\db\StaleObjectException
316
     */
317
    public function actionDelete($id)
318
    {
319
        $model = $this->findModel($id);
320
        if (!$model->isSuperAdmin()) {
321
            if ($model->isDeleted()) {
322
                $model->delete();
323
                Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" have been successfully deleted.', [':name' => $model->username]));
324
            } else {
325
                /** @var $model \yii2tech\ar\softdelete\SoftDeleteBehavior */
326
                $model->softDelete();
327
                /** @var $model User */
328
                Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" are marked as deleted.', [':name' => $model->username]));
329
            }
330
        }
331
        return $this->redirect(['index']);
332
    }
333
334
    /**
335
     * Finds the User model based on its primary key value.
336
     * If the model is not found, a 404 HTTP exception will be thrown.
337
     * @param int|string $id
338
     * @return null|User the loaded model
339
     * @throws NotFoundHttpException if the model cannot be found
340
     */
341
    protected function findModel($id)
342
    {
343
        if (($model = User::findOne($id)) !== null) {
344
            return $model;
345
        }
346
        throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
347
    }
348
}
349