Completed
Push — master ( 55e0f0...d0f882 )
by Alexey
11:22
created

DefaultController::actionStatus()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 12
nc 5
nop 1
1
<?php
2
namespace modules\users\controllers\backend;
3
4
use Yii;
5
use modules\users\models\LoginForm;
6
use modules\users\models\User;
7
use modules\users\models\search\UserSearch;
8
use yii\web\Controller;
9
use yii\web\NotFoundHttpException;
10
use yii\filters\VerbFilter;
11
use yii\filters\AccessControl;
12
use modules\rbac\models\Permission;
13
use modules\rbac\models\Assignment;
14
use modules\users\Module;
15
16
/**
17
 * Class DefaultController
18
 * @package modules\users\controllers\backend
19
 */
20
class DefaultController extends Controller
21
{
22
    protected $jsFile;
23
24
    /**
25
     * @inheritdoc
26
     */
27
    public function behaviors()
28
    {
29
        return [
30
            'verbs' => [
31
                'class' => VerbFilter::className(),
32
                'actions' => [
33
                    'delete' => ['POST'],
34
                    'logout' => ['POST'],
35
                ],
36
            ],
37
            'access' => [
38
                'class' => AccessControl::className(),
39
                'rules' => [
40
                    [
41
                        'actions' => ['login'],
42
                        'allow' => true,
43
                        'roles' => ['?']
44
                    ],
45
                    [
46
                        'actions' => ['logout'],
47
                        'allow' => true,
48
                        'roles' => ['@']
49
                    ],
50
                    [
51
                        'allow' => true,
52
                        'roles' => [Permission::PERMISSION_MANAGER_USERS]
53
                    ],
54
                ],
55
            ],
56
        ];
57
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62
    public function init()
63
    {
64
        parent::init();
65
        $this->processRegisterJs();
66
    }
67
68
    /**
69
     * Publish and register the required JS file
70
     */
71
    protected function processRegisterJs()
72
    {
73
        $this->jsFile = '@modules/users/views/ajax/ajax.js';
74
        Yii::$app->assetManager->publish($this->jsFile);
75
        $this->getView()->registerJsFile(
76
            Yii::$app->assetManager->getPublishedUrl($this->jsFile),
77
            ['depends' => 'yii\web\JqueryAsset',] // depends
78
        );
79
    }
80
81
    /**
82
     * Lists all User models.
83
     * @return mixed
84
     */
85
    public function actionIndex()
86
    {
87
        $searchModel = new UserSearch();
88
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
89
        $assignModel = new Assignment();
90
        return $this->render('index', [
91
            'searchModel' => $searchModel,
92
            'dataProvider' => $dataProvider,
93
            'assignModel' => $assignModel,
94
        ]);
95
    }
96
97
    /**
98
     * Displays a single User model.
99
     * @param integer $id
100
     * @return mixed
101
     */
102
    public function actionView($id)
103
    {
104
        if ($model = $this->findModel($id)) {
105
            $assignModel = new Assignment([
106
                'user' => $model
107
            ]);
108
            return $this->render('view', [
109
                'model' => $model,
110
                'assignModel' => $assignModel,
111
            ]);
112
        }
113
        return $this->redirect(['index']);
114
    }
115
116
    /**
117
     * Generate new auth key
118
     * @param $id
119
     * @throws NotFoundHttpException
120
     */
121
    public function actionGenerateAuthKey($id)
122
    {
123
        $model = $this->findModel($id);
124
        $model->generateAuthKey();
125
        $model->save();
126
        $this->redirect(['view', 'id' => $model->id]);
127
    }
128
129
    /**
130
     * Creates a new User model.
131
     * If creation is successful, the browser will be redirected to the 'view' page.
132
     * @return mixed
133
     */
134
    public function actionCreate()
135
    {
136
        $model = new User();
137
        $model->status = $model::STATUS_WAIT;
138
        /** @var \modules\users\models\User $identity */
139
        $identity = Yii::$app->user->identity;
140
        $model->registration_type = $identity->id;
141
142
        if ($model->load(Yii::$app->request->post())) {
143
            if ($model->save()) {
144
                return $this->redirect(['view', 'id' => $model->id]);
145
            }
146
        }
147
148
        $model->scenario = $model::SCENARIO_ADMIN_CREATE;
149
        return $this->render('create', [
150
            'model' => $model,
151
        ]);
152
    }
153
154
    /**
155
     * Updates an existing User model.
156
     * If update is successful, the browser will be redirected to the 'view' page.
157
     * @param integer $id
158
     * @return mixed
159
     */
160
    public function actionUpdate($id)
161
    {
162
        if ($model = $this->findModel($id)) {
163
            return $this->render('update', [
164
                'model' => $model,
165
            ]);
166
        }
167
        return $this->redirect(['index']);
168
    }
169
170
    /**
171
     * @param $id
172
     * @return \yii\web\Response
173
     * @throws NotFoundHttpException
174
     */
175
    public function actionUpdateProfile($id)
176
    {
177
        if ($model = $this->findModel($id)) {
178
            $model->scenario = $model::SCENARIO_ADMIN_UPDATE;
179
180
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
181
                Yii::$app->session->setFlash('success', Module::t('module', 'Profile successfully changed.'));
182
            } else {
183
                Yii::$app->session->setFlash('error', Module::t('module', 'Error! Profile not changed.'));
184
            }
185
        }
186
        return $this->redirect(['update', 'id' => $model->id, 'tab' => 'profile']);
187
    }
188
189
    /**
190
     * @param $id
191
     * @return \yii\web\Response
192
     * @throws NotFoundHttpException
193
     */
194
    public function actionUpdatePassword($id)
195
    {
196
        if ($model = $this->findModel($id)) {
197
            $model->scenario = $model::SCENARIO_ADMIN_PASSWORD_UPDATE;
198
199
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
200
                Yii::$app->session->setFlash('success', Module::t('module', 'Password changed successfully.'));
201
            } else {
202
                Yii::$app->session->setFlash('error', Module::t('module', 'Error! Password changed not successfully.'));
203
            }
204
        }
205
        return $this->redirect(['update', 'id' => $model->id, 'tab' => 'password']);
206
    }
