-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathAuthController.php
More file actions
958 lines (809 loc) · 32.3 KB
/
AuthController.php
File metadata and controls
958 lines (809 loc) · 32.3 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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
<?php
namespace Fleetbase\Http\Controllers\Internal\v1;
use Fleetbase\Events\UserCreatedNewCompany;
use Fleetbase\Exceptions\InvalidVerificationCodeException;
use Fleetbase\Http\Controllers\Controller;
use Fleetbase\Http\Requests\AdminRequest;
use Fleetbase\Http\Requests\ChangePasswordRequest;
use Fleetbase\Http\Requests\Internal\ResetPasswordRequest;
use Fleetbase\Http\Requests\Internal\UserForgotPasswordRequest;
use Fleetbase\Http\Requests\JoinOrganizationRequest;
use Fleetbase\Http\Requests\LoginRequest;
use Fleetbase\Http\Requests\SignUpRequest;
use Fleetbase\Http\Requests\SwitchOrganizationRequest;
use Fleetbase\Http\Resources\Organization;
use Fleetbase\Mail\UserCredentialsMail;
use Fleetbase\Models\Company;
use Fleetbase\Models\CompanyUser;
use Fleetbase\Models\Invite;
use Fleetbase\Models\User;
use Fleetbase\Models\VerificationCode;
use Fleetbase\Notifications\UserForgotPassword;
use Fleetbase\Support\Auth;
use Fleetbase\Support\TwoFactorAuth;
use Fleetbase\Support\Utils;
use Fleetbase\Twilio\Support\Laravel\Facade as Twilio;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Laravel\Sanctum\PersonalAccessToken;
class AuthController extends Controller
{
/**
* Authenticates a user by email and responds with an auth token.
*
* @return \Illuminate\Http\Response
*/
public function login(LoginRequest $request)
{
$identity = $request->input('identity');
$password = $request->input('password');
$authToken = $request->input('authToken');
// If an existing auth token is provided, attempt to re-authenticate with it.
// The token must be valid AND must belong to the user identified by the
// 'identity' field in this request, preventing token-swap attacks where a
// token from one user could be used to authenticate as another.
if ($authToken) {
$personalAccessToken = PersonalAccessToken::findToken($authToken);
if ($personalAccessToken) {
$personalAccessToken->loadMissing('tokenable');
$tokenOwner = $personalAccessToken->tokenable;
if (
$tokenOwner instanceof User
&& ($tokenOwner->email === $identity || $tokenOwner->phone === $identity)
) {
return response()->json([
'token' => $authToken,
'type' => $tokenOwner->getType(),
]);
}
}
// If the token is invalid or does not match the claimed identity, fall
// through silently to normal password-based authentication. Do not
// return an error here to avoid leaking whether the token exists.
}
// Find the user using the identity provided
$user = User::where(function ($query) use ($identity) {
$query->where('email', $identity)->orWhere('phone', $identity);
})->first();
// If the user exists but has no password set (e.g. SSO-invited or provisioned
// accounts), silently fall through to the generic credentials error below.
// This guard MUST come before isInvalidPassword() which has a strict string
// type declaration on $hashedPassword and would throw a TypeError on null.
// We do NOT return a distinct error here to avoid leaking account state.
if ($user && empty($user->password)) {
$user = null;
}
// Use a generic error message for both non-existent user and wrong password
// to prevent user enumeration via differential error responses.
if (!$user || Auth::isInvalidPassword($password, $user->password)) {
return response()->error('These credentials do not match our records.', 401, ['code' => 'invalid_credentials']);
}
// Check if 2FA enabled
if (TwoFactorAuth::isEnabled($user)) {
$twoFaSession = TwoFactorAuth::start($user);
return response()->json([
'twoFaSession' => $twoFaSession,
'isEnabled' => true,
]);
}
if ($user->isNotVerified() && $user->isNotAdmin()) {
return response()->error('User is not verified.', 400, ['code' => 'not_verified']);
}
// Login
$user->updateLastLogin();
$token = $user->createToken($user->uuid);
return response()->json(['token' => $token->plainTextToken, 'type' => $user->getType()]);
}
/**
* Takes a request username/ or email and password and attempts to authenticate user
* will return the user model if the authentication was successful, else will 400.
*
* @return \Illuminate\Http\Response
*/
public function session(Request $request)
{
$token = $request->bearerToken();
$cacheKey = "session_validation_{$token}";
// Cache session validation for 5 minutes
$session = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($request) {
$user = $request->user();
if (!$user) {
return null;
}
$sessionData = [
'token' => $request->bearerToken(),
'user' => $user->uuid,
'verified' => $user->isVerified(),
'type' => $user->getType(),
'last_modified' => $user->updated_at,
];
if (session()->has('impersonator')) {
$sessionData['impersonator'] = session()->get('impersonator');
}
return $sessionData;
});
if (!$session) {
return response()->error('Session has expired.', 401, ['restore' => false]);
}
// Generate an etag
$etag = sha1(json_encode($session));
return response()
->json($session)
->setEtag($etag)
->setLastModified($session['last_modified'])
->header('Cache-Control', 'private, no-cache, must-revalidate')
->header('X-Cache-Hit', 'false');
}
/**
* Logs out the currently authenticated user.
*
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$token = $request->bearerToken();
Cache::forget("session_validation_{$token}");
Auth::logout();
return response()->json(['Goodbye']);
}
/**
* Bootstrap endpoint - combines session, organizations, and installer status.
*
* @return \Illuminate\Http\Response
*/
public function bootstrap(Request $request)
{
$user = $request->user();
$token = $request->bearerToken();
$cacheKey = "auth_bootstrap_{$user->uuid}_{$token}";
// Cache for 5 minutes
$bootstrap = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($request, $user) {
// Get session data
$session = [
'token' => $request->bearerToken(),
'user' => $user->uuid,
'verified' => $user->isVerified(),
'type' => $user->getType(),
];
if (session()->has('impersonator')) {
$session['impersonator'] = session()->get('impersonator');
}
// Get organizations (optimized query)
$organizations = Company::select([
'companies.uuid',
'companies.name',
'companies.owner_uuid',
])
->join('company_users', 'companies.uuid', '=', 'company_users.company_uuid')
->where('company_users.user_uuid', $user->uuid)
->whereNull('company_users.deleted_at')
->whereNotNull('companies.owner_uuid')
->with(['owner:uuid,company_uuid,name,email'])
->distinct()
->get();
// Get installer status (cached separately)
$installer = Cache::remember('installer_status', now()->addHour(), function () {
$shouldInstall = false;
$shouldOnboard = false;
try {
DB::connection()->getPdo();
if (DB::connection()->getDatabaseName()) {
if (\Illuminate\Support\Facades\Schema::hasTable('companies')) {
$shouldOnboard = !DB::table('companies')->exists();
} else {
$shouldInstall = true;
}
} else {
$shouldInstall = true;
}
} catch (\Exception $e) {
$shouldInstall = true;
}
return [
'shouldInstall' => $shouldInstall,
'shouldOnboard' => $shouldOnboard,
'defaultTheme' => \Fleetbase\Models\Setting::lookup('branding.default_theme', 'dark'),
];
});
return [
'session' => $session,
'organizations' => Organization::collection($organizations),
'installer' => $installer,
];
});
return response()->json($bootstrap)
->header('Cache-Control', 'private, max-age=300');
}
/**
* Send a verification SMS code.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function sendVerificationSms(Request $request)
{
// Users phone number
$phone = $queryPhone = $request->input('phone');
$countryCode = $request->input('countryCode');
$for = $request->input('driver');
// set phone number
if (!Str::startsWith($queryPhone, '+')) {
$queryPhone = '+' . $countryCode . $phone;
}
// Make sure user exists with phone number
$userExistsQuery = User::where('phone', $queryPhone)->whereNull('deleted_at')->withoutGlobalScopes();
if ($for === 'driver') {
$userExistsQuery->where('type', 'driver');
}
$userExists = $userExistsQuery->exists();
if (!$userExists) {
return response()->error('No user with this phone # found.');
}
// Generate hto
$verifyCode = mt_rand(100000, 999999);
$verifyCodeKey = Str::slug($queryPhone . '_verify_code', '_');
// Send user their verification code
try {
Twilio::message($queryPhone, 'Your Fleetbase authentication code is ' . $verifyCode);
} catch (\Exception|\Twilio\Exceptions\RestException $e) {
return response()->json(['error' => $e->getMessage()], 400);
}
// Store verify code for this number with a 10-minute TTL to prevent replay attacks
Redis::setex($verifyCodeKey, 600, $verifyCode);
// 200 OK
return response()->json(['status' => 'OK']);
}
/**
* Authenticate a user with SMS code.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function authenticateSmsCode(Request $request)
{
// Users phone number
$phone = $queryPhone = $request->input('phone');
$countryCode = $request->input('countryCode');
// set phone number
if (!Str::startsWith($queryPhone, '+')) {
$queryPhone = '+' . $countryCode . $phone;
}
// Users verfiy code entered
$verifyCode = $request->input('code');
$verifyCodeKey = Str::slug($queryPhone . '_verify_code', '_');
// Retrieve the stored verification code from Redis
$storedVerifyCode = Redis::get($verifyCodeKey);
// Retrieve the optional testing bypass code from configuration.
// This is configurable via the SMS_AUTH_BYPASS_CODE environment variable
// and is intended for development/testing environments only.
// It MUST be left unset (null) in production deployments.
$bypassCode = config('fleetbase.sms_auth_bypass_code');
// Verify the submitted code against the stored OTP using a constant-time
// comparison to prevent timing attacks. If a bypass code is configured
// and the environment is not production, also allow that code.
$isValidOtp = !empty($storedVerifyCode) && hash_equals((string) $storedVerifyCode, (string) $verifyCode);
$isBypassValid = !empty($bypassCode) && !app()->environment('production') && hash_equals((string) $bypassCode, (string) $verifyCode);
if (!$isValidOtp && !$isBypassValid) {
return response()->error('Invalid verification code');
}
// Remove from redis
Redis::del($verifyCodeKey);
// get user for phone number
$user = User::where('phone', $queryPhone)->first();
// Attempt authentication
if ($user) {
// Set authenticatin user
Auth::login($user);
// Generate token
try {
$token = $user->createToken($user->phone)->plainTextToken;
} catch (\Exception $e) {
return response()->error($e->getMessage());
}
if ($user->type === 'driver') {
$user->load(['driver']);
}
// Send message to notify users authentication
return response()->json([
'token' => $token,
'user' => $user,
]);
}
// If unable to authenticate user, respond with error
return response()->json('Authentication failed', 401);
}
/**
* Create resend verification code session.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function createVerificationSession(Request $request)
{
$send = $request->boolean('send');
$email = $request->input('email');
$token = Str::random(40);
$verificationSessionToken = base64_encode($email . '|' . $token);
// If opted to send verification token along with session
if ($send) {
// Get user
$user = User::where('email', $email)->first();
if ($user) {
// create verification code
VerificationCode::generateEmailVerificationFor($user);
} else {
Redis::del($token);
return response()->error('No user found with provided email address.');
}
}
// Store in redis
Redis::set($token, $verificationSessionToken, 'EX', now()->addMinutes(10)->timestamp);
return response()->json([
'token' => $token,
'session' => base64_encode($user->uuid),
]);
}
/**
* Validates an email verification session.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function validateVerificationSession(Request $request)
{
$email = $request->input('email');
$token = $request->input('token');
$verificationSessionToken = base64_encode($email . '|' . $token);
$sessionToken = Redis::get($token);
$isValid = $sessionToken === $verificationSessionToken;
return response()->json([
'valid' => $isValid,
]);
}
/**
* Send/Resend verification email.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function sendVerificationEmail(Request $request)
{
$email = $request->input('email');
$token = $request->input('token');
$verificationSessionToken = base64_encode($email . '|' . $token);
$sessionToken = Redis::get($token);
$isValid = $sessionToken === $verificationSessionToken;
// Check in session
if (!$isValid) {
return response()->error('Invalid verification session.');
}
// Get user
$user = User::where('email', $email)->first();
if ($user) {
// create verification code
VerificationCode::generateEmailVerificationFor($user);
} else {
return response()->error('No user found with provided email address.');
}
return response()->json([
'status' => 'success',
]);
}
/**
* Verfiy and validate an email address with code.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function verifyEmail(Request $request)
{
$authenticate = $request->boolean('authenticate');
$token = $request->input('token');
$email = $request->input('email');
$code = $request->input('code');
$verificationSessionToken = base64_encode($email . '|' . $token);
$sessionToken = Redis::get($token);
$isValid = $sessionToken === $verificationSessionToken;
// Check in session
if (!$isValid) {
return response()->error('Invalid verification session.');
}
// Check user
$user = User::where('email', $email)->first();
if (!$user) {
return response()->error('No user found with provided email.');
}
// If user is already verified
if ($user->isVerified()) {
return response()->error('User is already verified.');
}
// Verify the user using the verification code
try {
$user->verify($code);
} catch (InvalidVerificationCodeException $e) {
return response()->error('Invalid verification code.');
}
// Activate user
$user->activate();
// If authenticate is set, generate and return a token
if ($authenticate) {
$user->updateLastLogin();
$token = $user->createToken($user->uuid);
return response()->json([
'status' => 'ok',
'verified_at' => $user->getDateVerified(),
'token' => $token->plainTextToken,
]);
}
// Return success response without token
return response()->json([
'status' => 'ok',
'verified_at' => $user->getDateVerified(),
'token' => null,
]);
}
/**
* Allow user to verify SMS code.
*
* @param \\Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response $response
*/
public function verifySmsCode(Request $request)
{
// Users phone number
$phone = $request->input('phone');
// Users verfiy code entered
$verifyCode = $request->input('code');
$verifyCodeKey = Str::slug($phone . '_verify_code', '_');
// Generate hto
$storedVerifyCode = Redis::get($verifyCodeKey);
// Verify
if ($verifyCode === $storedVerifyCode) {
// Remove from redis
Redis::del($verifyCodeKey);
// 200 OK
return response()->json([
'status' => 'OK',
'message' => 'Code verified',
]);
}
// 400 ERROR
return response()->error('Invalid verification code');
}
/**
* Creates a new company and user account.
*
* @param \Fleetbase\Http\Requests\SigUpRequest $request
*
* @return \Illuminate\Http\Response
*/
public function signUp(SignUpRequest $request)
{
$userDetails = $request->input('user');
$companyDetails = $request->input('company');
$newUser = Auth::register($userDetails, $companyDetails);
$token = $newUser->createToken($newUser->uuid);
return response()->json(['token' => $token->plainTextToken]);
}
/**
* Initializes a password reset using a verification code.
*
* @return \Illuminate\Http\Response
*/
public function createPasswordReset(UserForgotPasswordRequest $request)
{
$user = User::where('email', $request->input('email'))->first();
// create verification code
$verificationCode = VerificationCode::create([
'subject_uuid' => $user->uuid,
'subject_type' => Utils::getModelClassName($user),
'for' => 'password_reset',
'expires_at' => Carbon::now()->addMinutes(15),
'status' => 'active',
]);
// notify user of password reset
$user->notify(new UserForgotPassword($verificationCode));
return response()->json(['status' => 'ok']);
}
/**
* Reset password.
*
* @return \Illuminate\Http\Response
*/
public function resetPassword(ResetPasswordRequest $request)
{
$verificationCode = VerificationCode::where('code', $request->input('code'))->with(['subject'])->first();
$link = $request->input('link');
$password = $request->input('password');
// If link isn't valid
if ($verificationCode->uuid !== $link) {
return response()->error('Invalid password reset request!');
}
// if no subject error
if (!isset($verificationCode->subject)) {
return response()->error('Invalid password reset request!');
}
// reset users password
$verificationCode->subject->changePassword($password);
// verify code by deleting so its unusable
$verificationCode->delete();
return response()->json(['status' => 'ok']);
}
/**
* Simple check if verificationc code is still valid.
*
* @return \Illuminate\Http\Response
*/
public function validateVerificationCode(Request $request)
{
$id = $request->input('id');
$valid = VerificationCode::where('uuid', $id)->exists();
return response()->json(['is_valid' => $valid, 'id' => $id]);
}
/**
* Takes a request username/ or email and password and attempts to authenticate user
* will return the user model if the authentication was successful, else will 400.
*
* @return \Illuminate\Http\Response
*/
public function getUserOrganizations(Request $request)
{
$user = $request->user();
$cacheKey = "user_organizations_{$user->uuid}";
// Cache for 30 minutes
$companies = Cache::remember($cacheKey, 60 * 30, function () use ($user) {
return Company::select([
'companies.uuid',
'companies.name',
'companies.phone',
'companies.options',
'companies.currency',
'companies.timezone',
'companies.status',
'companies.type',
'companies.owner_uuid',
'companies.created_at',
'companies.updated_at',
])
->join('company_users', 'companies.uuid', '=', 'company_users.company_uuid')
->where('company_users.user_uuid', $user->uuid)
->whereNull('company_users.deleted_at')
->whereNotNull('companies.owner_uuid')
->with([
'owner:uuid,company_uuid,name,email,updated_at',
'owner.companyUser:uuid,user_uuid,company_uuid,updated_at',
])
->distinct()
->get();
});
/**
* Generate a full ETag representing:
* - all org UUIDs
* - all org updated_at timestamps
* - count of organizations
*/
$etagPayload = $companies->map(function ($company) {
$ownerTimestamp = $company->owner?->updated_at?->timestamp ?? 0;
return $company->uuid . ':' . $company->updated_at->timestamp . ':' . $ownerTimestamp;
})->join('|');
// Add count to ETag (if orgs added/removed)
$etagPayload .= '|count:' . $companies->count();
$etag = sha1($etagPayload);
return Organization::collection($companies)
->response()
->setEtag($etag)
->header('Cache-Control', 'private, no-cache, must-revalidate');
}
/**
* Clear user organizations cache (call when org changes).
*
* @return void
*/
public static function clearUserOrganizationsCache(string $userUuid)
{
Cache::forget("user_organizations_{$userUuid}");
}
/**
* Allows a user to simply switch their organization.
*
* @return \Illuminate\Http\Response
*/
public function switchOrganization(SwitchOrganizationRequest $request)
{
$nextOrganization = $request->input('next');
$user = $request->user();
if ($nextOrganization === $user->company_uuid) {
return response()->json(
[
'errors' => ['User is already on this organizations session'],
]
);
}
if (!CompanyUser::where(['user_uuid' => $user->uuid, 'company_uuid' => $nextOrganization])->exists()) {
return response()->json(
[
'errors' => ['You do not belong to this organization'],
]
);
}
$user->assignCompanyFromId($nextOrganization);
Auth::setSession($user);
return response()->json(['status' => 'ok']);
}
/**
* Allows a user to join an organization.
*
* @return \Illuminate\Http\Response
*/
public function joinOrganization(JoinOrganizationRequest $request)
{
try {
$company = Company::where('public_id', $request->input('next'))->first();
$user = Auth::getUserFromSession($request);
// Make sure user has been invited to join organizations
$isAlreadyInvited = Invite::isAlreadySentToJoinCompany($user, $company);
if (!$isAlreadyInvited) {
return response()->error('User has not been invited to join this organization.');
}
// Make sure user isn't already a member of this organization
if ($company->uuid === $user->company_uuid) {
return response()->error('User is already a member of this organization.');
}
$company->assignUser($user);
Auth::setSession($user);
return response()->json(['status' => 'ok']);
} catch (\Exception $e) {
return response()->error(app()->hasDebugModeEnabled() ? $e->getMessage() : 'Unable to join organization.');
}
}
/**
* Allows user to create a new organization.
*
* @return \Illuminate\Http\Response
*/
public function createOrganization(Request $request)
{
$user = Auth::getUserFromSession($request);
$input = array_merge($request->only(['name', 'description', 'phone', 'email', 'currency', 'country', 'timezone']), ['owner_uuid' => $user->uuid]);
try {
$company = Company::create($input);
// Set company owner
$company->setOwner($user)->save();
// Assign user to organization
$user->assignCompany($company, 'Administrator');
$user->assignSingleRole('Administrator');
// Company onboarding is not necessary - set correct flags
$company->update([
'onboarding_completed_at' => now(),
'onboarding_completed_by_uuid' => $user->uuid,
]);
// Fire event that user created a new organization
event(new UserCreatedNewCompany($user, $company));
} catch (\Throwable $e) {
return response()->error($e->getMessage());
}
Auth::setSession($user);
return new Organization($company);
}
/**
* Returns all authorization services which provide schemas.
*
* @return \Illuminate\Http\Response
*/
public function services()
{
$schemas = Utils::getAuthSchemas();
$services = [];
foreach ($schemas as $schema) {
$services[] = $schema->name;
}
return response()->json(array_unique($services));
}
/**
* Change a user password.
*
* @return \Illuminate\Http\Response
*/
public function changeUserPassword(ChangePasswordRequest $request)
{
$user = Auth::getUserFromSession($request);
if (!$user) {
return response()->error('Not authorized to change user password.', 401);
}
$canChangePassword = $user->isAdmin() || $user->hasRole('Administrator') || $user->hasPermissionTo('iam change-password-for user');
if (!$canChangePassword) {
return response()->error('Not authorized to change user password.', 401);
}
// Get request input
$userId = $request->input('user');
$password = $request->input('password');
$confirmPassword = $request->input('password_confirmation');
$sendCredentials = $request->boolean('send_credentials');
if (!$userId) {
return response()->error('No user specified to change password for.');
}
if ($password !== $confirmPassword) {
return response()->error('Passwords do not match.');
}
$targetUser = User::where('uuid', $userId)->whereHas('anyCompanyUser', function ($query) {
$query->where('company_uuid', session('company'));
})->first();
if (!$targetUser) {
return response()->error('User not found to change password for.');
}
// Change password
$targetUser->changePassword($password);
// Send credentials to customer if opted
if ($sendCredentials) {
Mail::to($targetUser)->send(new UserCredentialsMail($password, $targetUser));
}
return response()->json(['status' => 'ok']);
}
/**
* Allows system admin to impersonate a user.
*
* @return \Illuminate\Http\Response
*/
public function impersonate(AdminRequest $request)
{
$currentUser = Auth::getUserFromSession($request);
if ($currentUser->isNotAdmin()) {
return response()->error('Not authorized to impersonate users.');
}
$targetUserId = $request->input('user');
if (!$targetUserId) {
return response()->error('Not target user selected to impersonate.');
}
$targetUser = User::where('uuid', $targetUserId)->first();
if (!$targetUser) {
return response()->error('The selected user to impersonate was not found.');
}
try {
Auth::setSession($targetUser);
session()->put('impersonator', $currentUser->uuid);
$token = $targetUser->createToken($targetUser->uuid);
} catch (\Exception $e) {
return response()->error($e->getMessage());
}
return response()->json(['status' => 'ok', 'token' => $token->plainTextToken]);
}
/**
* Ends the impersonation session.
*
* @return \Illuminate\Http\Response
*/
public function endImpersonation()
{
$impersonatorId = session()->get('impersonator');
if (!$impersonatorId) {
return response()->error('Not impersonator session found.');
}
$impersonator = User::where('uuid', $impersonatorId)->first();
if (!$impersonator) {
return response()->error('The impersonator user was not found.');
}
if ($impersonator->isNotAdmin()) {
return response()->error('The impersonator does not have permissions. Logout.');
}
try {
Auth::setSession($impersonator);
session()->remove('impersonator');
$token = $impersonator->createToken($impersonator->uuid);
} catch (\Exception $e) {
return response()->error($e->getMessage());
}
return response()->json(['status' => 'ok', 'token' => $token->plainTextToken]);
}
}