Completed
Push — master ( 0f3d1f...6a4fbf )
by vistart
03:41
created

UserController::actionChangePassword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
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\web\Controller;
23
use yii\web\BadRequestHttpException;
24
use yii\web\ForbiddenHttpException;
25
use yii\web\MethodNotAllowedHttpException;
26
use yii\web\ServerErrorHttpException;
27
use yii\web\UnauthorizedHttpException;
28
29
/**
30
 * @version 1.0
31
 * @author vistart <[email protected]>
32
 */
33
class UserController extends Controller
34
{
35
    public $layout = 'user';
36
    const RESULT_SUCCESS = 'success';
37
    const RESULT_FAILED = 'failed';
38
    const SESSION_KEY_MESSAGE = 'session_key_message';
39
    const SESSION_KEY_RESULT = 'session_key_result';
40
41
    public $registerSuccessMessage;
42
    public $registerFailedMessage;
43
44
    public $deregisterSuccessMessage;
45
    public $deregisterFailedMessage;
46
    
47
    public $updateSuccessMessage;
48
    public $updateFailedMessage;
49
50
    protected function initMessages()
51
    {
52
        if (!is_string($this->registerSuccessMessage)) {
53
            $this->registerSuccessMessage = Yii::t('user' ,'User Registered.');
54
        }
55
        if (!is_string($this->registerFailedMessage)) {
56
            $this->registerFailedMessage = Yii::t('user', 'Register Failed.');
57
        }
58
        if (!is_string($this->deregisterSuccessMessage)) {
59
            $this->deregisterSuccessMessage = Yii::t('user', 'User Deregistered.');
60
        }
61
        if (!is_string($this->deregisterFailedMessage)) {
62
            $this->deregisterFailedMessage = Yii::t('user', 'Failed to Deregister User.');
63
        }
64
        if (!is_string($this->updateSuccessMessage)) {
65
            $this->updateSuccessMessage = Yii::t('user', 'Updated.');
66
        }
67
        if (!is_string($this->updateFailedMessage)) {
68
            $this->updateFailedMessage = Yii::t('user', 'Failed to Update.');
69
        }
70
    }
71
72
    public function init()
73
    {
74
        $this->initMessages();
75
        parent::init();
76
    }
77
78
    public function behaviors() {
79
        return [
80
            'access' => [
81
                'class' => AccessControl::class,
82
                'rules' => [
83
                    [ // Disallow all unauthorized users to access this controller.
84
                        'allow' => false,
85
                        'roles' => ['?'],
86
                    ],
87
                    [ // Allow the user who has the `listUser` permission to access the `index` action.
88
                        'actions' => ['index'],
89
                        'allow' => true,
90
                        'roles' => ['viewUser'],
91
                    ],
92
                    [ // Disallow other non-admin users to access this controller.
93
                        'allow' => false,
94
                        '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...
95
                            return !Yii::$app->authManager->checkAccess(Yii::$app->user->identity, 'admin');
96
                        },
97
                        '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...
98
                            throw new UnauthorizedHttpException(Yii::t('user', 'You are not an administrator and have no access to this page.'));
99
                        },
100
                    ],
101
                    [ // Disallow admin users to access deregister action directly, only `POST` accepted.
102
                        'actions' => ['deregister'],
103
                        'allow' => false,
104
                        '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...
105
                            return strtoupper(Yii::$app->request->getMethod()) != 'POST';
106
                        },
107
                        '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...
108
                            throw new MethodNotAllowedHttpException(Yii::t('user', 'You cannot access this page directly.'));
109
                        },
110
                    ],
111
                    [ // Allow admin user to access other views.
112
                      // This is a final rule, if you want to add other rules, please put it before this rule.
113
                        'allow' => true,
114
                        'roles' => ['admin'], // Administrator can access this controller.
115
                    ],
116
                ],
117
            ],
118
        ];
119
    }
120
121
    public function actionIndex()
122
    {
123
        $class = Yii::$app->user->identityClass;
124
        if (!class_exists($class)) {
125
            return $this->render('index', ['dataProvider' => null]);
126
        }
127
        $dataProvider = new ActiveDataProvider([
128
            'query' => $class::find(),
129
            'pagination' => [
130
                'pageParam' => 'user-page',
131
                'pageSize' => 20,
132
            ],
133
            'sort' => [
134
                'sortParam' => 'user-sort',
135
            ],
136
        ]);
137
        return $this->render('index', ['dataProvider' => $dataProvider]);
138
    }
