Completed
Push — master ( 008d1c...59e294 )
by vistart
03:42
created

web/admin/controllers/UserController.php (8 issues)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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