-
-
Notifications
You must be signed in to change notification settings - Fork 365
/
Copy pathAccountController.php
1308 lines (1071 loc) · 49.1 KB
/
AccountController.php
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
/**
* UserFrosting (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/UserFrosting
* @copyright Copyright (c) 2019 Alexander Weissman
* @license https://github.com/userfrosting/UserFrosting/blob/master/LICENSE.md (MIT License)
*/
namespace UserFrosting\Sprinkle\Account\Controller;
use Carbon\Carbon;
use Illuminate\Database\Capsule\Manager as Capsule;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UserFrosting\Fortress\RequestDataTransformer;
use UserFrosting\Fortress\RequestSchema;
use UserFrosting\Fortress\ServerSideValidator;
use UserFrosting\Fortress\Adapter\JqueryValidationAdapter;
use UserFrosting\Sprinkle\Account\Account\Registration;
use UserFrosting\Sprinkle\Account\Controller\Exception\SpammyRequestException;
use UserFrosting\Sprinkle\Account\Facades\Password;
use UserFrosting\Sprinkle\Account\Util\Util as AccountUtil;
use UserFrosting\Sprinkle\Core\Controller\SimpleController;
use UserFrosting\Sprinkle\Core\Mail\EmailRecipient;
use UserFrosting\Sprinkle\Core\Mail\TwigMailMessage;
use UserFrosting\Sprinkle\Core\Util\Captcha;
use UserFrosting\Support\Exception\BadRequestException;
use UserFrosting\Support\Exception\ForbiddenException;
use UserFrosting\Support\Exception\NotFoundException;
/**
* Controller class for /account/* URLs. Handles account-related activities, including login, registration, password recovery, and account settings.
*
* @author Alex Weissman (https://alexanderweissman.com)
* @see http://www.userfrosting.com/navigating/#structure
*/
class AccountController extends SimpleController
{
/**
* Check a username for availability.
*
* This route is throttled by default, to discourage abusing it for account enumeration.
* This route is "public access".
*
* AuthGuard: false
* Route: /account/check-username
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
* @throws BadRequestException
*/
public function checkUsername(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
// GET parameters
$params = $request->getQueryParams();
// Load request schema
$schema = new RequestSchema('schema://requests/check-username.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
// Validate, and halt on validation errors.
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
// TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException
$e = new BadRequestException('Missing or malformed request data!');
foreach ($validator->errors() as $idx => $field) {
foreach ($field as $eidx => $error) {
$e->addUserMessage($error);
}
}
throw $e;
}
/** @var \UserFrosting\Sprinkle\Core\Throttle\Throttler $throttler */
$throttler = $this->ci->throttler;
$delay = $throttler->getDelay('check_username_request');
// Throttle requests
if ($delay > 0) {
return $response->withJson([], 429);
}
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
/** @var \UserFrosting\I18n\MessageTranslator $translator */
$translator = $this->ci->translator;
// Log throttleable event
$throttler->logEvent('check_username_request');
if ($classMapper->staticMethod('user', 'findUnique', $data['user_name'], 'user_name')) {
$message = $translator->translate('USERNAME.NOT_AVAILABLE', $data);
return $response->write($message)->withStatus(200);
} else {
return $response->write('true')->withStatus(200);
}
}
/**
* Processes a request to cancel a password reset request.
*
* This is provided so that users can cancel a password reset request, if they made it in error or if it was not initiated by themselves.
* Processes the request from the password reset link, checking that:
* 1. The provided token is associated with an existing user account, who has a pending password reset request.
*
* AuthGuard: false
* Route: /account/set-password/deny
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function denyResetPassword(Request $request, Response $response, $args)
{
// GET parameters
$params = $request->getQueryParams();
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
$loginPage = $this->ci->router->pathFor('login');
// Load validation rules
$schema = new RequestSchema('schema://requests/deny-password.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
// Validate, and halt on validation errors. Since this is a GET request, we need to redirect on failure
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
return $response->withRedirect($loginPage);
}
$passwordReset = $this->ci->repoPasswordReset->cancel($data['token']);
if (!$passwordReset) {
$ms->addMessageTranslated('danger', 'PASSWORD.FORGET.INVALID');
return $response->withRedirect($loginPage);
}
$ms->addMessageTranslated('success', 'PASSWORD.FORGET.REQUEST_CANNED');
return $response->withRedirect($loginPage);
}
/**
* Processes a request to email a forgotten password reset link to the user.
*
* Processes the request from the form on the "forgot password" page, checking that:
* 1. The rate limit for this type of request is being observed.
* 2. The provided email address belongs to a registered account;
* 3. The submitted data is valid.
* Note that we have removed the requirement that a password reset request not already be in progress.
* This is because we need to allow users to re-request a reset, even if they lose the first reset email.
* This route is "public access".
* @todo require additional user information
* @todo prevent password reset requests for root account?
*
* AuthGuard: false
* Route: /account/forgot-password
* Route Name: {none}
* Request type: POST
* @param Request $request
* @param Response $response
* @param array $args
*/
public function forgotPassword(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// Get POST parameters
$params = $request->getParsedBody();
// Load the request schema
$schema = new RequestSchema('schema://requests/forgot-password.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
// Validate, and halt on validation errors. Failed validation attempts do not count towards throttling limit.
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
return $response->withJson([], 400);
}
// Throttle requests
/** @var \UserFrosting\Sprinkle\Core\Throttle\Throttler $throttler */
$throttler = $this->ci->throttler;
$throttleData = [
'email' => $data['email']
];
$delay = $throttler->getDelay('password_reset_request', $throttleData);
if ($delay > 0) {
$ms->addMessageTranslated('danger', 'RATE_LIMIT_EXCEEDED', ['delay' => $delay]);
return $response->withJson([], 429);
}
// All checks passed! log events/activities, update user, and send email
// Begin transaction - DB will be rolled back if an exception occurs
Capsule::transaction(function () use ($classMapper, $data, $throttler, $throttleData, $config) {
// Log throttleable event
$throttler->logEvent('password_reset_request', $throttleData);
// Load the user, by email address
$user = $classMapper->staticMethod('user', 'where', 'email', $data['email'])->first();
// Check that the email exists.
// If there is no user with that email address, we should still pretend like we succeeded, to prevent account enumeration
if ($user) {
// Try to generate a new password reset request.
// Use timeout for "reset password"
$passwordReset = $this->ci->repoPasswordReset->create($user, $config['password_reset.timeouts.reset']);
// Create and send email
$message = new TwigMailMessage($this->ci->view, 'mail/password-reset.html.twig');
$message->from($config['address_book.admin'])
->addEmailRecipient(new EmailRecipient($user->email, $user->full_name))
->addParams([
'user' => $user,
'token' => $passwordReset->getToken(),
'request_date' => Carbon::now()->format('Y-m-d H:i:s')
]);
$this->ci->mailer->send($message);
}
});
// TODO: create delay to prevent timing-based attacks
$ms->addMessageTranslated('success', 'PASSWORD.FORGET.REQUEST_SENT', ['email' => $data['email']]);
return $response->withJson([], 200);
}
/**
* Returns a modal containing account terms of service.
*
* This does NOT render a complete page. Instead, it renders the HTML for the form, which can be embedded in other pages.
*
* AuthGuard: false
* Route: /modals/account/tos
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function getModalAccountTos(Request $request, Response $response, $args)
{
return $this->ci->view->render($response, 'modals/tos.html.twig');
}
/**
* Generate a random captcha, store it to the session, and return the captcha image.
*
* AuthGuard: false
* Route: /account/captcha
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function imageCaptcha(Request $request, Response $response, $args)
{
$captcha = new Captcha($this->ci->session, $this->ci->config['session.keys.captcha']);
$captcha->generateRandomCode();
return $response->withStatus(200)
->withHeader('Content-Type', 'image/png;base64')
->write($captcha->getImage());
}
/**
* Processes an account login request.
*
* Processes the request from the form on the login page, checking that:
* 1. The user is not already logged in.
* 2. The rate limit for this type of request is being observed.
* 3. Email login is enabled, if an email address was used.
* 4. The user account exists.
* 5. The user account is enabled and verified.
* 6. The user entered a valid username/email and password.
* This route, by definition, is "public access".
*
* AuthGuard: false
* Route: /account/login
* Route Name: {none}
* Request type: POST
* @param Request $request
* @param Response $response
* @param array $args
*/
public function login(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
$currentUser = $this->ci->currentUser;
/** @var \UserFrosting\Sprinkle\Account\Authenticate\Authenticator $authenticator */
$authenticator = $this->ci->authenticator;
// Return 200 success if user is already logged in
if ($authenticator->check()) {
$ms->addMessageTranslated('warning', 'LOGIN.ALREADY_COMPLETE');
return $response->withJson([], 200);
}
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// Get POST parameters
$params = $request->getParsedBody();
// Load the request schema
$schema = new RequestSchema('schema://requests/login.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
// Validate, and halt on validation errors. Failed validation attempts do not count towards throttling limit.
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
return $response->withJson([], 400);
}
// Determine whether we are trying to log in with an email address or a username
$isEmail = filter_var($data['user_name'], FILTER_VALIDATE_EMAIL);
// Throttle requests
/** @var \UserFrosting\Sprinkle\Core\Throttle\Throttler $throttler */
$throttler = $this->ci->throttler;
$userIdentifier = $data['user_name'];
$throttleData = [
'user_identifier' => $userIdentifier
];
$delay = $throttler->getDelay('sign_in_attempt', $throttleData);
if ($delay > 0) {
$ms->addMessageTranslated('danger', 'RATE_LIMIT_EXCEEDED', [
'delay' => $delay
]);
return $response->withJson([], 429);
}
// Log throttleable event
$throttler->logEvent('sign_in_attempt', $throttleData);
// If credential is an email address, but email login is not enabled, raise an error.
// Note that we do this after logging throttle event, so this error counts towards throttling limit.
if ($isEmail && !$config['site.login.enable_email']) {
$ms->addMessageTranslated('danger', 'USER_OR_PASS_INVALID');
return $response->withJson([], 403);
}
// Try to authenticate the user. Authenticator will throw an exception on failure.
/** @var \UserFrosting\Sprinkle\Account\Authenticate\Authenticator $authenticator */
$authenticator = $this->ci->authenticator;
$currentUser = $authenticator->attempt(($isEmail ? 'email' : 'user_name'), $userIdentifier, $data['password'], $data['rememberme']);
$ms->addMessageTranslated('success', 'WELCOME', $currentUser->export());
// Set redirect, if relevant
$redirectOnLogin = $this->ci->get('redirect.onLogin');
return $redirectOnLogin($request, $response, $args);
}
/**
* Log the user out completely, including destroying any "remember me" token.
*
* AuthGuard: true
* Route: /account/logout
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function logout(Request $request, Response $response, $args)
{
// Destroy the session
$this->ci->authenticator->logout();
// Return to home page
$config = $this->ci->config;
return $response->withStatus(302)->withHeader('Location', $config['site.uri.public']);
}
/**
* Render the "forgot password" page.
*
* This creates a simple form to allow users who forgot their password to have a time-limited password reset link emailed to them.
* By default, this is a "public page" (does not require authentication).
*
* AuthGuard: false
* Route: /account/forgot-password
* Route Name: forgot-password
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function pageForgotPassword(Request $request, Response $response, $args)
{
// Load validation rules
$schema = new RequestSchema('schema://requests/forgot-password.yaml');
$validator = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'pages/forgot-password.html.twig', [
'page' => [
'validators' => [
'forgot_password' => $validator->rules('json', false)
]
]
]);
}
/**
* Render the account registration page for UserFrosting.
*
* This allows new (non-authenticated) users to create a new account for themselves on your website (if enabled).
* By definition, this is a "public page" (does not require authentication).
*
* AuthGuard: false
* checkEnvironment
* Route: /account/register
* Route Name: register
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
* @throws NotFoundException If site registration is disabled
*/
public function pageRegister(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
/** @var \UserFrosting\I18n\LocalePathBuilder */
$localePathBuilder = $this->ci->localePathBuilder;
if (!$config['site.registration.enabled']) {
throw new NotFoundException();
}
/** @var \UserFrosting\Sprinkle\Account\Authenticate\Authenticator $authenticator */
$authenticator = $this->ci->authenticator;
// Redirect if user is already logged in
if ($authenticator->check()) {
$redirect = $this->ci->get('redirect.onAlreadyLoggedIn');
return $redirect($request, $response, $args);
}
// Load validation rules
$schema = new RequestSchema('schema://requests/register.yaml');
$validatorRegister = new JqueryValidationAdapter($schema, $this->ci->translator);
// Get locale information
$currentLocales = $localePathBuilder->getLocales();
return $this->ci->view->render($response, 'pages/register.html.twig', [
'page' => [
'validators' => [
'register' => $validatorRegister->rules('json', false)
]
],
'locales' => [
'available' => $config['site.locales.available'],
'current' => end($currentLocales)
]
]);
}
/**
* Render the "resend verification email" page.
*
* This is a form that allows users who lost their account verification link to have the link resent to their email address.
* By default, this is a "public page" (does not require authentication).
*
* AuthGuard: false
* Route: /account/resend-verification
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function pageResendVerification(Request $request, Response $response, $args)
{
// Load validation rules
$schema = new RequestSchema('schema://requests/resend-verification.yaml');
$validator = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'pages/resend-verification.html.twig', [
'page' => [
'validators' => [
'resend_verification' => $validator->rules('json', false)
]
]
]);
}
/**
* Reset password page.
*
* Renders the new password page for password reset requests.
*
* AuthGuard: false
* Route: /account/set-password/confirm
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function pageResetPassword(Request $request, Response $response, $args)
{
// Insert the user's secret token from the link into the password reset form
$params = $request->getQueryParams();
// Load validation rules - note this uses the same schema as "set password"
$schema = new RequestSchema('schema://requests/set-password.yaml');
$validator = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'pages/reset-password.html.twig', [
'page' => [
'validators' => [
'set_password' => $validator->rules('json', false)
]
],
'token' => isset($params['token']) ? $params['token'] : '',
]);
}
/**
* Render the "set password" page.
*
* Renders the page where new users who have had accounts created for them by another user, can set their password.
* By default, this is a "public page" (does not require authentication).
*
* AuthGuard: false
* Route:
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function pageSetPassword(Request $request, Response $response, $args)
{
// Insert the user's secret token from the link into the password set form
$params = $request->getQueryParams();
// Load validation rules
$schema = new RequestSchema('schema://requests/set-password.yaml');
$validator = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'pages/set-password.html.twig', [
'page' => [
'validators' => [
'set_password' => $validator->rules('json', false)
]
],
'token' => isset($params['token']) ? $params['token'] : '',
]);
}
/**
* Account settings page.
*
* Provides a form for users to modify various properties of their account, such as name, email, locale, etc.
* Any fields that the user does not have permission to modify will be automatically disabled.
* This page requires authentication.
*
* AuthGuard: true
* Route: /account/settings
* Route Name: {none}
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
* @throws ForbiddenException If user is not authozied to access page
*/
public function pageSettings(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager */
$authorizer = $this->ci->authorizer;
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
$currentUser = $this->ci->currentUser;
// Access-controlled page
if (!$authorizer->checkAccess($currentUser, 'uri_account_settings')) {
throw new ForbiddenException();
}
// Load validation rules
$schema = new RequestSchema('schema://requests/account-settings.yaml');
$validatorAccountSettings = new JqueryValidationAdapter($schema, $this->ci->translator);
$schema = new RequestSchema('schema://requests/profile-settings.yaml');
$validatorProfileSettings = new JqueryValidationAdapter($schema, $this->ci->translator);
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// Get a list of all locales
$locales = $config->getDefined('site.locales.available');
return $this->ci->view->render($response, 'pages/account-settings.html.twig', [
'locales' => $locales,
'page' => [
'validators' => [
'account_settings' => $validatorAccountSettings->rules('json', false),
'profile_settings' => $validatorProfileSettings->rules('json', false)
],
'visibility' => ($authorizer->checkAccess($currentUser, 'update_account_settings') ? '' : 'disabled')
]
]);
}
/**
* Render the account sign-in page for UserFrosting.
*
* This allows existing users to sign in.
* By definition, this is a "public page" (does not require authentication).
*
* AuthGuard: false
* checkEnvironment
* Route: /account/sign-in
* Route Name: login
* Request type: GET
* @param Request $request
* @param Response $response
* @param array $args
*/
public function pageSignIn(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
/** @var \UserFrosting\Sprinkle\Account\Authenticate\Authenticator $authenticator */
$authenticator = $this->ci->authenticator;
// Redirect if user is already logged in
if ($authenticator->check()) {
$redirect = $this->ci->get('redirect.onAlreadyLoggedIn');
return $redirect($request, $response, $args);
}
// Load validation rules
$schema = new RequestSchema('schema://requests/login.yaml');
$validatorLogin = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'pages/sign-in.html.twig', [
'page' => [
'validators' => [
'login' => $validatorLogin->rules('json', false)
]
]
]);
}
/**
* Processes a request to update a user's profile information.
*
* Processes the request from the user profile settings form, checking that:
* 1. They have the necessary permissions to update the posted field(s);
* 2. The submitted data is valid.
* This route requires authentication.
*
* AuthGuard: true
* Route: /account/settings/profile
* Route Name: {none}
* Request type: POST
* @param Request $request
* @param Response $response
* @param array $args
*/
public function profile(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager */
$authorizer = $this->ci->authorizer;
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
$currentUser = $this->ci->currentUser;
// Access control for entire resource - check that the current user has permission to modify themselves
// See recipe "per-field access control" for dynamic fine-grained control over which properties a user can modify.
if (!$authorizer->checkAccess($currentUser, 'update_account_settings')) {
$ms->addMessageTranslated('danger', 'ACCOUNT.ACCESS_DENIED');
return $response->withJson([], 403);
}
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// POST parameters
$params = $request->getParsedBody();
// Load the request schema
$schema = new RequestSchema('schema://requests/profile-settings.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
$error = false;
// Validate, and halt on validation errors.
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
$error = true;
}
// Check that locale is valid
$locales = $config->getDefined('site.locales.available');
if (!array_key_exists($data['locale'], $locales)) {
$ms->addMessageTranslated('danger', 'LOCALE.INVALID', $data);
$error = true;
}
if ($error) {
return $response->withJson([], 400);
}
// Looks good, let's update with new values!
// Note that only fields listed in `profile-settings.yaml` will be permitted in $data, so this prevents the user from updating all columns in the DB
$currentUser->fill($data);
$currentUser->save();
// Create activity record
$this->ci->userActivityLogger->info("User {$currentUser->user_name} updated their profile settings.", [
'type' => 'update_profile_settings'
]);
$ms->addMessageTranslated('success', 'PROFILE.UPDATED');
return $response->withJson([], 200);
}
/**
* Processes an new account registration request.
*
* This is throttled to prevent account enumeration, since it needs to divulge when a username/email has been used.
* Processes the request from the form on the registration page, checking that:
* 1. The honeypot was not modified;
* 2. The master account has already been created (during installation);
* 3. Account registration is enabled;
* 4. The user is not already logged in;
* 5. Valid information was entered;
* 6. The captcha, if enabled, is correct;
* 7. The username and email are not already taken.
* Automatically sends an activation link upon success, if account activation is enabled.
* This route is "public access".
* Returns the User Object for the user record that was created.
*
* AuthGuard: false
* Route: /account/register
* Route Name: {none}
* Request type: POST
* @param Request $request
* @param Response $response
* @param array $args
* @throws SpammyRequestException
*/
public function register(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// Get POST parameters: user_name, first_name, last_name, email, password, passwordc, captcha, spiderbro, csrf_token
$params = $request->getParsedBody();
// Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
if (!isset($params['spiderbro']) || $params['spiderbro'] != 'http://') {
throw new SpammyRequestException('Possible spam received:' . print_r($params, true));
}
// Security measure: do not allow registering new users until the master account has been created.
if (!$classMapper->staticMethod('user', 'find', $config['reserved_user_ids.master'])) {
$ms->addMessageTranslated('danger', 'ACCOUNT.MASTER_NOT_EXISTS');
return $response->withJson([], 403);
}
// Check if registration is currently enabled
if (!$config['site.registration.enabled']) {
$ms->addMessageTranslated('danger', 'REGISTRATION.DISABLED');
return $response->withJson([], 403);
}
/** @var \UserFrosting\Sprinkle\Account\Authenticate\Authenticator $authenticator */
$authenticator = $this->ci->authenticator;
// Prevent the user from registering if he/she is already logged in
if ($authenticator->check()) {
$ms->addMessageTranslated('danger', 'REGISTRATION.LOGOUT');
return $response->withJson([], 403);
}
// Load the request schema
$schema = new RequestSchema('schema://requests/register.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
$error = false;
// Validate request data
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
$error = true;
}
/** @var \UserFrosting\Sprinkle\Core\Throttle\Throttler $throttler */
$throttler = $this->ci->throttler;
$delay = $throttler->getDelay('registration_attempt');
// Throttle requests
if ($delay > 0) {
return $response->withJson([], 429);
}
// Check captcha, if required
if ($config['site.registration.captcha']) {
$captcha = new Captcha($this->ci->session, $this->ci->config['session.keys.captcha']);
if (!$data['captcha'] || !$captcha->verifyCode($data['captcha'])) {
$ms->addMessageTranslated('danger', 'CAPTCHA.FAIL');
$error = true;
}
}
if ($error) {
return $response->withJson([], 400);
}
// Remove captcha, password confirmation from object data after validation
unset($data['captcha']);
unset($data['passwordc']);
// Now that we check the form, we can register the actual user
$registration = new Registration($this->ci, $data);
try {
$user = $registration->register();
} catch (\Exception $e) {
$ms->addMessageTranslated('danger', $e->getMessage(), $data);
$error = true;
}
// Success message
if ($config['site.registration.require_email_verification']) {
// Verification required
$ms->addMessageTranslated('success', 'REGISTRATION.COMPLETE_TYPE2', $user->toArray());
} else {
// No verification required
$ms->addMessageTranslated('success', 'REGISTRATION.COMPLETE_TYPE1');
}
return $response->withJson([], 200);
}
/**
* Processes a request to resend the verification email for a new user account.
*
* Processes the request from the resend verification email form, checking that:
* 1. The rate limit on this type of request is observed;
* 2. The provided email is associated with an existing user account;
* 3. The user account is not already verified;
* 4. The submitted data is valid.
* This route is "public access".
*
* AuthGuard: false
* Route: /account/resend-verification
* Route Name: {none}
* Request type: POST
* @param Request $request
* @param Response $response
* @param array $args
*/
public function resendVerification(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// Get POST parameters
$params = $request->getParsedBody();
// Load the request schema
$schema = new RequestSchema('schema://requests/resend-verification.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
// Validate, and halt on validation errors. Failed validation attempts do not count towards throttling limit.
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
return $response->withJson([], 400);
}
// Throttle requests
/** @var \UserFrosting\Sprinkle\Core\Throttle\Throttler $throttler */
$throttler = $this->ci->throttler;
$throttleData = [
'email' => $data['email']
];
$delay = $throttler->getDelay('verification_request', $throttleData);
if ($delay > 0) {
$ms->addMessageTranslated('danger', 'RATE_LIMIT_EXCEEDED', ['delay' => $delay]);
return $response->withJson([], 429);
}
// All checks passed! log events/activities, create user, and send verification email (if required)
// Begin transaction - DB will be rolled back if an exception occurs
Capsule::transaction(function () use ($classMapper, $data, $throttler, $throttleData, $config) {