Passed
Push — dev5 ( 4b89af...8662bf )
by Ron
06:47
created

UserController::confirm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 2
rs 10
1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use DB;
6
use Mail;
7
// use App\Role;
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
use Illuminate\Support\Facades\Notification;
20
use App\Notifications\NewUserEmail;
21
22
use App\UserRoleType;
23
use App\UserLogins;
24
use App\Http\Resources\UserCollection;
25
use App\Http\Resources\User as UserResource;
26
27
class UserController extends Controller
28
{
29
    private $user;
30
    //  Constructor sets up middleware
31 112
    public function __construct()
32
    {
33 112
        $this->middleware('auth')->except('initializeUser', 'submitInitializeUser');
34
        $this->middleware(function ($request, $next) {
35 96
            $this->user = auth()->user();  //  TODO - is this correct????
36 96
            $this->authorize('hasAccess', 'Manage Users');
37 80
            return $next($request);
38 112
        });
39 112
    }
40
41
    //  Show the list of current users to edit
42 2
    public function index()
43
    {
44 2
        $userList = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $userList is dead and can be removed.
Loading history...
45 2
        $route    = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $route is dead and can be removed.
Loading history...
46
47
48
        $userList = new UserCollection(User::where('active', 1)->with(['UserLogins' => function ($query) {
49 2
            $query->latest()->limit(1);
50 2
        }])->get()
51
            /** @scrutinizer ignore-call */
52 2
            ->makeVisible('user_id'));
53 2
        $route    = 'admin.user.edit';
54
55 2
        return view('admin.userIndex', [
56 2
            'userList' => $userList,
57 2
            'route'    => $route,
58
            // 'method'   => 'edit',
59
        ]);
60
    }
61
62
    //  Check if a username is in use
63 12
    public function checkUser($username, $type)
64
    {
65 12
        $user = User::where($type, $username)->first();
66
67 12
        if(!$user)
68
        {
69 4
            return response()->json(['duplicate' => false]);
70
        }
71
72 8
        return response()->json([
73 8
            'duplicate' => true,
74 8
            'user'      => $user->full_name,
75 8
            'active'    => $user->active,
76
        ]);
77
    }
78
79
    //  Show the Add User form
80 2
    public function create()
81
    {
82 2
        $roles = UserRoleType::all(); // Role::all();
83
84 2
        $roleArr = [];
85 2
        foreach($roles as $role)
86
        {
87 2
            if($role->role_id == 1 && Auth::user()->role_id != 1)
88
            {
89
                continue;
90
            }
91 2
            else if($role->role_id == 2 && Auth::user()->role_id > 1)
92
            {
93
                continue;
94
            }
95
            else
96
            {
97
                // $roleArr[$role->role_id] = $role->name;
98 2
                $roleArr[] = [
99 2
                    'value' => $role->role_id,
100 2
                    'text'  => $role->name,
101
                ];
102
            }
103
        }
104
105 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
106 2
        return view('admin.newUser', [
107 2
            'roles' => $roleArr
108
        ]);
109
    }
110
111
    //  Submit the Add User form
112 16
    public function store(Request $request)
113
    {
114
        //  Validate the new user form
115 16
        $request->validate([
116 16
            'role'       => 'required|numeric',  //  TODO - add validation rule - is in user roles table
117
            'username'   => 'required|unique:users|regex:/^[a-zA-Z0-9_]*$/',
118
            'first_name' => 'required',
119
            'last_name'  => 'required',
120
            'email'      => 'required|unique:users',
121
        ]);
122
123
        //  Create the user
124 2
        $newUser = User::create([
125 2
            'role_id'    => $request->role,
126 2
            'username'   => $request->username,
127 2
            'first_name' => $request->first_name,
128 2
            'last_name'  => $request->last_name,
129 2
            'email'      => $request->email,
130 2
            'password'   => bcrypt(strtolower(Str::random(15))),
131 2
            'active'     => 1
132
        ]);
133
134 2
        $userID = $newUser->user_id;
135
136
        //  Create the setup user link
137 2
        $hash = strtolower(Str::random(30));
138 2
        UserInitialize::create([
139 2
            'username' => $request->username,
140 2
            'token'    => $hash
141
        ]);
142
143
        //  Email the new user
144
        // Mail::to($request->email)->send(new InitializeUser($hash, $request->username, $request->first_name.' '.$request->last_name));
145 2
        Notification::send($newUser, new NewUserEmail($newUser, $hash));
146
147 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
148 2
        Log::debug('User Data - ', $newUser->toArray());
149 2
        Log::notice('New User ID-'.$userID.' Created by ID-'.Auth::user()->user_id);
150
151
        // return redirect()->back()->with('success', 'New User Created');
152 2
        return response()->json(['success' => true]);
153
    }
154
155
    //  List all active or inactive users
156
    // public function show($type)
157
    // {
158
    //     $userList = [];
159
    //     $route    = '';
160
161
    //     switch($type)
162
    //     {
163
    //         case 'active':
164
    //             $userList = new UserCollection(User::where('active', 1)->with(['UserLogins' => function($query)
165
    //             {
166
    //                 $query->latest()->limit(1);
167
    //             }])->get()
168
    //             /** @scrutinizer ignore-call */
169
    //             ->makeVisible('user_id'));
170
    //             $route    = 'admin.user.edit';
171
    //             break;
172
    //         default:
173
    //             abort(404);
174
    //     }
175
176
    //     // return $userList;
177
178
179
    //     return view('admin.userIndex', [
180
    //         'userList' => $userList,
181
    //         'route'    => $route,
182
    //         // 'method'   => 'edit',
183
    //     ]);
184
185
    // }
186
187
    //  Open the edit user form
188 6
    public function edit($id)
189
    {
190 6
        $roles = UserRoleType::all(); // Role::all();
191 6
        $user  = new UserResource(User::findOrFail($id));
192
193
        //  Make sure that the user is not trying to deactivate someone with more permissions
194 4
        if ($user->role_id < Auth::user()->role_id) 
195
        {
196 2
            return abort(403);
1 ignored issue
show
Bug introduced by
Are you sure the usage of abort(403) 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...
197
        }
198
199
        //  Good to go - update user password
200 2
        $roleArr = [];
201 2
        foreach ($roles as $role) {
202 2
            if ($role->role_id == 1 && Auth::user()->role_id != 1) {
203
                continue;
204 2
            } else if ($role->role_id == 2 && Auth::user()->role_id > 1) {
205
                continue;
206
            } else {
207
                // $roleArr[$role->role_id] = $role->name;
208 2
                $roleArr[] = [
209 2
                    'value' => $role->role_id,
210 2
                    'text'  => $role->name,
211
                ];
212
            }
213
        }
214
215 2
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
216 2
        return view('admin.userEdit', [
217 2
            'roles' => $roleArr,
218 2
            'user'  => $user->makeVisible(['user_id', 'username']),
0 ignored issues
show
Bug introduced by
The method makeVisible() does not exist on App\Http\Resources\User. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

218
            'user'  => $user->/** @scrutinizer ignore-call */ makeVisible(['user_id', 'username']),
Loading history...
219
        ]);
220
    }
221
222
    //  Submit the update user form
223 22
    public function update(Request $request, $id)
224
    {
225 22
        $request->validate([
226
            'username'   => [
227 22
                                'required',
228 22
                                Rule::unique('users')->ignore($id, 'user_id')
229
                            ],
230 22
            'first_name' => 'required',
231 22
            'last_name'  => 'required',
232
            'email'      => [
233 22
                                'required',
234 22
                                Rule::unique('users')->ignore($id, 'user_id')
235
                            ],
236 22
            'role'       => 'required',
237
        ]);
238
239
        //  Update the user data
240 8
        $user = User::findOrFail($id);
241
242 6
        if ($user->role_id < Auth::user()->role_id) 
243
        {
244 2
            return abort(403);
1 ignored issue
show
Bug introduced by
Are you sure the usage of abort(403) 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...
245
        }
246
247 4
        $user->update(
248
        [
249 4
            'username'   => $request->username,
250 4
            'first_name' => $request->first_name,
251 4
            'last_name'  => $request->last_name,
252 4
            'email'      => $request->email,
253 4
            'role_id'    => $request->role,
254
        ]);
255
256
        //  Update the user's role
257 4
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
258 4
        Log::debug('Edit user form submitted for User ID-'.$id.'  Data - ', $request->toArray());
259 4
        Log::notice('User ID-'.$id.' has updated their information.');
260 4
        return response()->json(['success' => true]);
261
    }
262
263
    //  Submit the change password form
264 12
    public function submitPassword(Request $request)
265
    {
266 12
        $request->validate([
267 12
            'password' => 'required|string|min:6|confirmed',
268
            'user_id'  => 'required',
269
        ]);
270
271
        // $nextChange = isset($request->force_change) && $request->force_change == 'on' ? Carbon::now()->subDay() : null;
272
273 8
        if($request->force_change)
274
        {
275 6
            $nextChange = Carbon::now()->subDay();
276
        }
277
        else
278
        {
279 2
            $nextChange = config('users.passExpires') != null ? Carbon::now()->addDays(config('users.passExpires')) : null;
280
        }
281
282 8
        $user = User::find($request->user_id);
283
284
        //  Verify this is a valid user ID
285 8
        if (!$user) {
286 2
            $success = false;
287 2
            $reason  = 'Cannot find user with this ID';
288
        }
289
        //  Make sure that the user is not trying to deactivate someone with more permissions
290 6
        else if ($user->role_id < Auth::user()->role_id) {
291 2
            $success = false;
292 2
            $reason  = 'You cannot change password for a user with higher permissions that you.  If this user has locked themselves out, have then use the reset link on the login page.';
293
        }
294
        //  Good to go - update user password
295
        else {
296
            //  Update the user data
297 4
            $user->update(
298
            [
299 4
                'password'         => bcrypt($request->password),
300 4
                'password_expires' => $nextChange
301
            ]);
302 4
            $success = true;
303 4
            $reason  = 'Password for ' . $user->full_name . ' successfully reset.';
304
        }
305
306 8
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
307 8
        Log::notice('User ID-' . $request->user_id . ' password chagned by ' . Auth::user()->user_id, [
308 8
            'success' => $success,
309 8
            'reason'  => $reason,
310
        ]);
311
312 8
        return response()->json([
313 8
            'success' => $success,
314 8
            'reason'  => $reason,
315
        ]);
316
    }
317
318
    //  Disable the user
319 8
    public function destroy($id)
320
    {
321 8
        $user = User::find($id);
322
323
        //  Verify this is a valid user ID
324 8
        if(!$user)
325
        {
326 2
            $success = false;
327 2
            $reason  = 'Cannot find user with this ID';
328
        }
329
        //  Make suer that the user is not trying to deactivate themselves
330 6
        else if(Auth::user()->user_id == $id)
331
        {
332 2
            $success = false;
333 2
            $reason  = 'You cannot deactivate yourself';
334
        }
335
        //  Make sure that the user is not trying to deactivate someone with more permissions
336 4
        else if($user->role_id < Auth::user()->role_id)
337
        {
338 2
            $success = false;
339 2
            $reason  = 'You cannot deactivate a user with higher permissions that you.';
340
        }
341
        //  Good to go - deactivate user
342
        else
343
        {
344 2
            $user->update(['active' => 0]);
345 2
            $success = true;
346 2
            $reason  = 'User '.$user->full_name.' successfully deactivated.';
347
        }
348
349 8
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
350 8
        Log::notice('User ID-'.$id.' disabled by '.Auth::user()->user_id, [
351 8
            'success' => $success,
352 8
            'reason'  => $reason,
353
        ]);
354
355 8
        return response()->json([
356 8
            'success' => $success,
357 8
            'reason'  => $reason,
358
        ]);
359
    }
360
}
361