Passed
Push — master ( 399152...14bbe3 )
by Alexey
02:45
created

BaseController::findModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace modules\users\controllers\backend;
4
5
use Yii;
6
use modules\users\models\LoginForm;
7
use modules\users\models\User;
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\users\Module;
14
15
/**
16
 * Class BaseController
17
 * @package modules\users\controllers\backend
18
 */
19
class BaseController extends Controller
20
{
21
    /** @var  string|bool $jsFile */
22
    protected $jsFile;
23
24
    /**
25
     * @inheritdoc
26
     * @return array
27
     */
28
    public function behaviors()
29
    {
30
        return [
31
            'verbs' => [
32
                'class' => VerbFilter::className(),
33
                'actions' => [
34
                    'delete' => ['POST'],
35
                    'logout' => ['POST'],
36
                ],
37
            ],
38
            'access' => [
39
                'class' => AccessControl::className(),
40
                'rules' => [
41
                    [
42
                        'actions' => ['login'],
43
                        'allow' => true,
44
                        'roles' => ['?']
45
                    ],
46
                    [
47
                        'actions' => ['logout'],
48
                        'allow' => true,
49
                        'roles' => ['@']
50
                    ],
51
                    [
52
                        'allow' => true,
53
                        'roles' => [Permission::PERMISSION_MANAGER_USERS]
54
                    ],
55
                ],
56
            ],
57
        ];
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function init()
64
    {
65
        parent::init();
66
        $this->processRegisterJs();
67
    }
68
69
    /**
70
     * Publish and register the required JS file
71
     */
72
    protected function processRegisterJs()
73
    {
74
        $this->jsFile = '@modules/users/views/ajax/ajax.js';
75
        $assetManager = Yii::$app->assetManager;
76
        $assetManager->publish($this->jsFile);
77
        $url = $assetManager->getPublishedUrl($this->jsFile);
78
        $this->view->registerJsFile($url,
79
            ['depends' => 'yii\web\JqueryAsset',] // depends
80
        );
81
    }
82
83
    /**
84
     * Generate new auth key
85
     * @param int|string $id
86
     * @throws NotFoundHttpException
87
     */
88
    public function actionGenerateAuthKey($id)
89
    {
90
        $model = $this->findModel($id);
91
        $model->generateAuthKey();
92
        $model->save();
93
        $this->redirect(['view', 'id' => $model->id]);
94
    }
95
96
    /**
97
     * Deletes an existing User model.
98
     * If deletion is successful, the browser will be redirected to the 'index' page.
99
     * @param int|string $id
100
     * @return mixed
101
     */
102
    public function actionDelete($id)
103
    {
104
        /** @var \modules\users\models\User $model */
105
        $model = $this->findModel($id);
106
        // Запрещаем удалять самого себя
107
        /** @var object $identity */
108
        $identity = Yii::$app->user->identity;
109
        if ($model->id !== $identity->id) {
110
            if ($model->isDeleted()) {
111
                if ($model->delete() !== false) {
112
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" have been successfully deleted.', [':name' => $model->username]));
113
                }
114
            } else {
115
                $model->scenario = User::SCENARIO_PROFILE_DELETE;
116
                $model->status = User::STATUS_DELETED;
117
                if ($model->save()) {
118
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" are marked as deleted.', [':name' => $model->username]));
119
                }
120
            }
121
        } else {
122
            Yii::$app->session->setFlash('warning', Module::t('module', 'You can not remove yourself.'));
123
        }
124
        return $this->redirect(['index']);
125
    }
126
127
    /**
128
     * Finds the User model based on its primary key value.
129
     * If the model is not found, a 404 HTTP exception will be thrown.
130
     * @param int|string $id
131
     * @return null|User the loaded model
132
     * @throws NotFoundHttpException if the model cannot be found
133
     */
134
    protected function findModel($id)
135
    {
136
        if (($model = User::findOne($id)) !== null) {
137
            return $model;
138
        }
139
        throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
140
    }
141
142
    /**
143
     * Login action.
144
     *
145
     * @return string|\yii\web\Response
146
     */
147
    public function actionLogin()
148
    {
149
        if (!Yii::$app->user->isGuest) {
150
            return $this->goHome();
151
        }
152
153
        $this->layout = '//login';
154
155
        $model = new LoginForm();
156
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
157
            // Если запрещен доступ к Backend сбрасываем авторизацию записываем сообщение в сессию
158
            // и перебрасываем на страницу входа
159
            if (!Yii::$app->user->can(\modules\rbac\models\Permission::PERMISSION_VIEW_ADMIN_PAGE)) {
160
                Yii::$app->user->logout();
161
                Yii::$app->session->setFlash('error', Module::t('module', 'You do not have rights, access is denied.'));
162
                return $this->goHome();
163
            }
164
            return $this->goBack();
165
        }
166
        return $this->render('login', [
167
            'model' => $model,
168
        ]);
169
    }
170
171
    /**
172
     * Logout action.
173
     *
174
     * @return \yii\web\Response
175
     */
176
    public function actionLogout()
177
    {
178
        $model = new LoginForm();
179
        $model->logout();
180
        return $this->goHome();
181
    }
182
}
183