Completed
Push — master ( 04d388...479b0f )
by vistart
04:24
created

UserController::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 48
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 48
rs 9.125
cc 1
eloc 27
nc 1
nop 0
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\user\web\admin\controllers;
14
15
use rhosocial\user\User;
16
use rhosocial\user\Profile;
17
use rhosocial\user\forms\ChangePasswordForm;
18
use rhosocial\user\forms\RegisterForm;
19
use Yii;
20
use yii\data\ActiveDataProvider;
21
use yii\filters\AccessControl;
22
use yii\filters\VerbFilter;
23
use yii\web\Controller;
24
use yii\web\BadRequestHttpException;
25
use yii\web\ForbiddenHttpException;
26
use yii\web\MethodNotAllowedHttpException;
27
use yii\web\ServerErrorHttpException;
28
use yii\web\UnauthorizedHttpException;
29
30
/**
31
 * @version 1.0
32
 * @author vistart <[email protected]>
33
 */
34
class UserController extends Controller
35
{
36
    public $layout = 'user';
37
    const RESULT_SUCCESS = 'success';
38
    const RESULT_FAILED = 'failed';
39
    const SESSION_KEY_MESSAGE = 'session_key_message';
40
    const SESSION_KEY_RESULT = 'session_key_result';
41
42
    public $registerSuccessMessage;
43
    public $registerFailedMessage;
44
45
    public $deregisterSuccessMessage;
46
    public $deregisterFailedMessage;
47
    
48
    public $updateSuccessMessage;
49
    public $updateFailedMessage;
50
51
    protected function initMessages()
52
    {
53
        if (!is_string($this->registerSuccessMessage)) {
54
            $this->registerSuccessMessage = Yii::t('user' ,'User Registered.');
55
        }
56
        if (!is_string($this->registerFailedMessage)) {
57
            $this->registerFailedMessage = Yii::t('user', 'Register Failed.');
58
        }
59
        if (!is_string($this->deregisterSuccessMessage)) {
60
            $this->deregisterSuccessMessage = Yii::t('user', 'User Deregistered.');
61
        }
62
        if (!is_string($this->deregisterFailedMessage)) {
63
            $this->deregisterFailedMessage = Yii::t('user', 'Failed to Deregister User.');
64
        }
65
        if (!is_string($this->updateSuccessMessage)) {
66
            $this->updateSuccessMessage = Yii::t('user', 'Updated.');
67
        }
68
        if (!is_string($this->updateFailedMessage)) {
69
            $this->updateFailedMessage = Yii::t('user', 'Failed to Update.');
70
        }
71
    }
72
73
    public function init()
74
    {
75
        $this->initMessages();
76
        parent::init();
77
    }
78
79
    public function behaviors() {
80
        return [
81
            'access' => [
82
                'class' => AccessControl::class,
83
                'rules' => [
84
                    [ // Disallow all unauthorized users to access this controller.
85
                        'allow' => false,
86
                        'roles' => ['?'],
87
                    ],
88
                    [ // Allow the user who has the `viewUser` permission to access the `index` action.
89
                        'actions' => ['index'],
90
                        'allow' => true,
91
                        'roles' => ['viewUser'],
92
                    ],
93
                    [ // Disallow other non-admin users to access this controller.
94
                        'allow' => false,
95
                        'matchCallback' => function ($rule, $action) {
0 ignored issues
show
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
                            return !Yii::$app->authManager->checkAccess(Yii::$app->user->identity, 'admin');
97
                        },
98
                        'denyCallback' => function ($rule, $action) {
0 ignored issues
show
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
99
                            throw new UnauthorizedHttpException(Yii::t('user', 'You are not an administrator and have no access to this page.'));
100
                        },
101
                    ],
102
                    [ // Disallow admin users to access deregister action directly, only `POST` accepted.
103
                        'actions' => ['deregister'],
104
                        'allow' => false,
105
                        'matchCallback' => function ($rule, $action) {
0 ignored issues
show
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
106
                            return strtoupper(Yii::$app->request->getMethod()) != 'POST';
107
                        },
108
                        'denyCallback' => function ($rule, $action) {
0 ignored issues
show
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
109
                            throw new MethodNotAllowedHttpException(Yii::t('user', 'You cannot access this page directly.'));
110
                        },
111
                    ],
112
                    [ // Allow admin user to access other views.
113
                      // This is a final rule, if you want to add other rules, please put it before this rule.
114
                        'allow' => true,
115
                        'roles' => ['admin'], // Administrator can access this controller.
116
                    ],
117
                ],
118
            ],
119
            'verbs' => [
120
                'class' => VerbFilter::class,
121
                'actions' => [
122
                    'deregister' => ['post'],
123
                ],
124
            ],
125
        ];
126
    }
127
128
    public function actionIndex()
129
    {
130
        $class = Yii::$app->user->identityClass;
131
        if (!class_exists($class)) {
132
            return $this->render('index', ['dataProvider' => null]);
133
        }
134
        $dataProvider = new ActiveDataProvider([
135
            'query' => $class::find(),
136
            'pagination' => [
137
                'pageParam' => 'user-page',
138
                'pageSize' => 20,
139
            ],
140
            'sort' => [
141
                'sortParam' => 'user-sort',
142
            ],
143
        ]);
144
        return $this->render('index', ['dataProvider' => $dataProvider]);
145
    }
146
147
    public function actionRegisterNewUser()
148
    {
149
        $model = new RegisterForm();
150
        if ($model->load(Yii::$app->request->post())) {
151
            try {
152
                if (($result = $model->register()) === true) {
153
                    Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
154
                    Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $model->model->getID() . ') ' . $this->registerSuccessMessage);
155
                    return $this->redirect(['index']);
156
                }
157
                if ($result instanceof \Exception) {
158
                    throw $result;
159
                }
160
            } catch (\Exception $ex) {
161
                Yii::error($ex->getMessage(), __METHOD__);
162
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
163
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, $ex->getMessage());
164
            }
165
        }