207
208
    /**
209
     * Change Status
210
     * @param $id
211
     * @return array|\yii\web\Response
212
     * @throws NotFoundHttpException
213
     */
214
    public function actionStatus($id)
215
    {
216
        if (Yii::$app->request->isAjax) {
217
            if ($model = $this->findModel($id)) {
218
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
219
                /**
220
                 * Запрещаем менять статус у себя
221
                 * @var \modules\users\models\User $identity
222
                 */
223
                $identity = Yii::$app->user->identity;
224
                if ($model->id !== $identity->id) {
225
                    $model->setStatus();
226
                    if ($model->save()) {
227
                        return [
228
                            'body' => $model->getStatusLabelName(),
229
                            'success' => true,
230
                        ];
231
                    }
232
                }
233
            }
234
        }
235
        return $this->redirect(['index']);
236
    }
237
238
    /**
239
     * Deletes an existing User model.
240
     * If deletion is successful, the browser will be redirected to the 'index' page.
241
     * @param integer $id
242
     * @return mixed
243
     */
244
    public function actionDelete($id)
245
    {
246
        $model = $this->findModel($id);
247
        // Запрещаем удалять самого себя
248
        if ($model->id !== Yii::$app->user->identity->getId()) {
249
            if ($model->isDeleted()) {
250
                if ($model->delete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model->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...
251
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" have been successfully deleted.', [':name' => $model->username]));
252
                }
253
            } else {
254
                $model->scenario = $model::SCENARIO_PROFILE_DELETE;
255
                $model->status = $model::STATUS_DELETED;
256
                if ($model->save()) {
257
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" are marked as deleted.', [':name' => $model->username]));
258
                }
259
            }
260
        } else {
261
            Yii::$app->session->setFlash('warning', Module::t('module', 'You can not remove yourself.'));
262
        }
263
        return $this->redirect(['index']);
264
    }
265
266
    /**
267
     * Finds the User model based on its primary key value.
268
     * If the model is not found, a 404 HTTP exception will be thrown.
269
     * @param integer $id
270
     * @return User the loaded model
271
     * @throws NotFoundHttpException if the model cannot be found
272
     */
273
    protected function findModel($id)
274
    {
275
        if (($model = User::findOne($id)) !== null) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \modules\users\models\User::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 276 which is incompatible with the return type documented by modules\users\controller...ltController::findModel of type modules\users\models\User.
Loading history...
276
            return $model;
277
        } else {
278
            throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
279
        }
280
    }
281
282
    /**
283
     * Login action.
284
     *
285
     * @return string
286
     */
287
    public function actionLogin()
288
    {
289
        if (!Yii::$app->user->isGuest) {
290
            return $this->goHome();
291
        }
292
293
        $this->layout = '//login';
294
295
        $model = new LoginForm();
296
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
297
            // Если запрещен доступ к Backend сбрасываем авторизацию записываем сообщение в сессию
298
            // и перебрасываем на страницу входа
299
            if (!Yii::$app->user->can(\modules\rbac\models\Permission::PERMISSION_VIEW_ADMIN_PAGE)) {
300
                Yii::$app->user->logout();
301
                Yii::$app->session->setFlash('error', Module::t('module', 'You do not have rights, access is denied.'));
302
                return $this->goHome();
303
            }
304
            return $this->goBack();
305
        }
306
        return $this->render('login', [
307
            'model' => $model,
308
        ]);
309
    }
310
311
    /**
312
     * Logout action.
313
     *
314
     * @return string
315
     */
316
    public function actionLogout()
317
    {
318
        Yii::$app->user->logout();
319
        return $this->goHome();
320
    }
321
}
322