-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathSecurity.php
1385 lines (1215 loc) · 44.7 KB
/
Security.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
namespace SilverStripe\Security;
use LogicException;
use Page;
use ReflectionClass;
use SilverStripe\CMS\Controllers\ModelAsController;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\Form;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements;
use SilverStripe\View\SSViewer;
use SilverStripe\View\TemplateGlobalProvider;
/**
* Implements a basic security model
*/
class Security extends Controller implements TemplateGlobalProvider
{
private static $allowed_actions = [
'basicauthlogin',
'changepassword',
'index',
'login',
'logout',
'lostpassword',
'passwordsent',
'ping',
];
/**
* If set to TRUE to prevent sharing of the session across several sites
* in the domain.
*
* @config
* @var bool
*/
private static $strict_path_checking = false;
/**
* The password encryption algorithm to use by default.
* This is an arbitrary code registered through {@link PasswordEncryptor}.
*
* @config
* @var string
*/
private static $password_encryption_algorithm = 'blowfish';
/**
* Showing "Remember me"-checkbox
* on loginform, and saving encrypted credentials to a cookie.
*
* @config
* @var bool
*/
private static $autologin_enabled = true;
/**
* Determine if login username may be remembered between login sessions
* If set to false this will disable auto-complete and prevent username persisting in the session
*
* @config
* @var bool
*/
private static $remember_username = true;
/**
* Location of word list to use for generating passwords
*
* @config
* @var string
*/
private static $word_list = './wordlist.txt';
/**
* @config
* @var string
*/
private static $template = 'BlankPage';
/**
* Template that is used to render the pages.
*
* @var string
* @config
*/
private static $template_main = 'Page';
/**
* Class to use for page rendering
*
* @var string
* @config
*/
private static $page_class = Page::class;
/**
* Default message set used in permission failures.
*
* @config
* @var array|string
*/
private static $default_message_set;
/**
* The default login URL
*
* @config
*
* @var string
*/
private static $login_url = 'Security/login';
/**
* The default logout URL
*
* @config
*
* @var string
*/
private static $logout_url = 'Security/logout';
/**
* The default lost password URL
*
* @config
*
* @var string
*/
private static $lost_password_url = 'Security/lostpassword';
/**
* Value of X-Frame-Options header
*
* @config
* @var string
*/
private static $frame_options = 'SAMEORIGIN';
/**
* Value of the X-Robots-Tag header (for the Security section)
*
* @config
* @var string
*/
private static $robots_tag = 'noindex, nofollow';
/**
* Enable or disable recording of login attempts
* through the {@link LoginAttempt} object.
*
* @config
* @var boolean $login_recording
*/
private static $login_recording = false;
/**
* @var boolean If set to TRUE or FALSE, {@link database_is_ready()}
* will always return FALSE. Used for unit testing.
*/
protected static $force_database_is_ready;
/**
* When the database has once been verified as ready, it will not do the
* checks again.
*
* @var bool
*/
protected static $database_is_ready = false;
/**
* @var Authenticator[] available authenticators
*/
private $authenticators = [];
/**
* @var Member Currently logged in user (if available)
*/
protected static $currentUser;
/**
* @return Authenticator[]
*/
public function getAuthenticators()
{
return array_filter($this->authenticators);
}
/**
* @param Authenticator[] $authenticators
*/
public function setAuthenticators(array $authenticators)
{
$this->authenticators = $authenticators;
}
protected function init()
{
parent::init();
// Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
$frameOptions = static::config()->get('frame_options');
if ($frameOptions) {
$this->getResponse()->addHeader('X-Frame-Options', $frameOptions);
}
// Prevent search engines from indexing the login page
$robotsTag = static::config()->get('robots_tag');
if ($robotsTag) {
$this->getResponse()->addHeader('X-Robots-Tag', $robotsTag);
}
}
public function index()
{
$this->httpError(404); // no-op
}
/**
* Get the selected authenticator for this request
*
* @param string $name The identifier of the authenticator in your config
* @return Authenticator Class name of Authenticator
* @throws LogicException
*/
protected function getAuthenticator($name = 'default')
{
$authenticators = $this->getAuthenticators();
if (isset($authenticators[$name])) {
return $authenticators[$name];
}
throw new LogicException('No valid authenticator found');
}
/**
* Get all registered authenticators
*
* @param int $service The type of service that is requested
* @return Authenticator[] Return an array of Authenticator objects
*/
public function getApplicableAuthenticators($service = Authenticator::LOGIN)
{
$authenticators = $this->getAuthenticators();
/** @var Authenticator $authenticator */
foreach ($authenticators as $name => $authenticator) {
if (!($authenticator->supportedServices() & $service)) {
unset($authenticators[$name]);
}
}
if (empty($authenticators)) {
throw new LogicException('No applicable authenticators found');
}
return $authenticators;
}
/**
* Check if a given authenticator is registered
*
* @param string $authenticator The configured identifier of the authenticator
* @return bool Returns TRUE if the authenticator is registered, FALSE
* otherwise.
*/
public function hasAuthenticator($authenticator)
{
$authenticators = $this->getAuthenticators();
return !empty($authenticators[$authenticator]);
}
/**
* Register that we've had a permission failure trying to view the given page
*
* This will redirect to a login page.
* If you don't provide a messageSet, a default will be used.
*
* @param Controller $controller The controller that you were on to cause the permission
* failure.
* @param string|array $messageSet The message to show to the user. This
* can be a string, or a map of different
* messages for different contexts.
* If you pass an array, you can use the
* following keys:
* - default: The default message
* - alreadyLoggedIn: The message to
* show if the user
* is already logged
* in and lacks the
* permission to
* access the item.
*
* The alreadyLoggedIn value can contain a '%s' placeholder that will be replaced with a link
* to log in.
* @return HTTPResponse
*/
public static function permissionFailure($controller = null, $messageSet = null)
{
self::set_ignore_disallowed_actions(true);
// Parse raw message / escape type
$parseMessage = function ($message) {
if ($message instanceof DBField) {
return [
$message->getValue(),
$message->config()->get('escape_type') === 'raw'
? ValidationResult::CAST_TEXT
: ValidationResult::CAST_HTML,
];
}
// Default to escaped value
return [
$message,
ValidationResult::CAST_TEXT,
];
};
if (!$controller && Controller::has_curr()) {
$controller = Controller::curr();
}
if (Director::is_ajax()) {
$response = ($controller) ? $controller->getResponse() : new HTTPResponse();
$response->setStatusCode(403);
if (!static::getCurrentUser()) {
$response->setBody(
_t('SilverStripe\\CMS\\Controllers\\ContentController.NOTLOGGEDIN', 'Not logged in')
);
$response->setStatusDescription(
_t('SilverStripe\\CMS\\Controllers\\ContentController.NOTLOGGEDIN', 'Not logged in')
);
// Tell the CMS to allow re-authentication
if (CMSSecurity::singleton()->enabled()) {
$response->addHeader('X-Reauthenticate', '1');
}
}
return $response;
}
// Prepare the messageSet provided
if (!$messageSet) {
if ($configMessageSet = static::config()->get('default_message_set')) {
$messageSet = $configMessageSet;
} else {
$messageSet = [
'default' => _t(
__CLASS__ . '.NOTEPAGESECURED',
"That page is secured. Enter your credentials below and we will send "
. "you right along."
),
'alreadyLoggedIn' => _t(
__CLASS__ . '.ALREADYLOGGEDIN',
"You don't have access to this page. If you have another account that "
. "can access that page, you can log in again below."
)
];
}
}
if (!is_array($messageSet)) {
$messageSet = ['default' => $messageSet];
}
$member = static::getCurrentUser();
// Work out the right message to show
if ($member && $member->exists()) {
$response = ($controller) ? $controller->getResponse() : new HTTPResponse();
$response->setStatusCode(403);
//If 'alreadyLoggedIn' is not specified in the array, then use the default
//which should have been specified in the lines above
if (isset($messageSet['alreadyLoggedIn'])) {
$message = $messageSet['alreadyLoggedIn'];
} else {
$message = $messageSet['default'];
}
list($messageText, $messageCast) = $parseMessage($message);
static::singleton()->setSessionMessage($messageText, ValidationResult::TYPE_WARNING, $messageCast);
$request = new HTTPRequest('GET', '/');
if ($controller) {
$request->setSession($controller->getRequest()->getSession());
}
$loginResponse = static::singleton()->login($request);
if ($loginResponse instanceof HTTPResponse) {
return $loginResponse;
}
$response->setBody((string)$loginResponse);
$controller->extend('permissionDenied', $member);
return $response;
}
$message = $messageSet['default'];
$request = $controller->getRequest();
if ($request->hasSession()) {
list($messageText, $messageCast) = $parseMessage($message);
static::singleton()->setSessionMessage($messageText, ValidationResult::TYPE_WARNING, $messageCast);
$request->getSession()->set("BackURL", $_SERVER['REQUEST_URI']);
}
// TODO AccessLogEntry needs an extension to handle permission denied errors
// Audit logging hook
$controller->extend('permissionDenied', $member);
return $controller->redirect(Controller::join_links(
Security::config()->uninherited('login_url'),
"?BackURL=" . urlencode($_SERVER['REQUEST_URI'])
));
}
/**
* The intended uses of this function is to temporarily change the current user for things such as
* canView() checks or unit tests. It is stateless and will not persist between requests. Importantly
* it also will not call any logic that may be present in the current IdentityStore logIn() or logout() methods
*
* If you are unit testing and calling FunctionalTest::get() or FunctionalTest::post() and you need to change
* the current user, you should instead use SapphireTest::logInAs() / logOut() which itself will call
* Injector::inst()->get(IdentityStore::class)->logIn($member) / logout()
*
* @param null|Member $currentUser
*/
public static function setCurrentUser($currentUser = null)
{
self::$currentUser = $currentUser;
}
/**
* @return null|Member
*/
public static function getCurrentUser()
{
return self::$currentUser;
}
/**
* Get the login forms for all available authentication methods
*
* @deprecated 5.0.0 Now handled by {@link static::delegateToMultipleHandlers}
*
* @return array Returns an array of available login forms (array of Form
* objects).
*
*/
public function getLoginForms()
{
Deprecation::notice('5.0.0', 'Now handled by delegateToMultipleHandlers');
return array_map(
function (Authenticator $authenticator) {
return [
$authenticator->getLoginHandler($this->Link())->loginForm()
];
},
$this->getApplicableAuthenticators()
);
}
/**
* Get a link to a security action
*
* @param string $action Name of the action
* @return string Returns the link to the given action
*/
public function Link($action = null)
{
/** @skipUpgrade */
$link = Controller::join_links(Director::baseURL(), "Security", $action);
$this->extend('updateLink', $link, $action);
return $link;
}
/**
* This action is available as a keep alive, so user
* sessions don't timeout. A common use is in the admin.
*/
public function ping()
{
HTTPCacheControlMiddleware::singleton()->disableCache();
Requirements::clear();
return 1;
}
/**
* Perform pre-login checking and prepare a response if available prior to login
*
* @return HTTPResponse Substitute response object if the login process should be circumvented.
* Returns null if should proceed as normal.
*/
protected function preLogin()
{
// Event handler for pre-login, with an option to let it break you out of the login form
$eventResults = $this->extend('onBeforeSecurityLogin');
// If there was a redirection, return
if ($this->redirectedTo()) {
return $this->getResponse();
}
// If there was an HTTPResponse object returned, then return that
if ($eventResults) {
foreach ($eventResults as $result) {
if ($result instanceof HTTPResponse) {
return $result;
}
}
}
// If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect
// back. The login message check is necessary to prevent infinite loops where BackURL links to
// an action that triggers Security::permissionFailure.
// This step is necessary in cases such as automatic redirection where a user is authenticated
// upon landing on an SSL secured site and is automatically logged in, or some other case
// where the user has permissions to continue but is not given the option.
if (!$this->getSessionMessage()
&& ($member = static::getCurrentUser())
&& $member->exists()
&& $this->getRequest()->requestVar('BackURL')
) {
return $this->redirectBack();
}
return null;
}
public function getRequest()
{
// Support Security::singleton() where a request isn't always injected
$request = parent::getRequest();
if ($request) {
return $request;
}
if (Controller::has_curr() && Controller::curr() !== $this) {
return Controller::curr()->getRequest();
}
return null;
}
/**
* Prepare the controller for handling the response to this request
*
* @param string $title Title to use
* @return Controller
*/
protected function getResponseController($title)
{
// Use the default setting for which Page to use to render the security page
$pageClass = $this->config()->get('page_class');
if (!$pageClass || !class_exists($pageClass)) {
return $this;
}
// Create new instance of page holder
/** @var Page $holderPage */
$holderPage = Injector::inst()->create($pageClass);
$holderPage->Title = $title;
/** @skipUpgrade */
$holderPage->URLSegment = 'Security';
// Disable ID-based caching of the log-in page by making it a random number
$holderPage->ID = -1 * random_int(1, 10000000);
$controller = ModelAsController::controller_for($holderPage);
$controller->setRequest($this->getRequest());
$controller->doInit();
return $controller;
}
/**
* Combine the given forms into a formset with a tabbed interface
*
* @param array|Form[] $forms
* @return string
*/
protected function generateTabbedFormSet($forms)
{
if (count($forms) === 1) {
return $forms;
}
$viewData = new ArrayData([
'Forms' => new ArrayList($forms),
]);
return $viewData->renderWith(
$this->getTemplatesFor('MultiAuthenticatorTabbedForms')
);
}
/**
* Get the HTML Content for the $Content area during login
*
* @param string $messageType Type of message, if available, passed back to caller (by reference)
* @return string Message in HTML format
*/
protected function getSessionMessage(&$messageType = null)
{
$session = $this->getRequest()->getSession();
$message = $session->get('Security.Message.message');
$messageType = null;
if (empty($message)) {
return null;
}
$messageType = $session->get('Security.Message.type');
$messageCast = $session->get('Security.Message.cast');
if ($messageCast !== ValidationResult::CAST_HTML) {
$message = Convert::raw2xml($message);
}
return sprintf('<p class="message %s">%s</p>', Convert::raw2att($messageType), $message);
}
/**
* Set the next message to display for the security login page. Defaults to warning
*
* @param string $message Message
* @param string $messageType Message type. One of ValidationResult::TYPE_*
* @param string $messageCast Message cast. One of ValidationResult::CAST_*
*/
public function setSessionMessage(
$message,
$messageType = ValidationResult::TYPE_WARNING,
$messageCast = ValidationResult::CAST_TEXT
) {
Controller::curr()
->getRequest()
->getSession()
->set("Security.Message.message", $message)
->set("Security.Message.type", $messageType)
->set("Security.Message.cast", $messageCast);
}
/**
* Clear login message
*/
public static function clearSessionMessage()
{
Controller::curr()
->getRequest()
->getSession()
->clear("Security.Message");
}
/**
* Show the "login" page
*
* For multiple authenticators, Security_MultiAuthenticatorLogin is used.
* See getTemplatesFor and getIncludeTemplate for how to override template logic
*
* @param null|HTTPRequest $request
* @param int $service
* @return HTTPResponse|string Returns the "login" page as HTML code.
* @throws HTTPResponse_Exception
*/
public function login($request = null, $service = Authenticator::LOGIN)
{
if ($request) {
$this->setRequest($request);
} elseif ($this->getRequest()) {
$request = $this->getRequest();
} else {
throw new HTTPResponse_Exception("No request available", 500);
}
// Check pre-login process
if ($response = $this->preLogin()) {
return $response;
}
$authName = null;
$handlers = $this->getServiceAuthenticatorsFromRequest($service, $request);
$link = $this->Link('login');
array_walk(
$handlers,
function (Authenticator &$auth, $name) use ($link) {
$auth = $auth->getLoginHandler(Controller::join_links($link, $name));
}
);
return $this->delegateToMultipleHandlers(
$handlers,
_t(__CLASS__ . '.LOGIN', 'Log in'),
$this->getTemplatesFor('login'),
[$this, 'aggregateTabbedForms']
);
}
/**
* Log the currently logged in user out
*
* Logging out without ID-parameter in the URL, will log the user out of all applicable Authenticators.
*
* Adding an ID will only log the user out of that Authentication method.
*
* @param null|HTTPRequest $request
* @param int $service
* @return HTTPResponse|string
*/
public function logout($request = null, $service = Authenticator::LOGOUT)
{
$authName = null;
if (!$request) {
$request = $this->getRequest();
}
$handlers = $this->getServiceAuthenticatorsFromRequest($service, $request);
$link = $this->Link('logout');
array_walk(
$handlers,
function (Authenticator &$auth, $name) use ($link) {
$auth = $auth->getLogoutHandler(Controller::join_links($link, $name));
}
);
return $this->delegateToMultipleHandlers(
$handlers,
_t(__CLASS__ . '.LOGOUT', 'Log out'),
$this->getTemplatesFor('logout'),
[$this, 'aggregateAuthenticatorResponses']
);
}
/**
* Get authenticators for the given service, optionally filtered by the ID parameter
* of the current request
*
* @param int $service
* @param HTTPRequest $request
* @return array|Authenticator[]
* @throws HTTPResponse_Exception
*/
protected function getServiceAuthenticatorsFromRequest($service, HTTPRequest $request)
{
$authName = null;
if ($request->param('ID')) {
$authName = $request->param('ID');
}
// Delegate to a single named handler - e.g. Security/login/<authname>/
if ($authName && $this->hasAuthenticator($authName)) {
if ($request) {
$request->shift();
}
$authenticator = $this->getAuthenticator($authName);
if (!$authenticator->supportedServices() & $service) {
// Try to be helpful and show the service constant name, e.g. Authenticator::LOGIN
$constants = array_flip((new ReflectionClass(Authenticator::class))->getConstants());
$message = 'Invalid Authenticator "' . $authName . '" for ';
if (array_key_exists($service, $constants)) {
$message .= 'service: Authenticator::' . $constants[$service];
} else {
$message .= 'unknown authenticator service';
}
throw new HTTPResponse_Exception($message, 400);
}
$handlers = [$authName => $authenticator];
} else {
// Delegate to all of them, building a tabbed view - e.g. Security/login/
$handlers = $this->getApplicableAuthenticators($service);
}
return $handlers;
}
/**
* Aggregate tabbed forms from each handler to fragments ready to be rendered.
*
* @skipUpgrade
* @param array $results
* @return array
*/
protected function aggregateTabbedForms(array $results)
{
$forms = [];
foreach ($results as $authName => $singleResult) {
// The result *must* be an array with a Form key
if (!is_array($singleResult) || !isset($singleResult['Form'])) {
user_error('Authenticator "' . $authName . '" doesn\'t support tabbed forms', E_USER_WARNING);
continue;
}
$forms[] = $singleResult['Form'];
}
if (!$forms) {
throw new \LogicException('No authenticators found compatible with tabbed forms');
}
return [
'Forms' => ArrayList::create($forms),
'Form' => $this->generateTabbedFormSet($forms)
];
}
/**
* We have three possible scenarios.
* We get back Content (e.g. Password Reset)
* We get back a Form (no token set for logout)
* We get back a HTTPResponse, telling us to redirect.
* Return the first one, which is the default response, as that covers all required scenarios
*
* @param array $results
* @return array|HTTPResponse
*/
protected function aggregateAuthenticatorResponses($results)
{
$error = false;
$result = null;
foreach ($results as $authName => $singleResult) {
if (($singleResult instanceof HTTPResponse) ||
(is_array($singleResult) &&
(isset($singleResult['Content']) || isset($singleResult['Form'])))
) {
// return the first successful response
return $singleResult;
} else {
// Not a valid response
$error = true;
}
}
if ($error) {
throw new \LogicException('No authenticators found compatible with logout operation');
}
return $result;
}
/**
* Delegate to a number of handlers and aggregate the results. This is used, for example, to
* build the log-in page where there are multiple authenticators active.
*
* If a single handler is passed, delegateToHandler() will be called instead
*
* @param array|RequestHandler[] $handlers
* @param string $title The title of the form
* @param array $templates
* @param callable $aggregator
* @return array|HTTPResponse|RequestHandler|DBHTMLText|string
*/
protected function delegateToMultipleHandlers(array $handlers, $title, array $templates, callable $aggregator)
{
// Simpler case for a single authenticator
if (count($handlers) === 1) {
return $this->delegateToHandler(array_values($handlers)[0], $title, $templates);
}
// Process each of the handlers
$results = array_map(
function (RequestHandler $handler) {
return $handler->handleRequest($this->getRequest());
},
$handlers
);
$response = call_user_func_array($aggregator, [$results]);
// The return could be a HTTPResponse, in which we don't want to call the render
if (is_array($response)) {
return $this->renderWrappedController($title, $response, $templates);
}
return $response;
}
/**
* Delegate to another RequestHandler, rendering any fragment arrays into an appropriate.
* controller.
*
* @param RequestHandler $handler
* @param string $title The title of the form
* @param array $templates
* @return array|HTTPResponse|RequestHandler|DBHTMLText|string
*/
protected function delegateToHandler(RequestHandler $handler, $title, array $templates = [])
{
$result = $handler->handleRequest($this->getRequest());
// Return the customised controller - may be used to render a Form (e.g. login form)
if (is_array($result)) {
$result = $this->renderWrappedController($title, $result, $templates);
}
return $result;
}
/**
* Render the given fragments into a security page controller with the given title.
*
* @param string $title string The title to give the security page
* @param array $fragments A map of objects to render into the page, e.g. "Form"
* @param array $templates An array of templates to use for the render
* @return HTTPResponse|DBHTMLText
*/
protected function renderWrappedController($title, array $fragments, array $templates)
{
$controller = $this->getResponseController($title);
// if the controller calls Director::redirect(), this will break early
if (($response = $controller->getResponse()) && $response->isFinished()) {
return $response;
}
// Handle any form messages from validation, etc.
$messageType = '';
$message = $this->getSessionMessage($messageType);
// We've displayed the message in the form output, so reset it for the next run.
static::clearSessionMessage();
// Ensure title is present - in case getResponseController() didn't return a page controller
$fragments = array_merge($fragments, ['Title' => $title]);
if ($message) {
$messageResult = [
'Content' => DBField::create_field('HTMLFragment', $message),
'Message' => DBField::create_field('HTMLFragment', $message),
'MessageType' => $messageType
];
$fragments = array_merge($fragments, $messageResult);
}
return $controller->customise($fragments)->renderWith($templates);
}
public function basicauthlogin()
{
$member = BasicAuth::requireLogin($this->getRequest(), 'SilverStripe login', 'ADMIN');
static::setCurrentUser($member);
}
/**
* Show the "lost password" page
*
* @return string Returns the "lost password" page as HTML code.
*/
public function lostpassword()
{
$handlers = [];
$authenticators = $this->getApplicableAuthenticators(Authenticator::RESET_PASSWORD);
/** @var Authenticator $authenticator */
foreach ($authenticators as $authenticator) {
$handlers[] = $authenticator->getLostPasswordHandler(
Controller::join_links($this->Link(), 'lostpassword')
);
}
return $this->delegateToMultipleHandlers(
$handlers,
_t('SilverStripe\\Security\\Security.LOSTPASSWORDHEADER', 'Lost Password'),
$this->getTemplatesFor('lostpassword'),
[$this, 'aggregateAuthenticatorResponses']
);
}
/**
* Show the "change password" page.
* This page can either be called directly by logged-in users
* (in which case they need to provide their old password),
* or through a link emailed through {@link lostpassword()}.
* In this case no old password is required, authentication is ensured
* through the Member.AutoLoginHash property.