Completed
Push — master ( 51f787...8bc09a )
by Alexey
03:06
created

DefaultController::processGenerateAuthKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
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
class DefaultController extends Controller
23
{
24
    /**
25
     * @inheritdoc
26
     * @return array
27
     */
28
    public function behaviors()
29
    {
30
        return [
31
            'verbs' => $this->getVerbs(),
32
            'access' => $this->getAccess()
33
        ];
34
    }
35
36
    /**
37
     * @return array
38
     */
39
    private function getVerbs()
40
    {
41
        return [
42
            'class' => VerbFilter::class,
43
            'actions' => [
44
                'delete' => ['POST'],
45
                'logout' => ['POST'],
46
            ],
47
        ];
48
    }
49
50
    /**
51
     * @return array
52
     */
53
    private function getAccess()
54
    {
55
        return [
56
            'class' => AccessControl::class,
57
            'rules' => [
58
                [
59
                    'actions' => ['login'],
60
                    'allow' => true,
61
                    'roles' => ['?']
62
                ],
63
                [
64
                    'actions' => ['logout'],
65
                    'allow' => true,
66
                    'roles' => ['@']
67
                ],
68
                [
69
                    'allow' => true,
70
                    'roles' => [Permission::PERMISSION_MANAGER_USERS]
71
                ],
72
            ],
73
        ];
74
    }
75
76
    /**
77
     * Login action.
78
     *
79
     * @return string|\yii\web\Response
80
     */
81
    public function actionLogin()
82
    {
83
        if (!Yii::$app->user->isGuest) {
84
            return $this->goHome();
85
        }
86
87
        $this->layout = '//login';
88
89
        $model = new LoginForm();
90
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
91
            return $this->processCheckPermissionLogin();
92
        }
93
        return $this->render('login', [
94
            'model' => $model,
95
        ]);
96
    }
97
98
    /**
99
     * @return \yii\web\Response
100
     */
101
    protected function processCheckPermissionLogin()
102
    {
103
        // If access to Backend is denied, reset authorization, write a message to the session
104
        // and move it to the login page
105
        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

105
        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...
106
            Yii::$app->user->logout();
107
            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

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