-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathUserController.php
More file actions
889 lines (748 loc) · 30.1 KB
/
UserController.php
File metadata and controls
889 lines (748 loc) · 30.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
<?php
namespace Fleetbase\Http\Controllers\Internal\v1;
use Fleetbase\Attributes\SkipAuthorizationCheck;
use Fleetbase\Events\UserRemovedFromCompany;
use Fleetbase\Exceptions\FleetbaseRequestValidationException;
use Fleetbase\Exports\UserExport;
use Fleetbase\Http\Controllers\FleetbaseController;
use Fleetbase\Http\Requests\CreateUserRequest;
use Fleetbase\Http\Requests\ExportRequest;
use Fleetbase\Http\Requests\Internal\AcceptCompanyInvite;
use Fleetbase\Http\Requests\Internal\InviteUserRequest;
use Fleetbase\Http\Requests\Internal\ResendUserInvite;
use Fleetbase\Http\Requests\Internal\UpdatePasswordRequest;
use Fleetbase\Http\Requests\Internal\ValidatePasswordRequest;
use Fleetbase\Http\Requests\UpdateUserRequest;
use Fleetbase\Models\Company;
use Fleetbase\Models\CompanyUser;
use Fleetbase\Models\Invite;
use Fleetbase\Models\Permission;
use Fleetbase\Models\Policy;
use Fleetbase\Models\Setting;
use Fleetbase\Models\User;
use Fleetbase\Notifications\UserAcceptedCompanyInvite;
use Fleetbase\Notifications\UserInvited;
use Fleetbase\Services\UserCacheService;
use Fleetbase\Support\Auth;
use Fleetbase\Support\NotificationRegistry;
use Fleetbase\Support\TwoFactorAuth;
use Fleetbase\Support\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends FleetbaseController
{
/**
* The resource to query.
*
* @var string
*/
public $resource = 'user';
/**
* The service which this controller belongs to.
*
* @var string
*/
public $service = 'iam';
/**
* Create user request.
*
* @var CreateUserRequest
*/
public $createRequest = CreateUserRequest::class;
/**
* Update user request.
*
* Enforces that email and phone cannot be set to an empty string
* and that uniqueness constraints are respected on update.
*
* @var UpdateUserRequest
*/
public $updateRequest = UpdateUserRequest::class;
/**
* Query users always against the production database.
*
* Users are authoritative in production. The sandbox database contains
* only a mirrored copy. Temporarily restoring the production connection
* for this query ensures the IAM list is correct regardless of whether
* the console is in sandbox mode, without affecting any other sandbox
* queries in the same request lifecycle.
*
* @return \Illuminate\Http\Response
*/
public function queryRecord(Request $request)
{
$isSandbox = config('fleetbase.connection.db') === 'sandbox';
if ($isSandbox) {
config([
'database.default' => env('DB_CONNECTION', 'mysql'),
'fleetbase.connection.db' => env('DB_CONNECTION', 'mysql'),
]);
}
$response = parent::queryRecord($request);
if ($isSandbox) {
config([
'database.default' => 'sandbox',
'fleetbase.connection.db' => 'sandbox',
]);
}
return $response;
}
/**
* Creates a record with request payload.
*
* If the supplied email address already belongs to an existing user the
* request is treated as a cross-organisation invitation rather than a
* duplicate-creation attempt. The existing user is invited to join the
* current company and the response includes `invited: true` so the
* frontend can display the appropriate success message.
*
* @return \Illuminate\Http\Response
*/
public function createRecord(Request $request)
{
$this->validateRequest($request);
// Detect whether the email already belongs to an existing user.
// If so, redirect to the cross-organisation invite flow instead of
// attempting to create a duplicate user record.
$email = strtolower((string) $request->input('user.email', ''));
$existingUser = $email ? User::where('email', $email)->whereNull('deleted_at')->first() : null;
if ($existingUser) {
// Guard: the user is already a member of the current organisation.
$alreadyMember = $existingUser->companyUsers()
->where('company_uuid', session('company'))
->exists();
if ($alreadyMember) {
return response()->error('This user is already a member of your organisation.');
}
return $this->inviteExistingUser($existingUser, $request);
}
try {
$record = $this->model->createRecordFromRequest($request, function (&$request, &$input) {
// Get user properties
$name = $request->input('user.name');
$timezone = $request->or(['timezone', 'user.timezone'], date_default_timezone_get());
$username = Str::slug($name . '_' . Str::random(4), '_');
// Prepare user attributes
$input = User::applyUserInfoFromRequest($request, array_merge($input, [
'company_uuid' => session('company'),
'name' => $name,
'username' => $username,
'ip_address' => $request->ip(),
'timezone' => $timezone,
]));
}, function (&$request, &$user) {
// Make sure to assign to current company
$company = Auth::getCompany();
// Set user type
$user->setUserType('user');
// Assign to user
$user->assignCompany($company, $request->input('user.role_uuid'));
// Assign role if set
if ($request->filled('user.role_uuid')) {
$user->assignSingleRole($request->input('user.role_uuid'));
}
// Sync Permissions
if ($request->isArray('user.permissions')) {
$permissions = Permission::whereIn('id', $request->array('user.permissions'))->get();
$user->syncPermissions($permissions);
}
// Sync Policies
if ($request->isArray('user.policies')) {
$policies = Policy::whereIn('id', $request->array('user.policies'))->get();
$user->syncPolicies($policies);
}
});
return ['user' => new $this->resource($record)];
} catch (\Exception $e) {
return response()->error($e->getMessage());
} catch (\Illuminate\Database\QueryException $e) {
return response()->error($e->getMessage());
} catch (FleetbaseRequestValidationException $e) {
return response()->error($e->getErrors());
}
}
/**
* Updates a record with request payload.
*
* @return \Illuminate\Http\Response
*/
public function updateRecord(Request $request, string $id)
{
// Run the UpdateUserRequest validation rules before delegating to the
// model trait. This prevents email/phone being set to an empty string
// and enforces uniqueness constraints on partial (PATCH) updates.
$this->validateRequest($request);
try {
$record = $this->model->updateRecordFromRequest($request, $id, function (&$request, &$user) {
// Assign role if set
if ($request->filled('user.role')) {
$user->assignSingleRole($request->input('user.role'));
}
// Sync Permissions
if ($request->isArray('user.permissions')) {
$permissions = Permission::whereIn('id', $request->array('user.permissions'))->get();
$user->syncPermissions($permissions);
}
// Sync Policies
if ($request->isArray('user.policies')) {
$policies = Policy::whereIn('id', $request->array('user.policies'))->get();
$user->syncPolicies($policies);
}
});
return ['user' => new $this->resource($record)];
} catch (\Exception $e) {
return response()->error($e->getMessage());
} catch (\Illuminate\Database\QueryException $e) {
return response()->error($e->getMessage());
} catch (FleetbaseRequestValidationException $e) {
return response()->error($e->getErrors());
}
}
/**
* Responds with the currently authenticated user.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function current(Request $request)
{
$user = $request->user();
if (!$user) {
return response()->error('No user session found', 401);
}
// Check if caching is enabled
if (!UserCacheService::isEnabled()) {
return response()->json([
'user' => new $this->resource($user),
]);
}
// Generate ETag for cache validation
$etag = UserCacheService::generateETag($user);
// Try to get from server cache
$companyId = session('company');
$cachedData = UserCacheService::get($user, $companyId);
if ($cachedData) {
// Return cached data with cache headers
return response()->json(['user' => $cachedData])
->setEtag($etag)
->setLastModified($user->updated_at)
->header('Cache-Control', 'private, no-cache, must-revalidate')
->header('X-Cache-Hit', 'true');
}
// Cache miss - load fresh data with eager loading
// Note: role, policies, permissions are accessors that use companyUser relationship
$user->loadCompanyUser();
// Transform to resource
$userData = new $this->resource($user);
$userArray = $userData->toArray($request);
// Store in cache
UserCacheService::put($user, $companyId, $userArray);
// Return with cache headers
return response()->json(['user' => $userArray])
->setEtag($etag)
->setLastModified($user->updated_at)
->header('Cache-Control', 'private, no-cache, must-revalidate')
->header('X-Cache-Hit', 'false');
}
/**
* Get the current user's two factor authentication settings.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function getTwoFactorSettings(Request $request)
{
$user = $request->user();
if (!$user) {
return response()->error('No user session found', 401);
}
$twoFaSettings = TwoFactorAuth::getTwoFaSettingsForUser($user);
return response()->json($twoFaSettings->value);
}
/**
* Save the current user's two factor authentication settings.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function saveTwoFactorSettings(Request $request)
{
$twoFaSettings = $request->array('twoFaSettings');
$user = $request->user();
if (!$user) {
return response()->error('No user session found', 401);
}
$twoFaSettings = TwoFactorAuth::saveTwoFaSettingsForUser($user, $twoFaSettings);
return response()->json($twoFaSettings->value);
}
/**
* Invite a user (new or existing) to join the current organisation.
*
* - If the email belongs to an existing user in another organisation, a
* cross-organisation invitation is issued without creating a new user.
* - If the email is brand-new, a pending user record is created and the
* invitation email is sent so they can set a password on acceptance.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function inviteUser(InviteUserRequest $request)
{
$data = $request->input('user');
$email = strtolower($data['email']);
$company = Auth::getCompany();
if (!$company) {
return response()->error('Unable to determine the current organisation.');
}
// Check if user already exists in the system.
$user = User::where('email', $email)->whereNull('deleted_at')->first();
if ($user) {
// Guard: already a member of this organisation.
$alreadyMember = $user->companyUsers()
->where('company_uuid', $company->uuid)
->exists();
if ($alreadyMember) {
return response()->error('This user is already a member of your organisation.');
}
// Existing user from another org — issue a cross-org invite.
return $this->inviteExistingUser($user, $request);
}
// Brand-new user — create a pending record then invite.
$data['company_uuid'] = $company->uuid;
$data['status'] = 'pending';
$data['type'] = 'user';
$data['created_at'] = Carbon::now();
$user = User::create($data);
// Set user type
$user->setUserType('user');
// Assign to user
$user->assignCompany($company, $request->input('user.role_uuid'));
// Assign role if set
if ($request->filled('user.role_uuid')) {
$user->assignSingleRole($request->input('user.role_uuid'));
}
$invitation = Invite::create([
'company_uuid' => $company->uuid,
'created_by_uuid' => session('user'),
'subject_uuid' => $company->uuid,
'subject_type' => Utils::getMutationType($company),
'protocol' => 'email',
'recipients' => [$user->email],
'reason' => 'join_company',
'meta' => array_filter(['role_uuid' => $request->input('user.role_uuid') ?? $request->input('user.role')]),
'expires_at' => now()->addHours(48),
]);
$user->notify(new UserInvited($invitation));
return response()->json(['user' => new $this->resource($user)]);
}
/**
* Issue a join-company invitation to a user who already exists in the
* system but belongs to a different organisation.
*
* This private helper is shared by both `createRecord()` (which detects
* an existing email during the standard "New User" flow) and `inviteUser()`
* (the dedicated invite endpoint). Keeping the logic in one place ensures
* both paths behave identically.
*
* @param User $user the existing user to invite
* @param Request $request the originating HTTP request
*/
private function inviteExistingUser(User $user, Request $request): \Illuminate\Http\JsonResponse
{
$company = Auth::getCompany();
if (!$company) {
return response()->error('Unable to determine the current organisation.');
}
// Guard: prevent duplicate invitations using the model helper.
if (Invite::isAlreadySentToJoinCompany($user, $company)) {
return response()->error('This user has already been invited to join your organisation.');
}
$invitation = Invite::create([
'company_uuid' => $company->uuid,
'created_by_uuid' => session('user'),
'subject_uuid' => $company->uuid,
'subject_type' => Utils::getMutationType($company),
'protocol' => 'email',
'recipients' => [$user->email],
'reason' => 'join_company',
'meta' => array_filter(['role_uuid' => $request->input('user.role_uuid') ?? $request->input('user.role')]),
'expires_at' => now()->addHours(48),
]);
$user->notify(new UserInvited($invitation));
// Return `invited: true` so the frontend can distinguish between
// a newly created user and a cross-organisation invite.
return response()->json([
'user' => new $this->resource($user),
'invited' => true,
]);
}
/**
* Resend invitation to pending user.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function resendInvitation(ResendUserInvite $request)
{
$user = User::where('uuid', $request->input('user'))->first();
$company = Company::where('uuid', session('company'))->first();
// create invitation
$invitation = Invite::create([
'company_uuid' => session('company'),
'created_by_uuid' => session('user'),
'subject_uuid' => $company->uuid,
'subject_type' => Utils::getMutationType($company),
'protocol' => 'email',
'recipients' => [$user->email],
'reason' => 'join_company',
'expires_at' => now()->addHours(48),
]);
// notify user
$user->notify(new UserInvited($invitation));
return response()->json(['status' => 'ok']);
}
/**
* Accept invitation to join a company/organization.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function acceptCompanyInvite(AcceptCompanyInvite $request)
{
$invite = Invite::where('code', $request->input('code'))->with(['subject'])->first();
// get invited email
$email = Arr::first($invite->recipients);
if (!$email) {
return response()->error('Unable to locate the user for this invitation.');
}
// get user from invite
$user = User::where('email', $email)->first();
if (!$user) {
return response()->error('Unable to locate the user for this invitation.');
}
// get the company who sent the invite
$company = $invite->subject;
if (!$company) {
return response()->error('The organization that invited you no longer exists.');
}
// determine if user needs to set password (when status pending)
$isPending = $needsPassword = $user->status === 'pending';
// Add user to company only if they are not already a member.
// This guards against double-acceptance (e.g. clicking the invite
// link twice) creating a duplicate company_users row.
$alreadyMember = CompanyUser::where('user_uuid', $user->uuid)
->where('company_uuid', $company->uuid)
->exists();
if (!$alreadyMember) {
// Use Company::addUser() so that role assignment is handled in
// one place. The role stored in the invite meta takes precedence;
// if none was set the default 'Administrator' role is used.
$roleIdentifier = $invite->getMeta('role_uuid', 'Administrator');
$companyUser = $company->addUser($user, $roleIdentifier);
$user->setRelation('companyUser', $companyUser);
} else {
// User is already a member — ensure the companyUser relation is
// loaded so that role assignment below can still be applied if
// the invite carries a role (e.g. re-sent invite with a new role).
$user->loadCompanyUser();
$roleUuid = $invite->getMeta('role_uuid');
if ($user->companyUser && $roleUuid) {
$user->companyUser->assignSingleRole($roleUuid);
}
}
// Delete the invite
$invite->delete();
// Switch the user's active company to the one they just joined.
// This ensures that subsequent calls to /users/me resolve the
// companyUser relationship (and therefore role/policies) against
// the correct company rather than the user's previous company.
$user->company_uuid = $company->uuid;
$user->save();
// activate user
if ($isPending) {
$user->update(['email_verified_at' => now()]);
$user->activate();
}
// create authentication token for user
$token = $user->createToken($invite->code);
// Notify company that user has accepted their invite
NotificationRegistry::notify(UserAcceptedCompanyInvite::class, $company, $user);
return response()->json([
'status' => 'ok',
'token' => $token->plainTextToken,
'needs_password' => $needsPassword,
]);
}
/**
* Deactivates a user.
*
* @return \Illuminate\Http\Response
*/
public function deactivate($id)
{
if (!$id) {
return response()->error('No user to deactivate', 401);
}
$currentUser = request()->user();
// Scope the lookup to the current company to prevent cross-organization IDOR.
$user = User::where('uuid', $id)
->whereHas('companyUsers', function ($query) {
$query->where('company_uuid', session('company'));
})
->first();
if (!$user) {
return response()->error('No user found', 404);
}
// Prevent a user from deactivating their own account via this endpoint.
if ($currentUser && $currentUser->uuid === $user->uuid) {
return response()->error('You cannot deactivate your own account.', 403);
}
// Layered privilege check:
//
// Tier 1 — System admins (isAdmin()) can deactivate anyone except other
// system admins. This is the highest privilege tier.
if ($user->isAdmin()) {
return response()->error('Insufficient permissions to deactivate this user.', 403);
}
// Tier 2 — Users holding the 'Administrator' role can only be deactivated
// by a system admin (handled above). A regular user or another
// role-based Administrator cannot deactivate them.
if ($user->hasRole('Administrator') && $currentUser && !$currentUser->isAdmin()) {
return response()->error('Insufficient permissions to deactivate this user.', 403);
}
// Only deactivate the CompanyUser record for the current organisation.
// Calling User::deactivate() would set the user's global status to
// 'inactive', locking them out of every organisation they belong to.
// Instead we update only the pivot record so the user remains active
// in any other organisations they are a member of.
$companyUser = $user->companyUsers()->where('company_uuid', session('company'))->first();
if (!$companyUser) {
return response()->error('User is not a member of this organisation.', 404);
}
$companyUser->status = 'inactive';
$companyUser->save();
return response()->json([
'message' => 'User deactivated',
'status' => $companyUser->status,
]);
}
/**
* Activates/re-activates a user.
*
* @return \Illuminate\Http\Response
*/
public function activate($id)
{
if (!$id) {
return response()->error('No user to activate', 401);
}
$currentUser = request()->user();
// Scope the lookup to the current company to prevent cross-organisation IDOR.
$user = User::where('uuid', $id)
->whereHas('companyUsers', function ($query) {
$query->where('company_uuid', session('company'));
})
->first();
if (!$user) {
return response()->error('No user found', 404);
}
// Activate both the User record and the CompanyUser record.
// Unlike deactivation (which is scoped to the current organisation only),
// activation must also update users.status because a newly created user
// starts with a global status of 'inactive' and needs to be unblocked
// at the user level before they can access any organisation.
$user->activate();
$user = $user->refresh();
return response()->json([
'message' => 'User activated',
'status' => $user->session_status,
]);
}
/**
* Verify a user manually.
*
* @return \Illuminate\Http\Response
*/
public function verify($id)
{
if (!$id) {
return response()->error('No user to activate', 401);
}
$user = User::where('uuid', $id)->first();
if (!$user) {
return response()->error('No user found', 401);
}
$user->manualVerify();
$user = $user->refresh();
return response()->json([
'message' => 'User verified',
'email_verified_at' => $user->email_verified_at,
'status' => 'ok',
]);
}
/**
* Removes this user from the current company.
*
* @return \Illuminate\Http\Response
*/
public function removeFromCompany($id)
{
if (!$id) {
return response()->error('No user to remove', 401);
}
// get user to remove from company
$user = User::where('uuid', $id)->first();
if (!$user) {
return response()->error('No user found', 401);
}
// get the current company user is being removed from
$company = Company::where('uuid', session('company'))->first();
if (!$company) {
return response()->error('Unable to remove user from this company', 401);
}
/** @var \Illuminate\Support\Collection */
$userCompanies = $user->companyUsers()->get();
// only a member to one company then delete the user
if ($userCompanies->count() === 1) {
$user->delete();
} else {
$user->companyUsers()->where('company_uuid', $company->uuid)->delete();
// trigger event user removed from company
event(new UserRemovedFromCompany($user, $company));
// set to other company for next login
$nextCompany = $userCompanies->filter(function ($userCompany) {
return $userCompany->company_uuid !== session('company');
})->first();
if ($nextCompany) {
$user->update(['company_uuid' => $nextCompany->uuid]);
} else {
$user->delete();
}
}
return response()->json([
'message' => 'User removed',
]);
}
/**
* Updates the current users password.
*
* @return \Illuminate\Http\Response
*/
public function setCurrentUserPassword(UpdatePasswordRequest $request)
{
$password = $request->input('password');
$user = $request->user();
if (!$user) {
return response()->error('User not authenticated');
}
$user->changePassword($password);
return response()->json(['status' => 'ok']);
}
/**
* Endpoint to quickly search/query.
*
* @return \Illuminate\Http\Response
*/
public function searchRecords(Request $request)
{
$query = $request->input('query');
$results = User::select(['uuid', 'name'])
->search($query)
->limit(12)
->get();
return response()->json($results);
}
/**
* Export the users to excel or csv.
*
* @return \Illuminate\Http\Response
*/
public function export(ExportRequest $request)
{
$format = $request->input('format', 'xlsx');
$selections = $request->array('selections');
$fileName = trim(Str::slug('users-' . date('Y-m-d-H:i')) . '.' . $format);
return Excel::download(new UserExport($selections), $fileName);
}
/**
* Get user and always return with driver.
*
* @return \Illuminate\Http\Response
*/
public static function getWithDriver($id, Request $request)
{
$user = User::select(['public_id', 'uuid', 'email', 'name', 'phone', 'type'])->where('uuid', $id)->with(['driver'])->first();
$json = $user->toArray();
$json['driver'] = $user->driver;
return response()->json(['user' => $user]);
}
/**
* Validate the user's current password.
*
* @return \Illuminate\Http\Response
*/
public function validatePassword(ValidatePasswordRequest $request)
{
return response()->json(['status' => 'ok']);
}
/**
* Change the user's password.
*
* @return \Illuminate\Http\Response
*/
public function changeUserPassword(UpdatePasswordRequest $request)
{
$user = $request->user();
$newPassword = $request->input('password');
$newConfirmPassword = $request->input('password_confirmation');
if ($newPassword !== $newConfirmPassword) {
return response()->error('Password is not matching');
}
$user->changePassword($newPassword);
return response()->json(['status' => 'ok']);
}
/**
* Save the user selected locale.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function setUserLocale(Request $request)
{
$locale = $request->input('locale', 'en-us');
$user = $request->user();
$localeSettingKey = 'user.' . $user->uuid . '.locale';
// Persist to database
Setting::configure($localeSettingKey, $locale);
return response()->json(['status' => 'ok']);
}
/**
* Get the user selected locale.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function getUserLocale(Request $request)
{
$user = $request->user();
$localeSettingKey = 'user.' . $user->uuid . '.locale';
// Get from database
$locale = Setting::lookup($localeSettingKey, 'en-us');
return response()->json(['status' => 'ok', 'locale' => $locale]);
}
/**
* Get all current user permissions.
*
* @return \Illuminate\Http\Response
*/
#[SkipAuthorizationCheck]
public function getUserPermissions(Request $request)
{
$user = $request->user();
$permissions = $user->getAllPermissions();
return response()->json(['permissions' => $permissions]);
}
}