Passed
Push — dev5 ( ba7c22...e927b9 )
by Ron
07:35
created

UserController::checkUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 2
dl 0
loc 13
ccs 0
cts 8
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use DB;
6
use Mail;
7
use App\Role;
0 ignored issues
show
Bug introduced by
The type App\Role 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...
8
use App\User;
9
use Carbon\Carbon;
10
use App\UserInitialize;
11
use Illuminate\Support\Str;
12
use App\Mail\InitializeUser;
13
use Illuminate\Http\Request;
14
use Illuminate\Validation\Rule;
15
use Illuminate\Support\Facades\Log;
16
use Illuminate\Support\Facades\Auth;
17
use App\Http\Controllers\Controller;
18
use Illuminate\Support\Facades\Route;
19
20
use App\UserRoleType;
21
22
class UserController extends Controller
23
{
24
    //  Constructor sets up middleware
25
    public function __construct()
26
    {
27
        $this->middleware('auth')->except('initializeUser', 'submitInitializeUser');
28
    }
29
30
    //  Show the list of current users to edit
31
    public function index()
32
    {
33
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
34
        return view('admin.userIndex', [
35
            'link' => 'admin.user.edit'
36
        ]);
37
    }
38
39
    //  Check if a username is in use
40
    public function checkUser($username, $type)
41
    {
42
        $user = User::where($type, $username)->first();
43
44
        if(!$user)
45
        {
46
            return response()->json(['duplicate' => false]);
47
        }
48
49
        return response()->json([
50
            'duplicate' => true,
51
            'user'      => $user->full_name,
52
            'active'    => $user->active,
53
        ]);
54
    }
55
56
    //  Show the Add User form
57
    public function create()
58
    {
59
        $roles = UserRoleType::all(); // Role::all();
60
61
        $roleArr = [];
62
        foreach($roles as $role)
63
        {
64
            if($role->role_id == 1 && Auth::user()->role_id != 1)
65
            {
66
                continue;
67
            }
68
            else if($role->role_id == 2 && Auth::user()->role_id > 1)
69
            {
70
                continue;
71
            }
72
            else
73
            {
74
                // $roleArr[$role->role_id] = $role->name;
75
                $roleArr[] = [
76
                    'value' => $role->role_id,
77
                    'text'  => $role->name,
78
                ];
79
            }
80
        }
81
82
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
83
        return view('admin.newUser', [
84
            'roles' => $roleArr
85
        ]);
86
    }
87
88
    //  Submit the Add User form
89
    public function store(Request $request)
90
    {
91
        //  Validate the new user form
92
        $request->validate([
93
            'username'   => 'required|unique:users|regex:/^[a-zA-Z0-9_]*$/',
94
            'first_name' => 'required',
95
            'last_name'  => 'required',
96
            'email'      => 'required|unique:users',
97
        ]);
98
99
        //  Create the user
100
        $newUser = User::create([
101
            'username'   => $request->username,
102
            'first_name' => $request->first_name,
103
            'last_name'  => $request->last_name,
104
            'email'      => $request->email,
105
            'password'   => bcrypt(strtolower(Str::random(15))),
106
            'active'     => 1
107
        ]);
108
109
        $userID = $newUser->user_id;
110
111
        //  Assign the users role
112
        DB::insert('INSERT INTO `user_role` (`user_id`, `role_id`) VALUES (?, ?)', [$userID, $request->role]);
113
114
        //  Create the setup user link
115
        $hash = strtolower(Str::random(30));
116
        UserInitialize::create([
117
            'username' => $request->username,
118
            'token'    => $hash
119
        ]);
120
121
        //  Email the new user
122
        Mail::to($request->email)->send(new InitializeUser($hash, $request->username, $request->first_name.' '.$request->last_name));
123
124
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
125
        Log::debug('User Data - ', $newUser->toArray());
126
        Log::notice('New User ID-'.$userID.' Created by ID-'.Auth::user()->user_id);
127
128
        return redirect()->back()->with('success', 'New User Created');
129
    }
130
131
    //  Bring up the "Finish User Setup" form
132
    public function initializeUser($hash)
133
    {
134
        $this->middleware('guest');
135
136
        //  Validate the hash token
137
        $user = UserInitialize::where('token', $hash)->get();
138
139
        if($user->isEmpty())
140
        {
141
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
142
            Log::warning('Visitor at IP Address '.\Request::ip().' tried to access invalid initialize hash - '.$hash);
143
            return abort(404);
1 ignored issue
show
Bug introduced by
Are you sure the usage of abort(404) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
144
        }
145
146
        Log::debug('Route '.Route::currentRouteName().' visited.');
147
        Log::debug('Link Hash -'.$hash);
148
        return view('account.initializeUser', ['hash' => $hash]);
149
    }
150
151
    //  Submit the initialize user form
152
    public function submitInitializeUser(Request $request, $hash)
153
    {
154
        //  Verify that the link matches the assigned email address
155
        $valid = UserInitialize::where('token', $hash)->first();
156
        if(empty($valid))
157
        {
158
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
159
            Log::warning('Visitor at IP Address '.\Request::ip().' tried to submit an invalid User Initialization link - '.$hash);
160
            return abort(404);
1 ignored issue
show
Bug introduced by
Are you sure the usage of abort(404) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
161
        }
162
163
        //  Validate the form
164
        $request->validate([
165
            'username' => [
166
                'required',
167
                Rule::in([$valid->username]),
168
            ],
169
            'newPass'  => 'required|string|min:6|confirmed'
170
        ]);
171
172
        //  Get the users information
173
        $userData = User::where('username', $valid->username)->first();
174
175
        $nextChange = config('users.passExpires') != null ? Carbon::now()->addDays(config('users.passExpires')) : null;
176
177
            //  Update the password
178
        User::find($userData->user_id)->update(
179
        [
180
            'password'         => bcrypt($request->newPass),
181
            'password_expires' => $nextChange
182
        ]);
183
184
        //  Remove the initialize instance
185
        UserInitialize::find($valid->id)->delete();
186
187
        //  Log in the user
188
        Auth::loginUsingID($userData->user_id);
189
190
        //  Redirect the user to the dashboard
191
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
192
        Log::debug('Initialize Data - '.$request->toArray());
0 ignored issues
show
Bug introduced by
Are you sure $request->toArray() of type array can be used in concatenation? ( Ignorable by Annotation )

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

192
        Log::debug('Initialize Data - './** @scrutinizer ignore-type */ $request->toArray());
Loading history...
193
        Log::notice('User has setup account', ['user_id' => $userData->user_id]);
194
        return redirect(route('dashboard'));
195
    }
196
197
    //  List all active or inactive users
198
    public function show($type)
199
    {
200
        $res = '';
201
        if($type == 'active')
202
        {
203
            $res = User::where('active', true)->with('UserLogins')->get();
204
        }
205
206
        $userList = [];
207
        foreach($res as $r)
208
        {
209
            $userList[] = [
210
                'user_id' => $r->user_id,
211
                'user'    => $r->first_name.' '.$r->last_name,
212
                'email'   => $r->email,
213
                'last'    => $r->UserLogins->last() ? date('M j, Y - g:i A', strtotime($r->UserLogins->last()->created_at)) : 'Never'
214
            ];
215
        }
216
217
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
218
        Log::debug('User List - ', $userList);
219
        return response()->json($userList);
220
    }
221
222
    //  Open the edit user form
223
    public function edit($id)
224
    {
225
        $roles    = Role::all();
226
        $userData = User::find($id);
227
        $userRole = DB::select('SELECT `role_id` FROM `user_role` WHERE `user_id` = ?', [$id])[0]->role_id;
228
229
        $roleArr = [];
230
        foreach($roles as $role)
231
        {
232
            if($role->role_id == 1 && !Auth::user()->hasAnyRole(['installer']))
233
            {
234
                continue;
235
            }
236
            else
237
            {
238
                $roleArr[$role->role_id] = $role->name;
239
            }
240
        }
241
242
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
243
        Log::debug('Edit user form opened for user ID-'.$id);
244
        return view('admin.editUser', [
245
            'userID' => $id,
246
            'roles'  => $roleArr,
247
            'role'   => $userRole,
248
            'user'   => $userData
249
        ]);
250
    }
251
252
    //  Submit the update user form
253
    public function update(Request $request, $id)
254
    {
255
        $request->validate([
256
            'username'   => [
257
                                'required',
258
                                Rule::unique('users')->ignore($id, 'user_id')
259
                            ],
260
            'first_name' => 'required',
261
            'last_name'  => 'required',
262
            'email'      => [
263
                                'required',
264
                                Rule::unique('users')->ignore($id, 'user_id')
265
                            ],
266
        ]);
267
268
        //  Update the user data
269
        User::find($id)->update(
270
        [
271
            'username'   => $request->username,
272
            'first_name' => $request->first_name,
273
            'last_name'  => $request->last_name,
274
            'email'      => $request->email
275
        ]);
276
277
        //  Update the user's role
278
        DB::update('UPDATE `user_role` SET `role_id` = ? WHERE `user_id` = ?', [$request->role, $id]);
279
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
280
        Log::debug('Edit user form submitted for User ID-'.$id.'  Data - ', $request->toArray());
281
        Log::notice('User ID-'.$id.' has updated their information.');
282
        return redirect(route('admin.user.index'))->with('success', 'User Updated Successfully');
283
    }
284
285
    //  List the active users to change the password for
286
    public function passwordList()
287
    {
288
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
289
        return view('admin.userIndex', [
290
            'link' => 'admin.changePassword'
291
        ]);
292
    }
293
294
    //  Change password form
295
    public function changePassword($id)
296
    {
297
        $name = User::find($id);
298
        $name = $name->first_name.' '.$name->last_name;
299
300
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
301
        Log::debug('Change change password form opened for User ID-'.$id);
302
        return view('admin.changePassword', [
303
            'id'   => $id,
304
            'user' => $name
305
        ]);
306
    }
307
308
    //  Submit the change password form
309
    public function submitPassword(Request $request, $id)
310
    {
311
        $request->validate([
312
            'password'   => 'required|string|min:6|confirmed'
313
        ]);
314
315
        $nextChange = isset($request->force_change) && $request->force_change == 'on' ? Carbon::now()->subDay() : null;
316
317
            //  Update the user data
318
        User::find($id)->update(
319
        [
320
            'password'         => bcrypt($request->password),
321
            'password_expires' => $nextChange
322
        ]);
323
324
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
325
        Log::debug('Password Change form submitted for user ID-'.$id.' Data - ', $request->toArray());
326
        Log::info('User ID-'.$id.' has changed their password.');
327
        return redirect(route('admin.user.index'))->with('success', 'User Password Updated Successfully');
328
    }
329
330
    //  Bring up the users that are available to deactivate
331
    public function disable()
332
    {
333
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
334
        return view('admin.userIndex', [
335
            'link' => 'admin.confirmDisable'
336
        ]);
337
    }
338
339
    //  Confirm to disable the user
340
    public function confirm($id)
341
    {
342
        $name = User::find($id);
343
        $name = $name->first_name.' '.$name->last_name;
344
345
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
346
        return view('admin.disableUser', [
347
            'id'   => $id,
348
            'name' => $name
349
        ]);
350
    }
351
352
    //  Disable the user
353
    public function destroy($id)
354
    {
355
        User::find($id)->update([
356
            'active' => 0
357
        ]);
358
359
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
360
        Log::notice('User ID-'.$id.' disabled by '.Auth::user()->user_id);
361
362
        return redirect(route('admin.user.index'))->with('success', 'User Deactivated Successfully');
363
    }
364
}
365