-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserController.php
More file actions
1209 lines (1070 loc) · 47.9 KB
/
Copy pathUserController.php
File metadata and controls
1209 lines (1070 loc) · 47.9 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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\OpenId\DiscoveryController;
use App\Http\Controllers\OpenId\OpenIdController;
use App\Http\Controllers\Traits\JsonResponses;
use App\Http\Controllers\Traits\MFACookieManager;
use App\Http\Utils\CountryList;
use App\libs\Auth\Models\TwoFactorAuditLog;
use App\libs\OAuth2\Strategies\LoginHintProcessStrategy;
use App\ModelSerializers\SerializerRegistry;
use App\Services\Auth\IDeviceTrustService;
use App\Services\Auth\IRecoveryCodeService;
use App\Services\Auth\ITwoFactorAuditService;
use App\Services\Auth\ITwoFactorGateService;
use App\Services\Auth\ITwoFactorRateLimitService;
use App\Services\Auth\IUserService as AuthUserService;
use Auth\Exceptions\AuthenticationException;
use Auth\Exceptions\UnverifiedEmailMemberException;
use Auth\MFAConstants;
use Auth\User;
use Exception;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use Models\OAuth2\Client;
use Models\OAuth2\OAuth2OTP;
use OAuth2\Factories\OAuth2AuthorizationRequestFactory;
use OAuth2\OAuth2Message;
use OAuth2\OAuth2Protocol;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Services\IMementoOAuth2SerializerService;
use OAuth2\Services\IResourceServerService;
use OAuth2\Services\ISecurityContextService;
use OAuth2\Services\ITokenService;
use OpenId\Services\IMementoOpenIdSerializerService;
use OpenId\Services\ITrustedSitesService;
use OpenId\Services\IUserService;
use RyanChandler\LaravelCloudflareTurnstile\Rules\Turnstile;
use Services\IUserActionService;
use Sokil\IsoCodes\IsoCodesFactory;
use Strategies\DefaultLoginStrategy;
use Strategies\IConsentStrategy;
use Strategies\MFA\MFAChallengeStrategyFactory;
use Strategies\OAuth2ConsentStrategy;
use Strategies\OAuth2LoginStrategy;
use Strategies\OpenIdConsentStrategy;
use Strategies\OpenIdLoginStrategy;
use Utils\IPHelper;
use Utils\Services\IAuthService;
use Utils\Services\IServerConfigurationService;
use Utils\Services\IServerConfigurationService as IUtilsServerConfigurationService;
/**
* Class UserController
* @package App\Http\Controllers
*/
final class UserController extends OpenIdController
{
/**
* @var IMementoOpenIdSerializerService
*/
private $openid_memento_service;
/**
* @var IMementoOAuth2SerializerService
*/
private $oauth2_memento_service;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IServerConfigurationService
*/
private $server_configuration_service;
/**
* @var DiscoveryController
*/
private $discovery;
/**
* @var IUserService
*/
private $user_service;
/**
* @var AuthUserService
*/
private $auth_user_service;
/**
* @var IUserActionService
*/
private $user_action_service;
/**
* @var DefaultLoginStrategy
*/
private $login_strategy;
/**
* @var IConsentStrategy
*/
private $consent_strategy;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IApiScopeRepository
*/
private $scope_repository;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IResourceServerService
*/
private $resource_server_service;
/**
* @var IUtilsServerConfigurationService
*/
private $utils_configuration_service;
/**
* @var ISecurityContextService
*/
private $security_context_service;
/**
* @var IDeviceTrustService
*/
private $device_trust_service;
/**
* @var ITwoFactorAuditService
*/
private $two_factor_audit_service;
/**
* @var ITwoFactorGateService
*/
private $mfa_gate_service;
/**
* @var ITwoFactorRateLimitService
*/
private $two_factor_rate_limit_service;
/**
* @var IRecoveryCodeService
*/
private $recovery_code_service;
/**
* @param IMementoOpenIdSerializerService $openid_memento_service
* @param IMementoOAuth2SerializerService $oauth2_memento_service
* @param IAuthService $auth_service
* @param IUtilsServerConfigurationService $server_configuration_service
* @param ITrustedSitesService $trusted_sites_service
* @param DiscoveryController $discovery
* @param IUserService $user_service
* @param AuthUserService $auth_user_service
* @param IUserActionService $user_action_service
* @param IClientRepository $client_repository
* @param IApiScopeRepository $scope_repository
* @param ITokenService $token_service
* @param IResourceServerService $resource_server_service
* @param IUtilsServerConfigurationService $utils_configuration_service
* @param ISecurityContextService $security_context_service
* @param LoginHintProcessStrategy $login_hint_process_strategy
*/
public function __construct
(
IMementoOpenIdSerializerService $openid_memento_service,
IMementoOAuth2SerializerService $oauth2_memento_service,
IAuthService $auth_service,
IServerConfigurationService $server_configuration_service,
ITrustedSitesService $trusted_sites_service,
DiscoveryController $discovery,
IUserService $user_service,
AuthUserService $auth_user_service,
IUserActionService $user_action_service,
IClientRepository $client_repository,
IApiScopeRepository $scope_repository,
ITokenService $token_service,
IResourceServerService $resource_server_service,
IUtilsServerConfigurationService $utils_configuration_service,
ISecurityContextService $security_context_service,
LoginHintProcessStrategy $login_hint_process_strategy,
IDeviceTrustService $device_trust_service,
ITwoFactorAuditService $two_factor_audit_service,
ITwoFactorGateService $mfa_gate_service,
ITwoFactorRateLimitService $two_factor_rate_limit_service,
IRecoveryCodeService $recovery_code_service,
)
{
$this->openid_memento_service = $openid_memento_service;
$this->oauth2_memento_service = $oauth2_memento_service;
$this->auth_service = $auth_service;
$this->server_configuration_service = $server_configuration_service;
$this->trusted_sites_service = $trusted_sites_service;
$this->discovery = $discovery;
$this->user_service = $user_service;
$this->auth_user_service = $auth_user_service;
$this->user_action_service = $user_action_service;
$this->client_repository = $client_repository;
$this->scope_repository = $scope_repository;
$this->token_service = $token_service;
$this->resource_server_service = $resource_server_service;
$this->utils_configuration_service = $utils_configuration_service;
$this->security_context_service = $security_context_service;
$this->device_trust_service = $device_trust_service;
$this->two_factor_audit_service = $two_factor_audit_service;
$this->mfa_gate_service = $mfa_gate_service;
$this->two_factor_rate_limit_service = $two_factor_rate_limit_service;
$this->recovery_code_service = $recovery_code_service;
$this->middleware(function ($request, $next) use($login_hint_process_strategy){
Log::debug(sprintf("UserController::middleware route %s %s", $request->getMethod(), $request->getRequestUri()));
if ($this->openid_memento_service->exists()) {
//openid stuff
Log::debug(sprintf("UserController::middleware OIDC"));
$this->login_strategy = new OpenIdLoginStrategy
(
$this->openid_memento_service,
$this->user_action_service,
$this->auth_service,
$login_hint_process_strategy
);
$this->consent_strategy = new OpenIdConsentStrategy
(
$this->openid_memento_service,
$this->auth_service,
$this->server_configuration_service,
$this->user_action_service
);
} else if ($this->oauth2_memento_service->exists()) {
Log::debug(sprintf("UserController::middleware OAUTH2"));
$this->login_strategy = new OAuth2LoginStrategy
(
$this->auth_service,
$this->oauth2_memento_service,
$this->user_action_service,
$login_hint_process_strategy
);
$this->consent_strategy = new OAuth2ConsentStrategy
(
$this->auth_service,
$this->oauth2_memento_service,
$this->scope_repository,
$this->client_repository
);
} else {
//default stuff
Log::debug(sprintf("UserController::middleware DEFAULT"));
$this->login_strategy = new DefaultLoginStrategy
(
$this->user_action_service,
$this->auth_service,
$login_hint_process_strategy
);
$this->consent_strategy = null;
}
return $next($request);
});
}
public function getLogin()
{
return $this->login_strategy->getLogin();
}
public function cancelLogin()
{
// A cancelled login must invalidate any pending MFA challenge server-side,
// not just reset the client's view of things - otherwise an OTP issued
// before cancel can still complete a login the user explicitly abandoned.
$method = Session::get('mfa_method');
if (!is_null($method)) {
MFAChallengeStrategyFactory::create($method)->clearPendingState();
}
$this->clearMFAUISessionState();
return $this->login_strategy->cancelLogin();
}
use JsonResponses;
use MFACookieManager;
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAccount()
{
try {
$email = Request::input("email", "");
if (empty($email)) {
throw new ValidationException("empty email.");
}
$user = $this->auth_service->getUserByUsername($email);
if (is_null($user))
throw new EntityNotFoundException();
return $this->ok(
[
'is_active' => $user->isActive(),
'is_verified' => $user->isEmailVerified(),
'pic' => $user->getPic(),
'full_name' => $user->getFullName(),
'has_password_set' => $user->hasPasswordSet(),
]
);
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function emitOTP()
{
try {
$username = Request::input("username", "");
$connection = Request::input("connection", "");
$send = Request::input("send", "");
if (empty($username)) {
throw new ValidationException("empty username param.");
}
if (empty($connection)) {
throw new ValidationException("empty connectin param.");
}
if (empty($send)) {
throw new ValidationException("empty send param.");
}
$client = null;
// check if we have a former oauth2 request
if ($this->oauth2_memento_service->exists()) {
Log::debug("UserController::getOTP exist a oauth auth request on session");
$oauth_auth_request = OAuth2AuthorizationRequestFactory::getInstance()->build
(
OAuth2Message::buildFromMemento($this->oauth2_memento_service->load())
);
if ($oauth_auth_request->isValid()) {
$client_id = $oauth_auth_request->getClientId();
$client = $this->client_repository->getClientById($client_id);
if (is_null($client))
throw new ValidationException("Client does not exists.");
$this->oauth2_memento_service->serialize($oauth_auth_request->getMessage()->createMemento());
}
}
$otp = $this->token_service->createOTPFromPayload([
OAuth2Protocol::OAuth2PasswordlessConnection => $connection,
OAuth2Protocol::OAuth2PasswordlessSend => $send,
OAuth2Protocol::OAuth2PasswordlessEmail => ($connection == OAuth2Protocol::OAuth2PasswordlessConnectionEmail) ? $username : null,
OAuth2Protocol::OAuth2PasswordlessPhoneNumber => ($connection == OAuth2Protocol::OAuth2PasswordlessConnectionSMS) ? $username : null
], $client);
// Restore-on-refresh: a subsequent GET /login can rehydrate the OTP
// screen from session instead of dropping back to the email form -
// same mechanism postLogin()'s MFA challengeRequired() branch already
// uses. user_verified is set unconditionally (not inside the
// existing-user lookup below) because loginWithOTP() auto-registers
// brand-new emails at redemption time; gating it on an existing user
// would silently break refresh-restoration for first-time passwordless
// users.
$existing_user = $this->auth_service->getUserByUsername($username);
Session::put('flow', IAuthService::AuthenticationFlowPasswordless);
Session::put('username', $username);
Session::put('user_verified', true);
// Mirrors login.js's emitOtpAction(), which falls back to the
// submitted email as the chip's display name when there's no real
// full name yet - persisting the same fallback here keeps the
// identity chip (visible right after opting into OTP) from
// vanishing on a refresh for a not-yet-registered email.
Session::put('user_fullname', !is_null($existing_user) ? $existing_user->getFullName() : $username);
Session::put('otp_length', $otp->getLength());
Session::put('otp_lifetime', $otp->getLifetime());
Session::put('otp_issued_at', $otp->getCreatedAt()?->getTimestamp() ?? time());
if (!is_null($existing_user)) {
Session::put('user_pic', $existing_user->getPic());
Session::put('user_is_active', $existing_user->isActive() ? 1 : 0);
}
return $this->created([
'otp_length' => $otp->getLength(),
'otp_lifetime' => $otp->getLifetime(),
]);
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function resendVerificationEmail(LaravelRequest $request)
{
try {
$payload = $request->all();
$validator = Validator::make($payload, [
'email' => 'required|string|email|max:255'
]);
if (!$validator->passes()) {
return $this->error412($validator->getMessageBag()->getMessages());
}
$this->auth_user_service->resendVerificationEmail($payload);
return $this->ok();
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function postLogin()
{
$max_login_attempts_2_show_captcha = $this->server_configuration_service->getConfigValue("MaxFailed.LoginAttempts.2ShowCaptcha");
$max_login_failed_attempts = intval($this->server_configuration_service->getConfigValue("MaxFailed.Login.Attempts"));
$login_attempts = 0;
$username = '';
$user = null;
try
{
$data = Request::all();
if (isset($data['username']))
$data['username'] = trim($data['username']);
if (isset($data['password']))
$data['password'] = trim($data['password']);
$login_attempts = intval(Request::input('login_attempts'));
// Build the validation constraint set.
$rules = [
'username' => 'required|email',
'password' => 'required',
'flow' => 'required|in:otp,password',
'connection' => 'sometimes|string|in:sms,email',
];
if ($login_attempts >= $max_login_attempts_2_show_captcha) {
$rules['cf-turnstile-response'] = ['required', new Turnstile()];
}
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
$username = $data['username'];
$password = $data['password'];
$flow = $data['flow'];
$remember = Request::input("remember");
$remember = !is_null($remember);
$connection = $data['connection'] ?? null;
try {
if ($flow == IAuthService::AuthenticationFlowPassword) {
// Validate credentials WITHOUT establishing a session, so the
// MFA gate can run before the user is authenticated.
$user = $this->auth_service->validateCredentials($username, $password);
$cookieToken = $this->getCookieToken();
if ($this->mfa_gate_service->requiresChallenge($user, $cookieToken)) {
// Initial issuance shares the resend rate-limit window
// (SDS idp-mfa.md §4.12) - without this, this route
// would be an unthrottled way to mail-bomb the account
// owner with OTP codes.
if ($this->two_factor_rate_limit_service->isRateLimited(
ITwoFactorRateLimitService::ActionResend,
$user->getId()
)) {
throw new AuthenticationException(ITwoFactorRateLimitService::RATE_LIMIT_MESSAGE);
}
// Issue a challenge and stop short of session creation.
$client = $this->resolveClientFromMemento();
$method = $user->getTwoFactorMethod();
$strategy = MFAChallengeStrategyFactory::create($method);
$payload = $this->auth_service->issueMFAChallenge($user, $strategy, $client, $remember);
$this->two_factor_rate_limit_service->increment(ITwoFactorRateLimitService::ActionResend, $user->getId());
// Best-effort: the challenge was already issued and the OTP
// sent, so an audit-logging failure must not 500 the user
// out of the mfa_required response they need to proceed.
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventChallengeIssued,
$method,
IPHelper::getUserIp()
);
} catch (\Throwable $ex) {
Log::warning($ex);
}
// Restore-on-refresh: a subsequent GET /login can rehydrate
// the 2FA screen from session instead of dropping back to the
// password form. otp_length/otp_lifetime (part of $payload)
// are flashed by challengeRequired() itself; flow/mfa_method
// aren't part of the challenge payload, so they're set here.
Session::put('flow', IAuthService::AuthenticationFlowMFA);
Session::put('mfa_method', $method);
// The password step now submits as a native form POST, so this
// response is a fresh page load, not a client-side transition -
// without these, the React app remounts with no identity state
// at all (no chip, and Cancel/session-expiry can't return to the
// password screen because it looks like the user was never
// verified). Same fields/getters as the AuthenticationException
// errorLogin() branch below.
$payload = array_merge($payload, [
'username' => $username,
'user_fullname' => $user->getFullName(),
'user_pic' => $user->getPic(),
'user_verified' => true,
'user_is_active' => $user->isActive() ? 1 : 0,
]);
return $this->login_strategy->challengeRequired($payload);
}
// No challenge required: establish the session and continue.
$this->auth_service->loginUser($user, $remember);
return $this->login_strategy->postLogin();
}
if ($flow == IAuthService::AuthenticationFlowPasswordless) {
$client = $this->resolveClientFromMemento();
$otpClaim = OAuth2OTP::fromParams($username, $connection, $password);
$this->auth_service->loginWithOTPEnforcing2FA($otpClaim, $client);
// A completed login must not leave the OTP screen restorable
// on a later refresh - same identity-leakage concern already
// fixed for the MFA flow's verify2FA()/verify2FARecovery().
$this->clearMFAUISessionState();
return $this->login_strategy->postLogin();
}
} catch (AuthenticationException $ex) {
// failed login attempt...
$user = $this->auth_service->getUserByUsername($username);
if (!is_null($user)) {
$login_attempts = $user->getLoginFailedAttempt();
}
return $this->login_strategy->errorLogin
(
[
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'max_login_failed_attempts' => $max_login_failed_attempts,
'login_attempts' => $login_attempts,
'error_message' => $ex->getMessage(),
'user_fullname' => !is_null($user) ? $user->getFullName() : "",
'user_pic' => !is_null($user) ? $user->getPic(): "",
'user_verified' => true,
'username' => $username,
'flow' => $flow,
'user_is_active' => !is_null($user) ? ($user->isActive() ? 1 : 0) : 0
]
);
}
}
// validator errors
$response_data = [
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'max_login_failed_attempts' => $max_login_failed_attempts,
'login_attempts' => $login_attempts,
'validator' => $validator,
];
if (is_null($user) && isset($data['username'])) {
$user = $this->auth_service->getUserByUsername($data['username']);
}
if(!is_null($user)){
$response_data['user_fullname'] = $user->getFullName();
$response_data['user_pic'] = $user->getPic();
$response_data['user_verified'] = 1;
$response_data['user_is_active'] = $user->isActive() ? 1 : 0;
}
return $this->login_strategy->errorLogin
(
$response_data
);
} catch (UnverifiedEmailMemberException $ex1) {
Log::warning($ex1);
$user = $this->auth_service->getUserByUsername($username);
$response_data = [
'max_login_attempts_2_show_captcha' => $max_login_attempts_2_show_captcha,
'max_login_failed_attempts' => $max_login_failed_attempts,
'login_attempts' => $login_attempts,
'username' => $username,
'error_message' => $ex1->getMessage(),
];
if (is_null($user) && isset($data['username'])) {
$user = $this->auth_service->getUserByUsername($data['username']);
}
if(!is_null($user)){
$response_data['user_fullname'] = $user->getFullName();
$response_data['user_pic'] = $user->getPic();
$response_data['user_verified'] = 1;
$response_data['user_is_active'] = $user->isActive() ? 1 : 0;
}
return $this->login_strategy->errorLogin
(
$response_data
);
} catch (AuthenticationException $ex2) {
Log::warning($ex2);
return Redirect::action('UserController@getLogin');
} catch (Exception $ex) {
Log::error($ex);
return Redirect::action('UserController@getLogin');
}
}
/**
* Resolves the OAuth2 client from a former authorization request stored in
* the session memento, if any. Returns null when there is no pending OAuth2
* request (e.g. plain IdP login).
*
* @return Client|null
* @throws ValidationException
*/
private function resolveClientFromMemento(): ?Client
{
if (!$this->oauth2_memento_service->exists()) {
return null;
}
Log::debug("UserController::resolveClientFromMemento exist a oauth auth request on session");
$oauth_auth_request = OAuth2AuthorizationRequestFactory::getInstance()->build
(
OAuth2Message::buildFromMemento($this->oauth2_memento_service->load())
);
if (!$oauth_auth_request->isValid()) {
return null;
}
$client = $this->client_repository->getClientById($oauth_auth_request->getClientId());
if (is_null($client))
throw new ValidationException("client does not exists");
$this->oauth2_memento_service->serialize($oauth_auth_request->getMessage()->createMemento());
return $client;
}
/**
* Verifies a 2FA OTP challenge and, on success, establishes the session.
*
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function verify2FA()
{
try {
$data = Request::all();
$validator = Validator::make($data, [
'otp_value' => 'required|string',
'method' => 'required|string|in:' . implode(',', User::ValidMFAMethods),
'trust_device' => 'sometimes|boolean',
]);
if (!$validator->passes()) {
return $this->error412($validator->getMessageBag()->getMessages());
}
$method = $data['method'];
$otp_value = $data['otp_value'];
$trust_device = Request::boolean('trust_device');
$strategy = MFAChallengeStrategyFactory::create($method);
$pending = $strategy->getPendingState();
if (is_null($pending)) {
return $this->mfaSessionExpired();
}
$user = $this->auth_service->getUserById($pending->getUserId());
if (is_null($user) || !$user->isTwoFactorMethodEnabled($method)) {
$strategy->clearPendingState();
return $this->mfaSessionExpired();
}
// Scope verification to the client the challenge was issued for.
$client = $this->resolveClientFromMemento();
try {
// Commits the OTP redeem (+ sibling revoke) in its own tx. The
// session, trusted-device enrollment and audit are applied below
// as separate post-verification steps.
$this->auth_service->verifyMFAChallenge(
$user,
$strategy,
$otp_value,
$client
);
} catch (AuthenticationException $ex) {
Log::warning($ex);
// Re-fetch user: the tx wrapper closed/reset the EM on failure, detaching the entity.
$userId = $pending->getUserId();
$user = $this->auth_service->getUserById($userId) ?? $user;
// Best-effort: an audit-logging failure here must not turn a
// clean 401 into a 500 (which would also drop the error_code
// the rate-limit middleware keys its failure count on).
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventChallengeFailed,
$method,
IPHelper::getUserIp()
);
} catch (\Throwable $auditEx) {
Log::warning($auditEx);
}
return $this->unauthorized(['error_code' => MFAConstants::ERROR_CODE_VERIFICATION_FAILED]);
}
// Second factor verified: establish the session.
$this->auth_service->loginUser($user, $pending->shouldRemember());
if ($trust_device) {
// Best-effort: the OTP is already redeemed and the session
// established, so a trusted-device enrollment failure must not
// 500 the user (which would lock them out on retry against a
// burned OTP). Log and continue; the device just isn't remembered.
try {
$this->queueDeviceTrustCookie($user);
} catch (\Throwable $ex) {
Log::warning($ex);
}
}
$strategy->clearPendingState();
$this->clearMFAUISessionState();
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventChallengeSucceeded,
$method,
IPHelper::getUserIp()
);
} catch (\Throwable $ex) {
Log::warning($ex);
}
// Return the same-origin post-login destination as data instead of a raw
// redirect for this XHR to follow: postLogin() can chain into a cross-origin
// hop (authorization code delivery to an already-consented OAuth2 client),
// which no XHR/fetch can read past - and per InteractiveGrantType::handle()'s
// consent-bypass branch, that hop also consumes the OAuth2 memento as a side
// effect, so a silently-failed XHR follow-through burns the authorization
// code with no way to recover it client-side. A real top-level navigation to
// this URL lets the browser complete that chain natively instead - CORS never
// applies to page navigations, only to XHR/fetch.
$redirect = $this->login_strategy->postLogin();
return $this->ok(['redirect_url' => $redirect->getTargetUrl()]);
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* Verifies a 2FA recovery code and, on success, establishes the session.
*
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function verify2FARecovery()
{
try {
$data = Request::all();
$validator = Validator::make($data, [
'recovery_code' => 'required|string',
]);
if (!$validator->passes()) {
return $this->error412($validator->getMessageBag()->getMessages());
}
$recovery_code = $data['recovery_code'];
// Recovery-code handling lives in the base strategy; session keys are
// method-agnostic, so any concrete strategy can read the pending state.
$strategy = MFAChallengeStrategyFactory::create(User::MFAMethod_OTP);
$pending = $strategy->getPendingState();
if (is_null($pending)) {
return $this->mfaSessionExpired();
}
$user = $this->auth_service->getUserById($pending->getUserId());
if (is_null($user)) {
$strategy->clearPendingState();
return $this->mfaSessionExpired();
}
// Same guard verify2FA() applies before redeeming: a pending OAuth2
// authorization request must still resolve to an existing client,
// or the single-use recovery code would be burned (and a session
// established) for an authorization request that can only fail at
// the /oauth2/auth hop. Recovery-code checking itself is
// client-agnostic, so the resolved client is not passed down.
$this->resolveClientFromMemento();
try {
$this->auth_service->verifyMFARecoveryCode($user, $strategy, $recovery_code);
} catch (AuthenticationException $ex) {
Log::warning($ex);
// Re-fetch user: the tx wrapper closed/reset the EM on failure, detaching the entity.
$userId = $pending->getUserId();
$user = $this->auth_service->getUserById($userId) ?? $user;
// Best-effort: see verify2FA() for rationale.
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventChallengeFailed,
TwoFactorAuditLog::MethodRecovery,
IPHelper::getUserIp()
);
} catch (\Throwable $auditEx) {
Log::warning($auditEx);
}
return $this->unauthorized(['error_code' => MFAConstants::ERROR_CODE_INVALID_RECOVERY]);
}
$this->auth_service->loginUser($user, $pending->shouldRemember());
$strategy->clearPendingState();
$this->clearMFAUISessionState();
// Best-effort: the recovery code is already redeemed and the session
// established, so an audit-logging failure must not 500 the user
// (which would strand them after burning their last-resort code).
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventRecoveryUsed,
TwoFactorAuditLog::MethodRecovery,
IPHelper::getUserIp()
);
} catch (\Throwable $ex) {
Log::warning($ex);
}
// See verify2FA() for rationale: return the destination as data so a real
// top-level navigation (not this XHR) performs any cross-origin hop. The
// recovery-codes standing rides along so the login page can warn the user
// when they've just burned into their last few codes (see RecoveryCodesStatus).
$redirect = $this->login_strategy->postLogin();
return $this->ok(array_merge(
['redirect_url' => $redirect->getTargetUrl()],
$this->recovery_code_service->getStatus($user)->toArray()
));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* Re-issues a 2FA challenge for the pending login and returns the challenge payload.
*
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function resend2FA()
{
try {
$data = Request::all();
$validator = Validator::make($data, [
'method' => 'required|string|in:' . implode(',', User::ValidMFAMethods),
]);
if (!$validator->passes()) {
return $this->error412($validator->getMessageBag()->getMessages());
}
$method = $data['method'];
$strategy = MFAChallengeStrategyFactory::create($method);
$pending = $strategy->getPendingState();
if (is_null($pending)) {
return $this->mfaSessionExpired();
}
$user = $this->auth_service->getUserById($pending->getUserId());
if (is_null($user) || !$user->isTwoFactorMethodEnabled($method)) {
$strategy->clearPendingState();
return $this->mfaSessionExpired();
}
$payload = $this->auth_service->resendMFAChallenge($user, $strategy, $this->resolveClientFromMemento(), $pending->shouldRemember());
// Keep the refresh-restorable session state in sync with the
// fresh challenge (e.g. otp_lifetime countdown resets on resend,
// mfa_method changes if this resend is actually a method switch).
Session::put('mfa_method', $method);
if (isset($payload['otp_length'])) {
Session::put('otp_length', $payload['otp_length']);
}
if (isset($payload['otp_lifetime'])) {
Session::put('otp_lifetime', $payload['otp_lifetime']);
}
if (isset($payload['otp_issued_at'])) {
Session::put('otp_issued_at', $payload['otp_issued_at']);
}
// Best-effort: the challenge was already re-issued and the OTP
// sent, so an audit-logging failure must not 500 the user out of
// the payload they need to complete verification.
try {
$this->two_factor_audit_service->log(
$user,
TwoFactorAuditLog::EventChallengeIssued,
$method,
IPHelper::getUserIp()
);