Completed
Push — master ( d7fe2d...0f3d1f )
by vistart
03:24
created

UserController::actionUpdate()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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