AdminUserController::resendVerification()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use App\Http\Controllers\BasePageController;
6
use App\Models\Invitation;
7
use App\Models\User;
8
use App\Models\UserDownload;
9
use App\Models\UserRequest;
10
use Illuminate\Http\RedirectResponse;
11
use Illuminate\Http\Request;
12
use Jrean\UserVerification\Facades\UserVerification;
13
use Spatie\Permission\Models\Role;
14
15
class AdminUserController extends BasePageController
16
{
17
    /**
18
     * @throws \Throwable
19
     */
20
    public function index(Request $request)
21
    {
22
        $this->setAdminPrefs();
23
24
        $meta_title = $title = 'User List';
25
26
        $roles = [];
27
        $userRoles = Role::cursor()->remember();
28
        foreach ($userRoles as $userRole) {
29
            $roles[$userRole->id] = $userRole->name;
30
        }
31
32
        $ordering = getUserBrowseOrdering();
33
        $orderBy = $request->has('ob') && \in_array($request->input('ob'), $ordering, false) ? $request->input('ob') : '';
34
        $page = $request->has('page') && is_numeric($request->input('page')) ? $request->input('page') : 1;
35
        $offset = ($page - 1) * config('nntmux.items_per_page');
36
37
        $variables = [
38
            'username' => $request->has('username') ? $request->input('username') : '',
39
            'email' => $request->has('email') ? $request->input('email') : '',
40
            'host' => $request->has('host') ? $request->input('host') : '',
41
            'role' => $request->has('role') ? $request->input('role') : '',
42
            'created_from' => $request->has('created_from') ? $request->input('created_from') : '',
43
            'created_to' => $request->has('created_to') ? $request->input('created_to') : '',
44
        ];
45
46
        $result = User::getRange(
47
            $offset,
48
            config('nntmux.items_per_page'),
49
            $orderBy,
50
            $variables['username'],
51
            $variables['email'],
52
            $variables['host'],
53
            $variables['role'],
54
            true,
55
            $variables['created_from'],
56
            $variables['created_to']
57
        );
58
59
        $results = $this->paginate($result ?? [], User::getCount($variables['role'], $variables['username'], $variables['host'], $variables['email'], $variables['created_from'], $variables['created_to']) ?? 0, config('nntmux.items_per_page'), $page, $request->url(), $request->query());
60
61
        // Note: API request counts are already included via the getRange query when $apiRequests = true
62
        // Country lookups and additional counts removed to improve performance on large datasets
63
        // These can be added back via individual user profile pages or AJAX calls if needed
64
65
        // Build order by URLs
66
        $orderByUrls = [];
67
        foreach ($ordering as $orderType) {
68
            $orderByUrls['orderby'.$orderType] = url('admin/user-list?ob='.$orderType);
69
        }
70
71
        $this->viewData = array_merge($this->viewData, [
72
            'username' => $variables['username'],
73
            'email' => $variables['email'],
74
            'host' => $variables['host'],
75
            'role' => $variables['role'],
76
            'created_from' => $variables['created_from'],
77
            'created_to' => $variables['created_to'],
78
            'role_ids' => array_keys($roles),
79
            'role_names' => $roles,
80
            'userlist' => $results,
81
            'title' => $title,
82
            'meta_title' => $meta_title,
83
        ], $orderByUrls);
84
85
        return view('admin.users.index', $this->viewData);
86
    }
87
88
    /**
89
     * @return RedirectResponse|\Illuminate\View\View
90
     *
91
     * @throws \Exception|\Throwable
92
     */
93
    public function edit(Request $request)
94
    {
95
        $this->setAdminPrefs();
96
97
        $user = [
98
            'id' => '',
99
            'username' => '',
100
            'email' => '',
101
            'password' => '',
102
            'role' => User::ROLE_USER,
103
            'notes' => '',
104
            'rate_limit' => 60,
105
        ];
106
107
        $meta_title = $title = 'View User';
108
109
        // set the current action
110
        $action = $request->input('action') ?? 'view';
111
112
        // get the user roles
113
        $userRoles = Role::cursor()->remember();
114
        $roles = [];
115
        $defaultRole = 'User';
116
        $defaultInvites = Invitation::DEFAULT_INVITES;
117
        foreach ($userRoles as $r) {
118
            $roles[$r->id] = $r->name;
119
            if ($r->isdefault === 1) {
120
                $defaultRole = $r->id;
121
                $defaultInvites = $r->defaultinvites;
122
            }
123
        }
124
125
        $error = null;
126
127
        switch ($action) {
128
            case 'add':
129
                $user += [
130
                    'role' => $defaultRole,
131
                    'notes' => '',
132
                    'invites' => $defaultInvites,
133
                    'movieview' => 0,
134
                    'xxxview' => 0,
135
                    'musicview' => 0,
136
                    'consoleview' => 0,
137
                    'gameview' => 0,
138
                    'bookview' => 0,
139
                ];
140
                break;
141
            case 'submit':
142
                if (empty($request->input('id'))) {
143
                    $invites = $defaultInvites;
144
                    foreach ($userRoles as $role) {
145
                        if ($role['id'] === $request->input('role')) {
146
                            $invites = $role['defaultinvites'];
147
                        }
148
                    }
149
                    $ret = User::signUp($request->input('username'), $request->input('password'), $request->input('email'), '', $request->input('notes'), $invites, '', true, $request->input('role'), false);
150
                } else {
151
                    $editedUser = User::find($request->input('id'));
152
153
                    // Check if role is changing and get stack preference
154
                    $roleChanged = $editedUser->roles_id != $request->input('role');
155
                    $stackRole = $request->input('stack_role') ? true : false; // Check if checkbox is checked
156
                    $changedBy = auth()->check() ? auth()->id() : null;
157
158
                    // CRITICAL: Capture the ORIGINAL rolechangedate BEFORE any updates
159
                    // This is needed for accurate role history tracking
160
                    // Convert to string to avoid any Carbon object reference issues
161
                    $originalRoleChangeDate = $editedUser->rolechangedate
162
                        ? $editedUser->rolechangedate->toDateTimeString()
163
                        : null;
164
165
                    \Log::info('AdminUserController - Before updates', [
166
                        'user_id' => $editedUser->id,
167
                        'originalRoleChangeDate' => $originalRoleChangeDate,
168
                        'current_roles_id' => $editedUser->roles_id,
169
                        'requested_role' => $request->input('role'),
170
                        'roleChanged' => $roleChanged,
171
                        'stackRole' => $stackRole,
172
                        'form_rolechangedate' => $request->input('rolechangedate'),
173
                    ]);
174
175
                    // Handle pending role cancellation
176
                    if ($request->has('cancel_pending_role') && $request->input('cancel_pending_role')) {
177
                        $editedUser->cancelPendingRole();
178
                    }
179
180
                    // Handle rolechangedate - Update the expiry for the CURRENT role FIRST
181
                    // This must happen BEFORE role change so the new expiry applies to the old role
182
                    $adminManuallySetExpiry = false;
183
                    if ($request->has('rolechangedate')) {
184
                        $roleChangeDate = $request->input('rolechangedate');
185
                        if (! empty($roleChangeDate)) {
186
                            User::updateUserRoleChangeDate($editedUser->id, $roleChangeDate);
187
                            $adminManuallySetExpiry = true; // Flag that admin set custom expiry
188
                        } else {
189
                            // Clear the rolechangedate if empty string is provided
190
                            $editedUser->update(['rolechangedate' => null]);
191
                        }
192
                        $editedUser->refresh();
193
194
                        \Log::info('AdminUserController - After expiry update', [
195
                            'user_id' => $editedUser->id,
196
                            'new_rolechangedate' => $editedUser->rolechangedate,
197
                            'adminManuallySetExpiry' => $adminManuallySetExpiry,
198
                        ]);
199
                    }
200
201
                    // If role is changing, handle it with stacking logic
202
                    // Pass the original expiry so history records the correct old_expiry_date
203
                    if ($roleChanged && $request->input('role') !== null) {
204
                        \Log::info('AdminUserController - About to call updateUserRole', [
205
                            'user_id' => $editedUser->id,
206
                            'new_role' => (int) $request->input('role'),
207
                            'originalRoleChangeDate_passed' => $originalRoleChangeDate,
208
                            'current_user_rolechangedate' => $editedUser->rolechangedate,
209
                        ]);
210
211
                        User::updateUserRole(
212
                            $editedUser->id,
213
                            (int) $request->input('role'), // Cast to integer
214
                            ! $adminManuallySetExpiry, // Only apply promotions if admin didn't set custom expiry
215
                            $stackRole, // Stack role if requested
216
                            $changedBy,
217
                            $originalRoleChangeDate, // Pass original expiry for history
218
                            $adminManuallySetExpiry // Preserve admin's manually set expiry date
219
                        );
220
                        $editedUser->refresh();
221
                    }
222
                    // Note: We don't call updateUserRole when role hasn't changed
223
                    // If admin manually set a rolechangedate, that's already applied above
224
225
                    // Update user basic information (but NOT the role - it's handled above)
226
                    // Use current role to avoid overwriting
227
                    $ret = User::updateUser(
228
                        $editedUser->id,
229
                        $request->input('username'),
230
                        $request->input('email'),
231
                        $editedUser->grabs,
232
                        $editedUser->roles_id, // Use current role, not the request role
233
                        $request->input('notes'),
234
                        $request->input('invites'),
235
                        ($request->has('movieview') ? 1 : 0),
236
                        ($request->has('musicview') ? 1 : 0),
237
                        ($request->has('gameview') ? 1 : 0),
238
                        ($request->has('xxxview') ? 1 : 0),
239
                        ($request->has('consoleview') ? 1 : 0),
240
                        ($request->has('bookview') ? 1 : 0)
241
                    );
242
243
                    if ($request->input('password') !== null) {
244
                        User::updatePassword($editedUser->id, $request->input('password'));
245
                    }
246
                }
247
248
                if ($ret >= 0) {
249
                    return redirect()->to('admin/user-list');
250
                }
251
252
                $error = match ($ret) {
253
                    User::ERR_SIGNUP_BADUNAME => 'Bad username. Try a better one.',
254
                    User::ERR_SIGNUP_BADPASS => 'Bad password. Try a longer one.',
255
                    User::ERR_SIGNUP_BADEMAIL => 'Bad email.',
256
                    User::ERR_SIGNUP_UNAMEINUSE => 'Username in use.',
257
                    User::ERR_SIGNUP_EMAILINUSE => 'Email in use.',
258
                    default => 'Unknown save error.',
259
                };
260
                $user += [
261
                    'id' => $request->input('id'),
262
                    'username' => $request->input('username'),
263
                    'email' => $request->input('email'),
264
                    'role' => $request->input('role'),
265
                    'notes' => $request->input('notes'),
266
                ];
267
                break;
268
            case 'view':
269
            default:
270
                if ($request->has('id')) {
271
                    $title = 'User Edit';
272
                    $id = $request->input('id');
273
                    $user = User::find($id);
274
275
                    // Add daily API and download counts
276
                    if ($user) {
277
                        try {
278
                            $user->daily_api_count = UserRequest::getApiRequests($user->id);
279
                            $user->daily_download_count = UserDownload::getDownloadRequests($user->id);
280
                        } catch (\Exception $e) {
281
                            $user->daily_api_count = 0;
282
                            $user->daily_download_count = 0;
283
                        }
284
                    }
285
                }
286
287
                break;
288
        }
289
290
        $this->viewData = array_merge($this->viewData, [
291
            'yesno_ids' => [1, 0],
292
            'yesno_names' => ['Yes', 'No'],
293
            'role_ids' => array_keys($roles),
294
            'role_names' => $roles,
295
            'user' => $user,
296
            'error' => $error,
297
            'title' => $title,
298
            'meta_title' => $meta_title,
299
        ]);
300
301
        return view('admin.users.edit', $this->viewData);
302
    }
303
304
    public function destroy(Request $request): RedirectResponse
305
    {
306
        if ($request->has('id')) {
307
            $user = User::find($request->input('id'));
308
            $username = $user->username; // Store username before deletion
309
310
            $user->delete();
311
312
            // Redirect with username to display in notification
313
            return redirect()->to('admin/user-list?deleted=1&username='.urlencode($username));
314
        }
315
316
        if ($request->has('redir')) {
317
            return redirect()->to($request->input('redir'));
318
        }
319
320
        return redirect()->to($request->server('HTTP_REFERER'));
0 ignored issues
show
Bug introduced by
It seems like $request->server('HTTP_REFERER') can also be of type array; however, parameter $path of Illuminate\Routing\Redirector::to() does only seem to accept string, 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

320
        return redirect()->to(/** @scrutinizer ignore-type */ $request->server('HTTP_REFERER'));
Loading history...
321
    }
322
323
    public function resendVerification(Request $request): RedirectResponse
324
    {
325
        if ($request->has('id')) {
326
            $user = User::find($request->input('id'));
327
            UserVerification::generate($user);
328
329
            UserVerification::send($user, 'User email verification required');
330
331
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
332
        }
333
334
        return redirect()->back()->with('error', 'User is invalid');
335
    }
336
337
    public function verify(Request $request): RedirectResponse
338
    {
339
        if ($request->has('id')) {
340
            $user = User::find($request->input('id'));
341
            User::query()->where('id', $request->input('id'))->update(['verified' => 1, 'email_verified_at' => now()]);
342
343
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
344
        }
345
346
        return redirect()->back()->with('error', 'User is invalid');
347
    }
348
}
349