139
140
    public function actionRegisterNewUser()
141
    {
142
        $model = new RegisterForm();
143
        if ($model->load(Yii::$app->request->post())) {
144
            try {
145
                if (($result = $model->register()) === true) {
146
                    Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
147
                    Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $model->model->getID() . ') ' . $this->registerSuccessMessage);
148
                    return $this->redirect(['index']);
149
                }
150
                if ($result instanceof \Exception) {
151
                    throw $result;
152
                }
153
            } catch (\Exception $ex) {
154
                Yii::error($ex->getMessage(), __METHOD__);
155
                    Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
156
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, $ex->getMessage());
157
            }
158
        }
159
        return $this->render('register-new-user', ['model' => $model]);
160
    }
161
162
    /**
163
     * Get user by ID.
164
     * @param string $id User ID.
165
     * @return User
166
     * @throws BadRequestHttpException throw if user not found.
167
     */
168
    protected function getUser($id)
169
    {
170
        $class = Yii::$app->user->identityClass;
171
        if (!class_exists($class)) {
172
            return null;
173
        }
174
        $user = $class::find()->id($id)->one();
175
        if (empty($user) || !($user instanceof User)) {
176
            throw new BadRequestHttpException(Yii::t('user', 'User Not Found.'));
177
        }
178
        return $user;
179
    }
180
181
    /**
182
     * Deregister User.
183
     * @param string $id User ID.
184
     * @return string
185
     */
186
    public function actionDeregister($id)
187
    {
188
        $id = (int)$id;
189
        if (Yii::$app->user->identity->getID() == $id) {
190
            throw new ForbiddenHttpException(Yii::t('user', 'You cannot deregister yourself.'));
191
        }
192
        $user = $this->getUser($id);
193
        try {
194
            $result = $user->deregister();
195
            if ($result instanceof \Exception) {
196
                throw $result;
197
            }
198
        } catch (\Exception $ex) {
199
            throw new ServerErrorHttpException($ex->getMessage());
200
        }
201
        if ($result !== true) {
202
            throw new ServerErrorHttpException(Yii::t('user', 'Failed to deregister user.'));
203
        }
204
        Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
205
        Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->deregisterSuccessMessage);
206
        return $this->redirect(['index']);
207
    }
208
209
    public function actionView($id)
210
    {
211
        $user = $this->getUser($id);
212
        return $this->render('view', ['user' => $user]);
213
    }
214
215
    public function actionUpdate($id)
216
    {
217
        $user = $this->getUser($id);
218
        $model = $user->profile;
219
        if (empty($model)) {
220
            $model = $user->createProfile();
221
        }
222
        $model->scenario = Profile::SCENARIO_UPDATE;
223
        if ($model->load(Yii::$app->request->post())) {
224
            if ($model->getGUID() != $user->getGUID()) {
225
                throw new BadRequestHttpException(Yii::t('user', 'Please do not forge parameters.'));
226
            }
227
            if ($model->save()) {
228
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
229
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateSuccessMessage);
230
                return $this->redirect(['update', 'id' => $id]);
231
            }
232
            Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
233
            Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateFailedMessage);
234
        }
235
        return $this->render('update', ['user' => $user, 'model' => $model]);
236
    }
237
238
    public function actionChangePassword($id)
239
    {
240
        $user = $this->getUser($id);
241
        $model = new ChangePasswordForm(['user' => $user, 'scenario' => ChangePasswordForm::SCENARIO_ADMIN]);
242
        if ($model->load(Yii::$app->request->post())){
243
            if ($model->changePassword()) {
244
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_SUCCESS);
245
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateSuccessMessage);
246
                return $this->redirect(['index', 'id' => $id]);
247
            } else {
248
                Yii::$app->session->setFlash(self::SESSION_KEY_RESULT, self::RESULT_FAILED);
249
                Yii::$app->session->setFlash(self::SESSION_KEY_MESSAGE, '(' . $user->getID() . ') ' . $this->updateFailedMessage);
250
            }
251
        }
252
        return $this->render('change-password', ['model' => $model]);
253
    }
254
}
255