Passed
Push — master ( 271103...91f535 )
by vistart
03:46
created

UserController::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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