166
        return $this->render('register-new-user', ['model' => $model]);
167
    }
168
169
    /**
170
     * Get user by ID.
171
     * @param string $id User ID.
172
     * @return User
173
     * @throws BadRequestHttpException throw if user not found.
174
     */
175
    protected function getUser($id)
176
    {
177
        $class = Yii::$app->user->identityClass;
178
        if (!class_exists($class)) {
179
            return null;
180
        }
181
        $user = $class::find()->id($id)->one();
182
        if (empty($user) || !($user instanceof User)) {
183
            throw new BadRequestHttpException(Yii::t('user', 'User Not Found.'));
184
        }
185
        return $user;
186
    }
187
188
    /**
189
     * Deregister User.
190
     * @param string $id User ID.
191
     * @return string
192
     */
193
    public function actionDeregister($id)
194
    {
195
        $id = (int)$id;
196
        if (Yii::$app->user->identity->getID() == $id) {
197
            throw new ForbiddenHttpException(Yii::t('user', 'You cannot deregister yourself.'));
198
        }
199
        $user = $this->getUser($id);
200
        try {
201
            $result = $user->deregister();
202
            if ($result instanceof \Exception) {
203
                throw $result;
204
            }
205
        } catch (\Exception $ex) {
206
            throw new ServerErrorHttpException($ex->getMessage());
207
        }
208
        if ($result !== true) {
209
            throw new ServerErrorHttpException(Yii::t('user', 'Failed to deregister user.'));
210
        }
211
        Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
212
        Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->deregisterSuccessMessage);
213
        return $this->redirect(['index']);
214
    }
215
216
    public function actionView($id)
217
    {
218
        $user = $this->getUser($id);
219
        return $this->render('view', ['user' => $user]);
220
    }
221
222
    public function actionUpdate($id)
223
    {
224
        $user = $this->getUser($id);
225
        $model = $user->profile;
226
        if (empty($model)) {
227
            $model = $user->createProfile();
228
        }
229
        $model->scenario = Profile::SCENARIO_UPDATE;
230
        if ($model->load(Yii::$app->request->post())) {
231
            if ($model->getGUID() != $user->getGUID()) {
232
                throw new BadRequestHttpException(Yii::t('user', 'Please do not forge parameters.'));
233
            }
234
            if ($model->save()) {
235
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
236
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateSuccessMessage);
237
                return $this->redirect(['update', 'id' => $id]);
238
            }
239
            Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
240
            Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateFailedMessage);
241
        }
242
        return $this->render('update', ['user' => $user, 'model' => $model]);
243
    }
244
245
    public function actionChangePassword($id)
246
    {
247
        $user = $this->getUser($id);
248
        $model = new ChangePasswordForm(['user' => $user, 'scenario' => ChangePasswordForm::SCENARIO_ADMIN]);
249
        if ($model->load(Yii::$app->request->post())){
250
            if ($model->changePassword()) {
251
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
252
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateSuccessMessage);
253
                return $this->redirect(['index', 'id' => $id]);
254
            } else {
255
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
256
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateFailedMessage);
257
            }
258
        }
259
        return $this->render('change-password', ['model' => $model]);
260
    }
261
}
262