ProfileController::edit()   F
last analyzed

Complexity

Conditions 91
Paths > 20000

Size

Total Lines 169
Code Lines 119

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 119
c 0
b 0
f 0
dl 0
loc 169
rs 0
cc 91
nc 1572884
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Jobs\SendAccountDeletedEmail;
6
use App\Models\ReleaseComment;
7
use App\Models\User;
8
use App\Models\UserDownload;
9
use App\Models\UserRequest;
10
use Illuminate\Contracts\View\Factory;
11
use Illuminate\Contracts\View\View;
12
use Illuminate\Foundation\Application;
13
use Illuminate\Http\RedirectResponse;
14
use Illuminate\Http\Request;
15
use Illuminate\Support\Arr;
16
use Illuminate\Support\Facades\Auth;
17
use Illuminate\Support\Facades\Validator;
18
use Jrean\UserVerification\Facades\UserVerification;
19
20
class ProfileController extends BasePageController
21
{
22
    /**
23
     * @throws \Throwable
24
     */
25
    public function show(Request $request): void
26
    {
27
        $this->setPreferences();
28
29
        $userID = $this->userdata->id;
30
        $privileged = $this->userdata->hasRole('Admin') || $this->userdata->hasRole('Moderator');
31
        $privateProfiles = config('nntmux_settings.private_profiles');
32
        $publicView = false;
33
34
        if ($privileged || ! $privateProfiles) {
35
            $altID = ($request->has('id') && (int) $request->input('id') >= 0) ? (int) $request->input('id') : false;
36
            $altUsername = ($request->has('name') && $request->input('name') !== '') ? $request->input('name') : false;
37
38
            // If both 'id' and 'name' are specified, 'id' should take precedence.
39
            if ($altID === false && $altUsername !== false) {
40
                $user = User::getByUsername($altUsername);
41
                if ($user) {
42
                    $this->userdata = $user;
43
                    $altID = $user['id'];
44
                    $userID = $altID;
45
                }
46
            } elseif ($altID !== false) {
47
                $user = User::find($altID);
48
                if ($user) {
49
                    $this->userdata = $user;
50
                    $userID = $altID;
51
                    $publicView = true;
52
                }
53
            }
54
        }
55
56
        $downloadList = UserDownload::getDownloadRequestsForUser($userID);
57
        $this->smarty->assign('downloadlist', $downloadList);
58
59
        if ($this->userdata === null) {
60
            $this->show404('No such user!');
61
        }
62
63
        // Check if the user selected a theme.
64
        if (! isset($this->userdata->style) || $this->userdata->style === 'None') {
65
            $this->userdata->style = 'Using the admin selected theme.';
66
        }
67
        $this->smarty->assign(
68
            [
69
                'apirequests' => UserRequest::getApiRequests($userID),
70
                'grabstoday' => UserDownload::getDownloadRequests($userID),
71
                'userinvitedby' => $this->userdata->invitedby !== '' ? User::find($this->userdata->invitedby) : '',
0 ignored issues
show
introduced by
The condition $this->userdata->invitedby !== '' is always true.
Loading history...
72
                'user' => $this->userdata,
73
                'privateprofiles' => $privateProfiles,
74
                'publicview' => $publicView,
75
                'privileged' => $privileged,
76
            ]
77
        );
78
79
        // Pager must be fetched after the variables are assigned to smarty.
80
        $this->smarty->assign(
81
            [
82
                'commentslist' => ReleaseComment::getCommentsForUserRange($userID),
83
            ]
84
        );
85
86
        $meta_title = 'View User Profile';
87
        $meta_keywords = 'view,profile,user,details';
88
        $meta_description = 'View User Profile for '.$this->userdata->username;
89
90
        $content = $this->smarty->fetch('profile.tpl');
91
92
        $this->smarty->assign(
93
            [
94
                'content' => $content,
95
                'meta_title' => $meta_title,
96
                'meta_keywords' => $meta_keywords,
97
                'meta_description' => $meta_description,
98
            ]
99
        );
100
        $this->pagerender();
101
    }
102
103
    /**
104
     * @return RedirectResponse|void
105
     *
106
     * @throws \Exception
107
     */
108
    public function edit(Request $request)
109
    {
110
        $this->setPreferences();
111
112
        $action = $request->input('action') ?? 'view';
113
114
        $userid = $this->userdata->id;
115
        if (! $this->userdata) {
116
            $this->show404('No such user!');
117
        }
118
119
        $errorStr = '';
120
        $success_2fa = $request->session()->get('success');
121
        $error_2fa = $request->session()->get('error');
122
123
        // Generate 2FA QR code URL if 2FA is set up but not enabled
124
        $google2fa_url = '';
125
        if ($this->userdata->passwordSecurity()->exists() && ! $this->userdata->passwordSecurity->google2fa_enable) {
0 ignored issues
show
Bug introduced by
The property google2fa_enable does not seem to exist on App\Models\PasswordSecurity. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
126
            $google2fa_url = \Google2FA::getQRCodeInline(
0 ignored issues
show
Bug introduced by
The type Google2FA was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
127
                config('app.name'),
128
                $this->userdata->email,
129
                $this->userdata->passwordSecurity->google2fa_secret
0 ignored issues
show
Bug introduced by
The property google2fa_secret does not seem to exist on App\Models\PasswordSecurity. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
130
            );
131
        }
132
133
        switch ($action) {
134
            case 'newapikey':
135
                User::updateRssKey($userid);
136
137
                return redirect()->to('profile');
138
            case 'clearcookies':
139
                return redirect()->to('profileedit');
140
            case 'submit':
141
                $validator = Validator::make($request->all(), [
142
                    'email' => ['nullable', 'string', 'email', 'max:255', 'unique:users', 'indisposable'],
143
                    'password' => ['nullable', 'string', 'min:8', 'confirmed', 'regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/'],
144
                ]);
145
146
                if ($validator->fails()) {
147
                    $errorStr = implode('', Arr::collapse($validator->errors()->toArray()));
148
                } else {
149
                    User::updateUser(
150
                        $userid,
151
                        $this->userdata->username,
152
                        $request->input('email'),
153
                        $this->userdata->grabs,
154
                        $this->userdata->roles_id,
155
                        $this->userdata->notes,
156
                        $this->userdata->invites,
157
                        $request->has('movieview') ? 1 : 0,
158
                        $request->has('musicview') ? 1 : 0,
159
                        $request->has('gameview') ? 1 : 0,
160
                        $request->has('xxxview') ? 1 : 0,
161
                        $request->has('consoleview') ? 1 : 0,
162
                        $request->has('bookview') ? 1 : 0,
163
                        'None',
164
                    );
165
166
                    if ((int) $request->input('viewconsole') === 1 && $this->userdata->can('view console') && ! $this->userdata->hasDirectPermission('view console')) {
167
                        $this->userdata->givePermissionTo('view console');
168
                    } elseif ((int) $request->input('viewconsole') === 0 && $this->userdata->can('view console') && $this->userdata->hasDirectPermission('view console')) {
169
                        $this->userdata->revokePermissionTo('view console');
170
                    } elseif ($this->userdata->cant('view console') && \in_array((int) $request->input('viewconsole'), [0, 1], true)) {
171
                        $this->userdata->revokePermissionTo('view console');
172
                    }
173
174
                    if ((int) $request->input('viewmovies') === 1 && $this->userdata->can('view movies') && ! $this->userdata->hasDirectPermission('view movies')) {
175
                        $this->userdata->givePermissionTo('view movies');
176
                    } elseif ((int) $request->input('viewmovies') === 0 && $this->userdata->can('view movies') && $this->userdata->hasDirectPermission('view movies')) {
177
                        $this->userdata->revokePermissionTo('view movies');
178
                    } elseif ($this->userdata->cant('view movies') && $this->userdata->hasDirectPermission('view movies') && \in_array((int) $request->input('viewmovies'), [0, 1], true)) {
179
                        $this->userdata->revokePermissionTo('view movies');
180
                    }
181
182
                    if ((int) $request->input('viewaudio') === 1 && $this->userdata->can('view audio') && ! $this->userdata->hasDirectPermission('view audio')) {
183
                        $this->userdata->givePermissionTo('view audio');
184
                    } elseif ((int) $request->input('viewaudio') === 0 && $this->userdata->can('view audio') && $this->userdata->hasDirectPermission('view audio')) {
185
                        $this->userdata->revokePermissionTo('view audio');
186
                    } elseif ($this->userdata->cant('view audio') && $this->userdata->hasDirectPermission('view audio') && \in_array((int) $request->input('viewaudio'), [0, 1], true)) {
187
                        $this->userdata->revokePermissionTo('view audio');
188
                    }
189
190
                    if ((int) $request->input('viewpc') === 1 && $this->userdata->can('view pc') && ! $this->userdata->hasDirectPermission('view pc')) {
191
                        $this->userdata->givePermissionTo('view pc');
192
                    } elseif ((int) $request->input('viewpc') === 0 && $this->userdata->can('view pc') && $this->userdata->hasDirectPermission('view pc')) {
193
                        $this->userdata->revokePermissionTo('view pc');
194
                    } elseif ($this->userdata->cant('view pc') && $this->userdata->hasDirectPermission('view pc') && \in_array((int) $request->input('viewpc'), [0, 1], true)) {
195
                        $this->userdata->revokePermissionTo('view pc');
196
                    }
197
198
                    if ((int) $request->input('viewtv') === 1 && $this->userdata->can('view tv') && ! $this->userdata->hasDirectPermission('view tv')) {
199
                        $this->userdata->givePermissionTo('view tv');
200
                    } elseif ((int) $request->input('viewtv') === 0 && $this->userdata->can('view tv') && $this->userdata->hasDirectPermission('view tv')) {
201
                        $this->userdata->revokePermissionTo('view tv');
202
                    } elseif ($this->userdata->cant('view tv') && $this->userdata->hasDirectPermission('view tv') && \in_array((int) $request->input('viewtv'), [0, 1], true)) {
203
                        $this->userdata->revokePermissionTo('view tv');
204
                    }
205
206
                    if ((int) $request->input('viewadult') === 1 && $this->userdata->can('view adult') && ! $this->userdata->hasDirectPermission('view adult')) {
207
                        $this->userdata->givePermissionTo('view adult');
208
                    } elseif ((int) $request->input('viewadult') === 0 && $this->userdata->can('view adult') && $this->userdata->hasDirectPermission('view adult')) {
209
                        $this->userdata->revokePermissionTo('view adult');
210
                    } elseif ($this->userdata->cant('view adult') && $this->userdata->hasDirectPermission('view adult') && \in_array((int) $request->input('viewadult'), [0, 1], true)) {
211
                        $this->userdata->revokePermissionTo('view adult');
212
                    }
213
214
                    if ((int) $request->input('viewbooks') === 1 && $this->userdata->can('view books') && ! $this->userdata->hasDirectPermission('view books')) {
215
                        $this->userdata->givePermissionTo('view books');
216
                    } elseif ((int) $request->input('viewbooks') === 0 && $this->userdata->can('view books') && $this->userdata->hasDirectPermission('view books')) {
217
                        $this->userdata->revokePermissionTo('view books');
218
                    } elseif ($this->userdata->cant('view books') && $this->userdata->hasDirectPermission('view books') && \in_array((int) $request->input('viewbooks'), [0, 1], true)) {
219
                        $this->userdata->revokePermissionTo('view books');
220
                    }
221
222
                    if ((int) $request->input('viewother') === 1 && $this->userdata->can('view other') && ! $this->userdata->hasDirectPermission('view other')) {
223
                        $this->userdata->givePermissionTo('view other');
224
                    } elseif ((int) $request->input('viewother') === 0 && $this->userdata->can('view other') && $this->userdata->hasDirectPermission('view other')) {
225
                        $this->userdata->revokePermissionTo('view other');
226
                    } elseif ($this->userdata->cant('view other') && $this->userdata->hasDirectPermission('view other') && \in_array((int) $request->input('viewother'), [0, 1], true)) {
227
                        $this->userdata->revokePermissionTo('view other');
228
                    }
229
230
                    if ($request->has('password') && ! empty($request->input('password'))) {
231
                        User::updatePassword($userid, $request->input('password'));
232
                    }
233
234
                    if (! $this->userdata->hasRole('Admin')) {
235
                        if (! empty($request->input('email')) && $this->userdata->email !== $request->input('email')) {
236
                            $this->userdata->email = $request->input('email');
237
238
                            $verify_user = $this->userdata;
239
240
                            UserVerification::generate($verify_user);
241
242
                            UserVerification::send($verify_user, 'User email verification required');
243
244
                            Auth::logout();
245
246
                            return redirect()->to('login')->with('info', 'You will be able to login after you verify your new email address');
247
                        }
248
                    }
249
250
                    return redirect()->to('profile')->with('success', 'Profile changes saved');
251
                }
252
                break;
253
254
            case 'view':
255
            default:
256
                break;
257
        }
258
259
        $this->smarty->assign('error', $errorStr);
260
        $this->smarty->assign('user', $this->userdata);
261
        $this->smarty->assign('userexccat', User::getCategoryExclusionById($userid));
262
        $this->smarty->assign('success_2fa', $success_2fa);
263
        $this->smarty->assign('error_2fa', $error_2fa);
264
        $this->smarty->assign('google2fa_url', $google2fa_url);
265
266
        $meta_title = 'Edit User Profile';
267
        $meta_keywords = 'edit,profile,user,details';
268
        $meta_description = 'Edit User Profile for '.$this->userdata->username;
269
270
        $this->smarty->assign('yesno_ids', [1, 0]);
271
        $this->smarty->assign('yesno_names', ['Yes', 'No']);
272
273
        $content = $this->smarty->fetch('profileedit.tpl');
274
275
        $this->smarty->assign(compact('content', 'meta_title', 'meta_keywords', 'meta_description'));
276
        $this->pagerender();
277
    }
278
279
    /**
280
     * @throws \Exception
281
     */
282
    public function destroy(Request $request): Application|View|Factory|RedirectResponse|\Illuminate\Contracts\Foundation\Application
283
    {
284
        $this->setPreferences();
285
        $userId = $request->input('id');
286
287
        if ($userId !== null && (int) $userId === $this->userdata->id && ! $this->userdata->hasRole('Admin')) {
288
            $user = User::find($userId);
289
            SendAccountDeletedEmail::dispatch($user);
290
            Auth::logout();
291
            $user->delete();
292
        }
293
294
        if ($this->userdata->hasRole('Admin')) {
295
            return redirect()->to('profile');
296
        }
297
298
        return view('errors.503')->with('warning', 'Dont try to delete another user account!');
299
    }
300
}
301