Completed
Push — master ( 91f535...9228e9 )
by vistart
03:37
created

UserController::initMessages()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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