Passed
Push — Auth ( 0585e4...0626eb )
by Stone
02:59
created

Home::deleteUser()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 16
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Admin;
4
5
6
use App\Models\RoleModel;
7
use App\Models\UserModel;
8
use Core\Constant;
9
use Core\Container;
10
use Core\Traits\PasswordFunctions;
11
use Core\Traits\StringFunctions;
12
13
class Home extends \Core\AdminController
14
{
15
    use StringFunctions;
0 ignored issues
show
Bug introduced by
The trait Core\Traits\StringFunctions requires the property $childNodes which is not provided by App\Controllers\Admin\Home.
Loading history...
16
    use PasswordFunctions;
17
    protected $siteConfig;
18
    protected $pagination;
19
20
    private $userModel;
21
    private $roleModel;
22
23
    public function __construct(Container $container)
24
    {
25
        $this->loadModules[] = 'SiteConfig';
26
        $this->loadModules[] = 'pagination';
27
        parent::__construct($container);
28
        $this->userModel = new UserModel($this->container);
29
        $this->roleModel = new RoleModel($this->container);
30
31
        $this->data['configs'] = $this->siteConfig->getSiteConfig();
32
    }
33
34
    /**
35
     * The front page of the admin section. We display the user info
36
     * @throws \ReflectionException
37
     * @throws \Twig_Error_Loader
38
     * @throws \Twig_Error_Runtime
39
     * @throws \Twig_Error_Syntax
40
     */
41
    public function index()
42
    {
43
        $this->onlyUser();
44
45
        //check if have prefilled form data and error mesages
46
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
47
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
48
49
        //remove the set data as it is now sent to the template
50
        $this->session->remove("registrationInfo");
51
        $this->session->remove("registrationErrors");
52
53
        $userId = $this->session->get("userId");
54
        $this->data["user"] = $this->userModel->getUserDetailsById($userId);
0 ignored issues
show
Bug introduced by
It seems like $userId can also be of type null; however, parameter $userId of App\Models\UserModel::getUserDetailsById() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

54
        $this->data["user"] = $this->userModel->getUserDetailsById(/** @scrutinizer ignore-type */ $userId);
Loading history...
55
56
        $this->data["roles"] = $this->roleModel->getRoleList();
57
58
        $this->renderView('Admin/Home');
59
    }
60
61
    /**
62
     * Administrate a user as an admin
63
     * @param int $userId
64
     * @throws \ReflectionException
65
     * @throws \Twig_Error_Loader
66
     * @throws \Twig_Error_Runtime
67
     * @throws \Twig_Error_Syntax
68
     */
69
    public function viewUser(int $userId)
70
    {
71
        $this->onlyAdmin();
72
        if (!$this->isInt($userId)) {
73
            throw new \Exception("Error in passed ID");
74
        }
75
76
        //check if have prefilled form data and error mesages
77
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
78
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
79
80
        //remove the set data as it is now sent to the template
81
        $this->session->remove("registrationInfo");
82
        $this->session->remove("registrationErrors");
83
84
        $this->data["user"] = $this->userModel->getUserDetailsById($userId);
85
86
        $this->data["roles"] = $this->roleModel->getRoleList();
87
88
        $this->renderView('Admin/Home');
89
    }
90
91
    /**
92
     * Update the user info via post
93
     */
94
    public function updateUser()
95
    {
96
        $this->onlyUser();
97
        $this->onlyPost();
98
99
        $user = (object)$this->request->getDataFull();
100
        $redirectUrl = "/admin";
101
102
        if ($user->userId !== $this->session->get("userId") || isset($user->userRoleSelector) || isset($user->locked_out)) {
103
            //an admin is trying to update a user or form tampered with
104
            $this->onlyAdmin();
105
            $redirectUrl = "/admin/home/view-user/" . $user->userId;
106
        } else {
107
            //set the role to the original state for update
108
            $beforeUser = $this->userModel->getUserDetailsById($user->userId);
109
            $user->userRoleSelector = $beforeUser->roles_idroles;
110
            $user->userLockedOut = $beforeUser->locked_out;
111
        }
112
113
        $userId = $user->userId;
114
        $password = $user->forgotPassword ?? "";
115
        $confirm = $user->forgotConfirm ?? "";
116
        $resetPassword = false;
117
        $error = false;
118
        $registerErrors = new \stdClass();
119
120
        if($userId == 1 && $user->userLockedOut == 1)
121
        {
122
            $error = true;
123
            $this->alertBox->setAlert("Original admin may not be deactivated", "error");
124
        }
125
126
        if($userId == 1 && $user->userRoleSelector != 2)
127
        {
128
            $error = true;
129
            $this->alertBox->setAlert("Original admin must stay admin", "error");
130
        }
131
132
        if ($password !== "" || $confirm !== "") {
133
            //we are resetting the password
134
            $resetPassword = true;
135
            if ($password !== $confirm) {
136
                $error = true;
137
                $registerErrors->forgotPassword = "password and confirmation do not match";
138
                $registerErrors->forgotConfirm = "password and confirmation do not match";
139
            }
140
141
            $passwordError = $this->isPasswordComplex($password);
142
            if (!$passwordError["success"]) {
143
                $error = true;
144
                $registerErrors->forgotPassword = $passwordError["message"];
145
            }
146
        }
147
148
        if ($user->userName == "") {
149
            $error = true;
150
            $registerErrors->userName = "name must not be empty";
151
        }
152
        if ($user->userSurname == "") {
153
            $error = true;
154
            $registerErrors->userSurname = "surname must not be empty";
155
        }
156
        if ($user->userUsername == "") {
157
            $error = true;
158
            $registerErrors->userUsername = "username must not be empty";
159
        }
160
161
        if ($error) {
162
            $this->session->set("registrationErrors", $registerErrors);
163
            $this->response->redirect($redirectUrl);
164
        }
165
166
        if ($resetPassword) {
167
            $this->userModel->resetPassword($userId, $password);
168
        }
169
170
        $this->userModel->updateUser($user);
171
172
        $this->alertBox->setAlert('User details updated');
173
        $this->response->redirect($redirectUrl);
174
    }
175
176
    /**
177
     * List all the users
178
     */
179
    public function listUsers(string $page = "page-1", int $linesPerPage = Constant::LIST_PER_PAGE)
180
    {
181
        $this->onlyAdmin();
182
183
        $totalUsers = $this->userModel->countUsers();
184
        $pagination = $this->pagination->getPagination($page, $totalUsers, $linesPerPage);
185
186
        if ($linesPerPage !== Constant::LIST_PER_PAGE) {
187
            $this->data['paginationPostsPerPage'] = $linesPerPage;
188
        }
189
190
        $this->data["posts"] = $this->userModel->getUserList($pagination["offset"], $linesPerPage);
191
        $this->data['pagination'] = $pagination;
192
        $this->renderView("Admin/ListUser");
193
    }
194
195
    /**
196
     * permanantly delete a user
197
     * @param int $userId
198
     * @throws \Exception
199
     */
200
    public function deleteUser(int $userId)
201
    {
202
        $this->onlyAdmin();
203
        if (!$this->isInt($userId)) {
204
            throw new \Exception("Error in passed ID");
205
        }
206
207
        if($userId === 1)
208
        {
209
            $this->alertBox->setAlert('Original Admin can not be deleted', "error");
210
            $this->response->redirect("/admin/home/list-users");
211
        }
212
213
        $this->userModel->deleteUser($userId);
214
        $this->alertBox->setAlert('User deleted');
215
        $this->response->redirect("/admin/home/list-users");
216
    }
217
}