Passed
Pull Request — 4 (#10041)
by Guy
07:06
created

Security::database_is_ready()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 14
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Security;
4
5
use LogicException;
6
use Page;
0 ignored issues
show
Bug introduced by
The type Page was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use ReflectionClass;
8
use SilverStripe\CMS\Controllers\ModelAsController;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Controllers\ModelAsController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Control\HTTPRequest;
12
use SilverStripe\Control\HTTPResponse;
13
use SilverStripe\Control\HTTPResponse_Exception;
14
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
15
use SilverStripe\Control\RequestHandler;
16
use SilverStripe\Core\ClassInfo;
17
use SilverStripe\Core\Convert;
18
use SilverStripe\Core\Injector\Injector;
19
use SilverStripe\Dev\Deprecation;
20
use SilverStripe\Dev\TestOnly;
21
use SilverStripe\Forms\Form;
22
use SilverStripe\ORM\ArrayList;
23
use SilverStripe\ORM\DataObject;
24
use SilverStripe\ORM\DB;
25
use SilverStripe\ORM\FieldType\DBField;
26
use SilverStripe\ORM\FieldType\DBHTMLText;
27
use SilverStripe\ORM\ValidationResult;
28
use SilverStripe\View\ArrayData;
29
use SilverStripe\View\Requirements;
30
use SilverStripe\View\SSViewer;
31
use SilverStripe\View\TemplateGlobalProvider;
32
33
/**
34
 * Implements a basic security model
35
 */
36
class Security extends Controller implements TemplateGlobalProvider
37
{
38
39
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
40
        'basicauthlogin',
41
        'changepassword',
42
        'index',
43
        'login',
44
        'logout',
45
        'lostpassword',
46
        'passwordsent',
47
        'ping',
48
    ];
49
50
    /**
51
     * If set to TRUE to prevent sharing of the session across several sites
52
     * in the domain.
53
     *
54
     * @config
55
     * @var bool
56
     */
57
    private static $strict_path_checking = false;
0 ignored issues
show
introduced by
The private property $strict_path_checking is not used, and could be removed.
Loading history...
58
59
    /**
60
     * The password encryption algorithm to use by default.
61
     * This is an arbitrary code registered through {@link PasswordEncryptor}.
62
     *
63
     * @config
64
     * @var string
65
     */
66
    private static $password_encryption_algorithm = 'blowfish';
0 ignored issues
show
introduced by
The private property $password_encryption_algorithm is not used, and could be removed.
Loading history...
67
68
    /**
69
     * Showing "Remember me"-checkbox
70
     * on loginform, and saving encrypted credentials to a cookie.
71
     *
72
     * @config
73
     * @var bool
74
     */
75
    private static $autologin_enabled = true;
0 ignored issues
show
introduced by
The private property $autologin_enabled is not used, and could be removed.
Loading history...
76
77
    /**
78
     * Determine if login username may be remembered between login sessions
79
     * If set to false this will disable auto-complete and prevent username persisting in the session
80
     *
81
     * @config
82
     * @var bool
83
     */
84
    private static $remember_username = true;
0 ignored issues
show
introduced by
The private property $remember_username is not used, and could be removed.
Loading history...
85
86
    /**
87
     * Location of word list to use for generating passwords
88
     *
89
     * @config
90
     * @var string
91
     */
92
    private static $word_list = './wordlist.txt';
0 ignored issues
show
introduced by
The private property $word_list is not used, and could be removed.
Loading history...
93
94
    /**
95
     * @config
96
     * @var string
97
     */
98
    private static $template = 'BlankPage';
0 ignored issues
show
introduced by
The private property $template is not used, and could be removed.
Loading history...
99
100
    /**
101
     * Template that is used to render the pages.
102
     *
103
     * @var string
104
     * @config
105
     */
106
    private static $template_main = 'Page';
0 ignored issues
show
introduced by
The private property $template_main is not used, and could be removed.
Loading history...
107
108
    /**
109
     * Class to use for page rendering
110
     *
111
     * @var string
112
     * @config
113
     */
114
    private static $page_class = Page::class;
0 ignored issues
show
introduced by
The private property $page_class is not used, and could be removed.
Loading history...
115
116
    /**
117
     * Default message set used in permission failures.
118
     *
119
     * @config
120
     * @var array|string
121
     */
122
    private static $default_message_set;
0 ignored issues
show
introduced by
The private property $default_message_set is not used, and could be removed.
Loading history...
123
124
    /**
125
     * The default login URL
126
     *
127
     * @config
128
     *
129
     * @var string
130
     */
131
    private static $login_url = 'Security/login';
0 ignored issues
show
introduced by
The private property $login_url is not used, and could be removed.
Loading history...
132
133
    /**
134
     * The default logout URL
135
     *
136
     * @config
137
     *
138
     * @var string
139
     */
140
    private static $logout_url = 'Security/logout';
0 ignored issues
show
introduced by
The private property $logout_url is not used, and could be removed.
Loading history...
141
142
    /**
143
     * The default lost password URL
144
     *
145
     * @config
146
     *
147
     * @var string
148
     */
149
    private static $lost_password_url = 'Security/lostpassword';
0 ignored issues
show
introduced by
The private property $lost_password_url is not used, and could be removed.
Loading history...
150
151
    /**
152
     * Value of X-Frame-Options header
153
     *
154
     * @config
155
     * @var string
156
     */
157
    private static $frame_options = 'SAMEORIGIN';
0 ignored issues
show
introduced by
The private property $frame_options is not used, and could be removed.
Loading history...
158
159
    /**
160
     * Value of the X-Robots-Tag header (for the Security section)
161
     *
162
     * @config
163
     * @var string
164
     */
165
    private static $robots_tag = 'noindex, nofollow';
0 ignored issues
show
introduced by
The private property $robots_tag is not used, and could be removed.
Loading history...
166
167
    /**
168
     * Enable or disable recording of login attempts
169
     * through the {@link LoginAttempt} object.
170
     *
171
     * @config
172
     * @var boolean $login_recording
173
     */
174
    private static $login_recording = false;
0 ignored issues
show
introduced by
The private property $login_recording is not used, and could be removed.
Loading history...
175
176
    /**
177
     * @var Authenticator[] available authenticators
178
     */
179
    private $authenticators = [];
180
181
    /**
182
     * @var Member Currently logged in user (if available)
183
     */
184
    protected static $currentUser;
185
186
    /**
187
     * @return Authenticator[]
188
     */
189
    public function getAuthenticators()
190
    {
191
        return array_filter($this->authenticators);
192
    }
193
194
    /**
195
     * @param Authenticator[] $authenticators
196
     */
197
    public function setAuthenticators(array $authenticators)
198
    {
199
        $this->authenticators = $authenticators;
200
    }
201
202
    protected function init()
203
    {
204
        parent::init();
205
206
        // Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
207
        $frameOptions = static::config()->get('frame_options');
208
        if ($frameOptions) {
209
            $this->getResponse()->addHeader('X-Frame-Options', $frameOptions);
210
        }
211
212
        // Prevent search engines from indexing the login page
213
        $robotsTag = static::config()->get('robots_tag');
214
        if ($robotsTag) {
215
            $this->getResponse()->addHeader('X-Robots-Tag', $robotsTag);
216
        }
217
    }
218
219
    public function index()
220
    {
221
        $this->httpError(404); // no-op
222
    }
223
224
    /**
225
     * Get the selected authenticator for this request
226
     *
227
     * @param string $name The identifier of the authenticator in your config
228
     * @return Authenticator Class name of Authenticator
229
     * @throws LogicException
230
     */
231
    protected function getAuthenticator($name = 'default')
232
    {
233
        $authenticators = $this->getAuthenticators();
234
235
        if (isset($authenticators[$name])) {
236
            return $authenticators[$name];
237
        }
238
239
        throw new LogicException('No valid authenticator found');
240
    }
241
242
    /**
243
     * Get all registered authenticators
244
     *
245
     * @param int $service The type of service that is requested
246
     * @return Authenticator[] Return an array of Authenticator objects
247
     */
248
    public function getApplicableAuthenticators($service = Authenticator::LOGIN)
249
    {
250
        $authenticators = $this->getAuthenticators();
251
252
        /** @var Authenticator $authenticator */
253
        foreach ($authenticators as $name => $authenticator) {
254
            if (!($authenticator->supportedServices() & $service)) {
255
                unset($authenticators[$name]);
256
            }
257
        }
258
259
        if (empty($authenticators)) {
260
            throw new LogicException('No applicable authenticators found');
261
        }
262
263
        return $authenticators;
264
    }
265
266
    /**
267
     * Check if a given authenticator is registered
268
     *
269
     * @param string $authenticator The configured identifier of the authenticator
270
     * @return bool Returns TRUE if the authenticator is registered, FALSE
271
     *              otherwise.
272
     */
273
    public function hasAuthenticator($authenticator)
274
    {
275
        $authenticators = $this->getAuthenticators();
276
277
        return !empty($authenticators[$authenticator]);
278
    }
279
280
    /**
281
     * Register that we've had a permission failure trying to view the given page
282
     *
283
     * This will redirect to a login page.
284
     * If you don't provide a messageSet, a default will be used.
285
     *
286
     * @param Controller $controller The controller that you were on to cause the permission
287
     *                               failure.
288
     * @param string|array $messageSet The message to show to the user. This
289
     *                                 can be a string, or a map of different
290
     *                                 messages for different contexts.
291
     *                                 If you pass an array, you can use the
292
     *                                 following keys:
293
     *                                   - default: The default message
294
     *                                   - alreadyLoggedIn: The message to
295
     *                                                      show if the user
296
     *                                                      is already logged
297
     *                                                      in and lacks the
298
     *                                                      permission to
299
     *                                                      access the item.
300
     *
301
     * The alreadyLoggedIn value can contain a '%s' placeholder that will be replaced with a link
302
     * to log in.
303
     * @return HTTPResponse
304
     */
305
    public static function permissionFailure($controller = null, $messageSet = null)
306
    {
307
        self::set_ignore_disallowed_actions(true);
308
309
        // Parse raw message / escape type
310
        $parseMessage = function ($message) {
311
            if ($message instanceof DBField) {
312
                return [
313
                    $message->getValue(),
314
                    $message->config()->get('escape_type') === 'raw'
315
                        ? ValidationResult::CAST_TEXT
316
                        : ValidationResult::CAST_HTML,
317
                ];
318
            }
319
320
            // Default to escaped value
321
            return [
322
                $message,
323
                ValidationResult::CAST_TEXT,
324
            ];
325
        };
326
327
        if (!$controller && Controller::has_curr()) {
328
            $controller = Controller::curr();
329
        }
330
331
        if (Director::is_ajax()) {
332
            $response = ($controller) ? $controller->getResponse() : new HTTPResponse();
333
            $response->setStatusCode(403);
334
            if (!static::getCurrentUser()) {
335
                $response->setBody(
336
                    _t('SilverStripe\\CMS\\Controllers\\ContentController.NOTLOGGEDIN', 'Not logged in')
337
                );
338
                $response->setStatusDescription(
339
                    _t('SilverStripe\\CMS\\Controllers\\ContentController.NOTLOGGEDIN', 'Not logged in')
340
                );
341
                // Tell the CMS to allow re-authentication
342
                if (CMSSecurity::singleton()->enabled()) {
343
                    $response->addHeader('X-Reauthenticate', '1');
344
                }
345
            }
346
347
            return $response;
348
        }
349
350
        // Prepare the messageSet provided
351
        if (!$messageSet) {
352
            if ($configMessageSet = static::config()->get('default_message_set')) {
353
                $messageSet = $configMessageSet;
354
            } else {
355
                $messageSet = [
356
                    'default' => _t(
357
                        __CLASS__ . '.NOTEPAGESECURED',
358
                        "That page is secured. Enter your credentials below and we will send "
359
                            . "you right along."
360
                    ),
361
                    'alreadyLoggedIn' => _t(
362
                        __CLASS__ . '.ALREADYLOGGEDIN',
363
                        "You don't have access to this page.  If you have another account that "
364
                            . "can access that page, you can log in again below."
365
                    )
366
                ];
367
            }
368
        }
369
370
        if (!is_array($messageSet)) {
371
            $messageSet = ['default' => $messageSet];
372
        }
373
374
        $member = static::getCurrentUser();
375
376
        // Work out the right message to show
377
        if ($member && $member->exists()) {
378
            $response = ($controller) ? $controller->getResponse() : new HTTPResponse();
379
            $response->setStatusCode(403);
380
381
            //If 'alreadyLoggedIn' is not specified in the array, then use the default
382
            //which should have been specified in the lines above
383
            if (isset($messageSet['alreadyLoggedIn'])) {
384
                $message = $messageSet['alreadyLoggedIn'];
385
            } else {
386
                $message = $messageSet['default'];
387
            }
388
389
            list($messageText, $messageCast) = $parseMessage($message);
390
            static::singleton()->setSessionMessage($messageText, ValidationResult::TYPE_WARNING, $messageCast);
391
            $request = new HTTPRequest('GET', '/');
392
            if ($controller) {
393
                $request->setSession($controller->getRequest()->getSession());
394
            }
395
            $loginResponse = static::singleton()->login($request);
396
            if ($loginResponse instanceof HTTPResponse) {
397
                return $loginResponse;
398
            }
399
400
            $response->setBody((string)$loginResponse);
401
402
            $controller->extend('permissionDenied', $member);
403
404
            return $response;
405
        }
406
        $message = $messageSet['default'];
407
408
        $request = $controller->getRequest();
409
        if ($request->hasSession()) {
410
            list($messageText, $messageCast) = $parseMessage($message);
411
            static::singleton()->setSessionMessage($messageText, ValidationResult::TYPE_WARNING, $messageCast);
412
413
            $request->getSession()->set("BackURL", $_SERVER['REQUEST_URI']);
414
        }
415
416
        // TODO AccessLogEntry needs an extension to handle permission denied errors
417
        // Audit logging hook
418
        $controller->extend('permissionDenied', $member);
419
420
        return $controller->redirect(Controller::join_links(
421
            Security::config()->uninherited('login_url'),
422
            "?BackURL=" . urlencode($_SERVER['REQUEST_URI'])
423
        ));
424
    }
425
426
    /**
427
     * The intended uses of this function is to temporarily change the current user for things such as
428
     * canView() checks or unit tests.  It is stateless and will not persist between requests.  Importantly
429
     * it also will not call any logic that may be present in the current IdentityStore logIn() or logout() methods
430
     *
431
     * If you are unit testing and calling FunctionalTest::get() or FunctionalTest::post() and you need to change
432
     * the current user, you should instead use SapphireTest::logInAs() / logOut() which itself will call
433
     * Injector::inst()->get(IdentityStore::class)->logIn($member) / logout()
434
     *
435
     * @param null|Member $currentUser
436
     */
437
    public static function setCurrentUser($currentUser = null)
438
    {
439
        self::$currentUser = $currentUser;
440
    }
441
442
    /**
443
     * @return null|Member
444
     */
445
    public static function getCurrentUser()
446
    {
447
        return self::$currentUser;
448
    }
449
450
    /**
451
     * Get the login forms for all available authentication methods
452
     *
453
     * @deprecated 5.0.0 Now handled by {@link static::delegateToMultipleHandlers}
454
     *
455
     * @return array Returns an array of available login forms (array of Form
456
     *               objects).
457
     *
458
     */
459
    public function getLoginForms()
460
    {
461
        Deprecation::notice('5.0.0', 'Now handled by delegateToMultipleHandlers');
462
463
        return array_map(
464
            function (Authenticator $authenticator) {
465
                return [
466
                    $authenticator->getLoginHandler($this->Link())->loginForm()
467
                ];
468
            },
469
            $this->getApplicableAuthenticators()
470
        );
471
    }
472
473
474
    /**
475
     * Get a link to a security action
476
     *
477
     * @param string $action Name of the action
478
     * @return string Returns the link to the given action
479
     */
480
    public function Link($action = null)
481
    {
482
        /** @skipUpgrade */
483
        $link = Controller::join_links(Director::baseURL(), "Security", $action);
484
        $this->extend('updateLink', $link, $action);
485
        return $link;
486
    }
487
488
    /**
489
     * This action is available as a keep alive, so user
490
     * sessions don't timeout. A common use is in the admin.
491
     */
492
    public function ping()
493
    {
494
        HTTPCacheControlMiddleware::singleton()->disableCache();
495
        Requirements::clear();
496
        return 1;
497
    }
498
499
    /**
500
     * Perform pre-login checking and prepare a response if available prior to login
501
     *
502
     * @return HTTPResponse Substitute response object if the login process should be circumvented.
503
     * Returns null if should proceed as normal.
504
     */
505
    protected function preLogin()
506
    {
507
        // Event handler for pre-login, with an option to let it break you out of the login form
508
        $eventResults = $this->extend('onBeforeSecurityLogin');
509
        // If there was a redirection, return
510
        if ($this->redirectedTo()) {
511
            return $this->getResponse();
512
        }
513
        // If there was an HTTPResponse object returned, then return that
514
        if ($eventResults) {
515
            foreach ($eventResults as $result) {
516
                if ($result instanceof HTTPResponse) {
517
                    return $result;
518
                }
519
            }
520
        }
521
522
        // If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect
523
        // back. The login message check is necessary to prevent infinite loops where BackURL links to
524
        // an action that triggers Security::permissionFailure.
525
        // This step is necessary in cases such as automatic redirection where a user is authenticated
526
        // upon landing on an SSL secured site and is automatically logged in, or some other case
527
        // where the user has permissions to continue but is not given the option.
528
        if (!$this->getSessionMessage()
529
            && ($member = static::getCurrentUser())
530
            && $member->exists()
531
            && $this->getRequest()->requestVar('BackURL')
532
        ) {
533
            return $this->redirectBack();
534
        }
535
536
        return null;
537
    }
538
539
    public function getRequest()
540
    {
541
        // Support Security::singleton() where a request isn't always injected
542
        $request = parent::getRequest();
543
        if ($request) {
0 ignored issues
show
introduced by
$request is of type SilverStripe\Control\HTTPRequest, thus it always evaluated to true.
Loading history...
544
            return $request;
545
        }
546
547
        if (Controller::has_curr() && Controller::curr() !== $this) {
548
            return Controller::curr()->getRequest();
549
        }
550
551
        return null;
552
    }
553
554
    /**
555
     * Prepare the controller for handling the response to this request
556
     *
557
     * @param string $title Title to use
558
     * @return Controller
559
     */
560
    protected function getResponseController($title)
561
    {
562
        // Use the default setting for which Page to use to render the security page
563
        $pageClass = $this->config()->get('page_class');
564
        if (!$pageClass || !class_exists($pageClass)) {
565
            return $this;
566
        }
567
568
        // Create new instance of page holder
569
        /** @var Page $holderPage */
570
        $holderPage = Injector::inst()->create($pageClass);
571
        $holderPage->Title = $title;
572
        /** @skipUpgrade */
573
        $holderPage->URLSegment = 'Security';
574
        // Disable ID-based caching  of the log-in page by making it a random number
575
        $holderPage->ID = -1 * random_int(1, 10000000);
576
577
        $controller = ModelAsController::controller_for($holderPage);
578
        $controller->setRequest($this->getRequest());
579
        $controller->doInit();
580
581
        return $controller;
582
    }
583
584
    /**
585
     * Combine the given forms into a formset with a tabbed interface
586
     *
587
     * @param array|Form[] $forms
588
     * @return string
589
     */
590
    protected function generateTabbedFormSet($forms)
591
    {
592
        if (count($forms) === 1) {
593
            return $forms;
594
        }
595
596
        $viewData = new ArrayData([
597
            'Forms' => new ArrayList($forms),
598
        ]);
599
600
        return $viewData->renderWith(
601
            $this->getTemplatesFor('MultiAuthenticatorTabbedForms')
602
        );
603
    }
604
605
    /**
606
     * Get the HTML Content for the $Content area during login
607
     *
608
     * @param string $messageType Type of message, if available, passed back to caller (by reference)
609
     * @return string Message in HTML format
610
     */
611
    protected function getSessionMessage(&$messageType = null)
612
    {
613
        $session = $this->getRequest()->getSession();
614
        $message = $session->get('Security.Message.message');
615
        $messageType = null;
616
        if (empty($message)) {
617
            return null;
618
        }
619
620
        $messageType = $session->get('Security.Message.type');
621
        $messageCast = $session->get('Security.Message.cast');
622
        if ($messageCast !== ValidationResult::CAST_HTML) {
623
            $message = Convert::raw2xml($message);
624
        }
625
626
        return sprintf('<p class="message %s">%s</p>', Convert::raw2att($messageType), $message);
0 ignored issues
show
Bug introduced by
It seems like SilverStripe\Core\Convert::raw2att($messageType) can also be of type array and array; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

626
        return sprintf('<p class="message %s">%s</p>', /** @scrutinizer ignore-type */ Convert::raw2att($messageType), $message);
Loading history...
627
    }
628
629
    /**
630
     * Set the next message to display for the security login page. Defaults to warning
631
     *
632
     * @param string $message Message
633
     * @param string $messageType Message type. One of ValidationResult::TYPE_*
634
     * @param string $messageCast Message cast. One of ValidationResult::CAST_*
635
     */
636
    public function setSessionMessage(
637
        $message,
638
        $messageType = ValidationResult::TYPE_WARNING,
639
        $messageCast = ValidationResult::CAST_TEXT
640
    ) {
641
        Controller::curr()
642
            ->getRequest()
643
            ->getSession()
644
            ->set("Security.Message.message", $message)
645
            ->set("Security.Message.type", $messageType)
646
            ->set("Security.Message.cast", $messageCast);
647
    }
648
649
    /**
650
     * Clear login message
651
     */
652
    public static function clearSessionMessage()
653
    {
654
        Controller::curr()
655
            ->getRequest()
656
            ->getSession()
657
            ->clear("Security.Message");
658
    }
659
660
    /**
661
     * Show the "login" page
662
     *
663
     * For multiple authenticators, Security_MultiAuthenticatorLogin is used.
664
     * See getTemplatesFor and getIncludeTemplate for how to override template logic
665
     *
666
     * @param null|HTTPRequest $request
667
     * @param int $service
668
     * @return HTTPResponse|string Returns the "login" page as HTML code.
669
     * @throws HTTPResponse_Exception
670
     */
671
    public function login($request = null, $service = Authenticator::LOGIN)
672
    {
673
        if ($request) {
674
            $this->setRequest($request);
675
        } elseif ($this->getRequest()) {
676
            $request = $this->getRequest();
677
        } else {
678
            throw new HTTPResponse_Exception("No request available", 500);
679
        }
680
681
        // Check pre-login process
682
        if ($response = $this->preLogin()) {
683
            return $response;
684
        }
685
        $authName = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $authName is dead and can be removed.
Loading history...
686
687
        $handlers = $this->getServiceAuthenticatorsFromRequest($service, $request);
688
689
        $link = $this->Link('login');
690
        array_walk(
691
            $handlers,
692
            function (Authenticator &$auth, $name) use ($link) {
693
                $auth = $auth->getLoginHandler(Controller::join_links($link, $name));
694
            }
695
        );
696
697
        return $this->delegateToMultipleHandlers(
698
            $handlers,
699
            _t(__CLASS__ . '.LOGIN', 'Log in'),
700
            $this->getTemplatesFor('login'),
701
            [$this, 'aggregateTabbedForms']
702
        );
703
    }
704
705
    /**
706
     * Log the currently logged in user out
707
     *
708
     * Logging out without ID-parameter in the URL, will log the user out of all applicable Authenticators.
709
     *
710
     * Adding an ID will only log the user out of that Authentication method.
711
     *
712
     * @param null|HTTPRequest $request
713
     * @param int $service
714
     * @return HTTPResponse|string
715
     */
716
    public function logout($request = null, $service = Authenticator::LOGOUT)
717
    {
718
        $authName = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $authName is dead and can be removed.
Loading history...
719
720
        if (!$request) {
721
            $request = $this->getRequest();
722
        }
723
724
        $handlers = $this->getServiceAuthenticatorsFromRequest($service, $request);
725
726
        $link = $this->Link('logout');
727
        array_walk(
728
            $handlers,
729
            function (Authenticator &$auth, $name) use ($link) {
730
                $auth = $auth->getLogoutHandler(Controller::join_links($link, $name));
731
            }
732
        );
733
734
        return $this->delegateToMultipleHandlers(
735
            $handlers,
736
            _t(__CLASS__ . '.LOGOUT', 'Log out'),
737
            $this->getTemplatesFor('logout'),
738
            [$this, 'aggregateAuthenticatorResponses']
739
        );
740
    }
741
742
    /**
743
     * Get authenticators for the given service, optionally filtered by the ID parameter
744
     * of the current request
745
     *
746
     * @param int $service
747
     * @param HTTPRequest $request
748
     * @return array|Authenticator[]
749
     * @throws HTTPResponse_Exception
750
     */
751
    protected function getServiceAuthenticatorsFromRequest($service, HTTPRequest $request)
752
    {
753
        $authName = null;
754
755
        if ($request->param('ID')) {
756
            $authName = $request->param('ID');
757
        }
758
759
        // Delegate to a single named handler - e.g. Security/login/<authname>/
760
        if ($authName && $this->hasAuthenticator($authName)) {
761
            if ($request) {
0 ignored issues
show
introduced by
$request is of type SilverStripe\Control\HTTPRequest, thus it always evaluated to true.
Loading history...
762
                $request->shift();
763
            }
764
765
            $authenticator = $this->getAuthenticator($authName);
766
767
            if (!$authenticator->supportedServices() & $service) {
768
                // Try to be helpful and show the service constant name, e.g. Authenticator::LOGIN
769
                $constants = array_flip((new ReflectionClass(Authenticator::class))->getConstants());
770
771
                $message = 'Invalid Authenticator "' . $authName . '" for ';
772
                if (array_key_exists($service, $constants)) {
773
                    $message .= 'service: Authenticator::' . $constants[$service];
774
                } else {
775
                    $message .= 'unknown authenticator service';
776
                }
777
778
                throw new HTTPResponse_Exception($message, 400);
779
            }
780
781
            $handlers = [$authName => $authenticator];
782
        } else {
783
            // Delegate to all of them, building a tabbed view - e.g. Security/login/
784
            $handlers = $this->getApplicableAuthenticators($service);
785
        }
786
787
        return $handlers;
788
    }
789
790
    /**
791
     * Aggregate tabbed forms from each handler to fragments ready to be rendered.
792
     *
793
     * @skipUpgrade
794
     * @param array $results
795
     * @return array
796
     */
797
    protected function aggregateTabbedForms(array $results)
798
    {
799
        $forms = [];
800
        foreach ($results as $authName => $singleResult) {
801
            // The result *must* be an array with a Form key
802
            if (!is_array($singleResult) || !isset($singleResult['Form'])) {
803
                user_error('Authenticator "' . $authName . '" doesn\'t support tabbed forms', E_USER_WARNING);
804
                continue;
805
            }
806
807
            $forms[] = $singleResult['Form'];
808
        }
809
810
        if (!$forms) {
811
            throw new \LogicException('No authenticators found compatible with tabbed forms');
812
        }
813
814
        return [
815
            'Forms' => ArrayList::create($forms),
816
            'Form' => $this->generateTabbedFormSet($forms)
817
        ];
818
    }
819
820
    /**
821
     * We have three possible scenarios.
822
     * We get back Content (e.g. Password Reset)
823
     * We get back a Form (no token set for logout)
824
     * We get back a HTTPResponse, telling us to redirect.
825
     * Return the first one, which is the default response, as that covers all required scenarios
826
     *
827
     * @param array $results
828
     * @return array|HTTPResponse
829
     */
830
    protected function aggregateAuthenticatorResponses($results)
831
    {
832
        $error = false;
833
        $result = null;
834
        foreach ($results as $authName => $singleResult) {
835
            if (($singleResult instanceof HTTPResponse) ||
836
                (is_array($singleResult) &&
837
                    (isset($singleResult['Content']) || isset($singleResult['Form'])))
838
            ) {
839
                // return the first successful response
840
                return $singleResult;
841
            } else {
842
                // Not a valid response
843
                $error = true;
844
            }
845
        }
846
847
        if ($error) {
848
            throw new \LogicException('No authenticators found compatible with logout operation');
849
        }
850
851
        return $result;
852
    }
853
854
    /**
855
     * Delegate to a number of handlers and aggregate the results. This is used, for example, to
856
     * build the log-in page where there are multiple authenticators active.
857
     *
858
     * If a single handler is passed, delegateToHandler() will be called instead
859
     *
860
     * @param array|RequestHandler[] $handlers
861
     * @param string $title The title of the form
862
     * @param array $templates
863
     * @param callable $aggregator
864
     * @return array|HTTPResponse|RequestHandler|DBHTMLText|string
865
     */
866
    protected function delegateToMultipleHandlers(array $handlers, $title, array $templates, callable $aggregator)
867
    {
868
869
        // Simpler case for a single authenticator
870
        if (count($handlers) === 1) {
871
            return $this->delegateToHandler(array_values($handlers)[0], $title, $templates);
872
        }
873
874
        // Process each of the handlers
875
        $results = array_map(
876
            function (RequestHandler $handler) {
877
                return $handler->handleRequest($this->getRequest());
878
            },
879
            $handlers
880
        );
881
882
        $response = call_user_func_array($aggregator, [$results]);
883
        // The return could be a HTTPResponse, in which we don't want to call the render
884
        if (is_array($response)) {
885
            return $this->renderWrappedController($title, $response, $templates);
886
        }
887
888
        return $response;
889
    }
890
891
    /**
892
     * Delegate to another RequestHandler, rendering any fragment arrays into an appropriate.
893
     * controller.
894
     *
895
     * @param RequestHandler $handler
896
     * @param string $title The title of the form
897
     * @param array $templates
898
     * @return array|HTTPResponse|RequestHandler|DBHTMLText|string
899
     */
900
    protected function delegateToHandler(RequestHandler $handler, $title, array $templates = [])
901
    {
902
        $result = $handler->handleRequest($this->getRequest());
903
904
        // Return the customised controller - may be used to render a Form (e.g. login form)
905
        if (is_array($result)) {
906
            $result = $this->renderWrappedController($title, $result, $templates);
907
        }
908
909
        return $result;
910
    }
911
912
    /**
913
     * Render the given fragments into a security page controller with the given title.
914
     *
915
     * @param string $title string The title to give the security page
916
     * @param array $fragments A map of objects to render into the page, e.g. "Form"
917
     * @param array $templates An array of templates to use for the render
918
     * @return HTTPResponse|DBHTMLText
919
     */
920
    protected function renderWrappedController($title, array $fragments, array $templates)
921
    {
922
        $controller = $this->getResponseController($title);
923
924
        // if the controller calls Director::redirect(), this will break early
925
        if (($response = $controller->getResponse()) && $response->isFinished()) {
926
            return $response;
927
        }
928
929
        // Handle any form messages from validation, etc.
930
        $messageType = '';
931
        $message = $this->getSessionMessage($messageType);
932
933
        // We've displayed the message in the form output, so reset it for the next run.
934
        static::clearSessionMessage();
935
936
        // Ensure title is present - in case getResponseController() didn't return a page controller
937
        $fragments = array_merge($fragments, ['Title' => $title]);
938
        if ($message) {
939
            $messageResult = [
940
                'Content'     => DBField::create_field('HTMLFragment', $message),
941
                'Message'     => DBField::create_field('HTMLFragment', $message),
942
                'MessageType' => $messageType
943
            ];
944
            $fragments = array_merge($fragments, $messageResult);
945
        }
946
947
        return $controller->customise($fragments)->renderWith($templates);
948
    }
949
950
    public function basicauthlogin()
951
    {
952
        $member = BasicAuth::requireLogin($this->getRequest(), 'SilverStripe login', 'ADMIN');
953
        static::setCurrentUser($member);
0 ignored issues
show
Bug introduced by
It seems like $member can also be of type boolean; however, parameter $currentUser of SilverStripe\Security\Security::setCurrentUser() does only seem to accept SilverStripe\Security\Member|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

953
        static::setCurrentUser(/** @scrutinizer ignore-type */ $member);
Loading history...
954
    }
955
956
    /**
957
     * Show the "lost password" page
958
     *
959
     * @return string Returns the "lost password" page as HTML code.
960
     */
961
    public function lostpassword()
962
    {
963
        $handlers = [];
964
        $authenticators = $this->getApplicableAuthenticators(Authenticator::RESET_PASSWORD);
965
        /** @var Authenticator $authenticator */
966
        foreach ($authenticators as $authenticator) {
967
            $handlers[] = $authenticator->getLostPasswordHandler(
968
                Controller::join_links($this->Link(), 'lostpassword')
969
            );
970
        }
971
972
        return $this->delegateToMultipleHandlers(
973
            $handlers,
974
            _t('SilverStripe\\Security\\Security.LOSTPASSWORDHEADER', 'Lost Password'),
975
            $this->getTemplatesFor('lostpassword'),
976
            [$this, 'aggregateAuthenticatorResponses']
977
        );
978
    }
979
980
    /**
981
     * Show the "change password" page.
982
     * This page can either be called directly by logged-in users
983
     * (in which case they need to provide their old password),
984
     * or through a link emailed through {@link lostpassword()}.
985
     * In this case no old password is required, authentication is ensured
986
     * through the Member.AutoLoginHash property.
987
     *
988
     * @see ChangePasswordForm
989
     *
990
     * @return string|HTTPRequest Returns the "change password" page as HTML code, or a redirect response
991
     */
992
    public function changepassword()
993
    {
994
        /** @var array|Authenticator[] $authenticators */
995
        $authenticators = $this->getApplicableAuthenticators(Authenticator::CHANGE_PASSWORD);
996
        $handlers = [];
997
        foreach ($authenticators as $authenticator) {
998
            $handlers[] = $authenticator->getChangePasswordHandler($this->Link('changepassword'));
999
        }
1000
1001
        return $this->delegateToMultipleHandlers(
1002
            $handlers,
1003
            _t('SilverStripe\\Security\\Security.CHANGEPASSWORDHEADER', 'Change your password'),
1004
            $this->getTemplatesFor('changepassword'),
1005
            [$this, 'aggregateAuthenticatorResponses']
1006
        );
1007
    }
1008
1009
    /**
1010
     * Create a link to the password reset form.
1011
     *
1012
     * GET parameters used:
1013
     * - m: member ID
1014
     * - t: plaintext token
1015
     *
1016
     * @param Member $member Member object associated with this link.
1017
     * @param string $autologinToken The auto login token.
1018
     * @return string
1019
     */
1020
    public static function getPasswordResetLink($member, $autologinToken)
1021
    {
1022
        $autologinToken = urldecode($autologinToken);
1023
1024
        return static::singleton()->Link('changepassword') . "?m={$member->ID}&t=$autologinToken";
1025
    }
1026
1027
    /**
1028
     * Determine the list of templates to use for rendering the given action.
1029
     *
1030
     * @skipUpgrade
1031
     * @param string $action
1032
     * @return array Template list
1033
     */
1034
    public function getTemplatesFor($action)
1035
    {
1036
        $templates = SSViewer::get_templates_by_class(static::class, "_{$action}", __CLASS__);
1037
1038
        return array_merge(
1039
            $templates,
1040
            [
1041
                "Security_{$action}",
1042
                "Security",
1043
                $this->config()->get("template_main"),
1044
                "BlankPage"
1045
            ]
1046
        );
1047
    }
1048
1049
    /**
1050
     * Return an existing member with administrator privileges, or create one of necessary.
1051
     *
1052
     * Will create a default 'Administrators' group if no group is found
1053
     * with an ADMIN permission. Will create a new 'Admin' member with administrative permissions
1054
     * if no existing Member with these permissions is found.
1055
     *
1056
     * Important: Any newly created administrator accounts will NOT have valid
1057
     * login credentials (Email/Password properties), which means they can't be used for login
1058
     * purposes outside of any default credentials set through {@link Security::setDefaultAdmin()}.
1059
     *
1060
     * @return Member
1061
     *
1062
     * @deprecated 4.0.0:5.0.0 Please use DefaultAdminService::findOrCreateDefaultAdmin()
1063
     */
1064
    public static function findAnAdministrator()
1065
    {
1066
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::findOrCreateDefaultAdmin()');
1067
1068
        $service = DefaultAdminService::singleton();
1069
        return $service->findOrCreateDefaultAdmin();
1070
    }
1071
1072
    /**
1073
     * Flush the default admin credentials
1074
     *
1075
     * @deprecated 4.0.0:5.0.0 Please use DefaultAdminService::clearDefaultAdmin()
1076
     */
1077
    public static function clear_default_admin()
1078
    {
1079
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::clearDefaultAdmin()');
1080
1081
        DefaultAdminService::clearDefaultAdmin();
1082
    }
1083
1084
    /**
1085
     * Set a default admin in dev-mode
1086
     *
1087
     * This will set a static default-admin which is not existing
1088
     * as a database-record. By this workaround we can test pages in dev-mode
1089
     * with a unified login. Submitted login-credentials are first checked
1090
     * against this static information in {@link Security::authenticate()}.
1091
     *
1092
     * @param string $username The user name
1093
     * @param string $password The password (in cleartext)
1094
     * @return bool True if successfully set
1095
     *
1096
     * @deprecated 4.0.0:5.0.0 Please use DefaultAdminService::setDefaultAdmin($username, $password)
1097
     */
1098
    public static function setDefaultAdmin($username, $password)
1099
    {
1100
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::setDefaultAdmin($username, $password)');
1101
1102
        DefaultAdminService::setDefaultAdmin($username, $password);
1103
        return true;
1104
    }
1105
1106
    /**
1107
     * Checks if the passed credentials are matching the default-admin.
1108
     * Compares cleartext-password set through Security::setDefaultAdmin().
1109
     *
1110
     * @param string $username
1111
     * @param string $password
1112
     * @return bool
1113
     *
1114
     * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::isDefaultAdminCredentials() instead
1115
     */
1116
    public static function check_default_admin($username, $password)
1117
    {
1118
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::isDefaultAdminCredentials($username, $password)');
1119
1120
        /** @var DefaultAdminService $service */
1121
        return DefaultAdminService::isDefaultAdminCredentials($username, $password);
1122
    }
1123
1124
    /**
1125
     * Check that the default admin account has been set.
1126
     *
1127
     * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::hasDefaultAdmin() instead
1128
     */
1129
    public static function has_default_admin()
1130
    {
1131
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::hasDefaultAdmin()');
1132
1133
        return DefaultAdminService::hasDefaultAdmin();
1134
    }
1135
1136
    /**
1137
     * Get default admin username
1138
     *
1139
     * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::getDefaultAdminUsername()
1140
     * @return string
1141
     */
1142
    public static function default_admin_username()
1143
    {
1144
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::getDefaultAdminUsername()');
1145
1146
        return DefaultAdminService::getDefaultAdminUsername();
1147
    }
1148
1149
    /**
1150
     * Get default admin password
1151
     *
1152
     * @deprecated 4.0.0:5.0.0 Use DefaultAdminService::getDefaultAdminPassword()
1153
     * @return string
1154
     */
1155
    public static function default_admin_password()
1156
    {
1157
        Deprecation::notice('5.0.0', 'Please use DefaultAdminService::getDefaultAdminPassword()');
1158
1159
        return DefaultAdminService::getDefaultAdminPassword();
1160
    }
1161
1162
    /**
1163
     * Encrypt a password according to the current password encryption settings.
1164
     * If the settings are so that passwords shouldn't be encrypted, the
1165
     * result is simple the clear text password with an empty salt except when
1166
     * a custom algorithm ($algorithm parameter) was passed.
1167
     *
1168
     * @param string $password The password to encrypt
1169
     * @param string $salt Optional: The salt to use. If it is not passed, but
1170
     *  needed, the method will automatically create a
1171
     *  random salt that will then be returned as return value.
1172
     * @param string $algorithm Optional: Use another algorithm to encrypt the
1173
     *  password (so that the encryption algorithm can be changed over the time).
1174
     * @param Member $member Optional
1175
     * @return mixed Returns an associative array containing the encrypted
1176
     *  password and the used salt in the form:
1177
     * <code>
1178
     *  array(
1179
     *  'password' => string,
1180
     *  'salt' => string,
1181
     *  'algorithm' => string,
1182
     *  'encryptor' => PasswordEncryptor instance
1183
     *  )
1184
     * </code>
1185
     * If the passed algorithm is invalid, FALSE will be returned.
1186
     *
1187
     * @throws PasswordEncryptor_NotFoundException
1188
     * @see encrypt_passwords()
1189
     */
1190
    public static function encrypt_password($password, $salt = null, $algorithm = null, $member = null)
1191
    {
1192
        // Fall back to the default encryption algorithm
1193
        if (!$algorithm) {
1194
            $algorithm = self::config()->get('password_encryption_algorithm');
1195
        }
1196
1197
        $encryptor = PasswordEncryptor::create_for_algorithm($algorithm);
1198
1199
        // New salts will only need to be generated if the password is hashed for the first time
1200
        $salt = ($salt) ? $salt : $encryptor->salt($password);
1201
1202
        return [
1203
            'password'  => $encryptor->encrypt($password, $salt, $member),
1204
            'salt' => $salt,
1205
            'algorithm' => $algorithm,
1206
            'encryptor' => $encryptor
1207
        ];
1208
    }
1209
1210
    /**
1211
     * Checks the database is in a state to perform security checks.
1212
     * See {@link DatabaseAdmin->init()} for more information.
1213
     *
1214
     * @return bool
1215
     */
1216
    public static function database_is_ready()
1217
    {
1218
        $toCheck = [
1219
            Member::class,
1220
            Group::class,
1221
            Permission::class,
1222
        ];
1223
        foreach ($toCheck as $class) {
1224
            if (!DB::database_is_ready($class)) {
1225
                return false;
1226
            }
1227
        }
1228
1229
        return true;
1230
    }
1231
1232
    /**
1233
     * Resets the database_is_ready cache
1234
     */
1235
    public static function clear_database_is_ready()
1236
    {
1237
        $toClear = [
1238
            Member::class,
1239
            Group::class,
1240
            Permission::class,
1241
        ];
1242
        foreach ($toClear as $class) {
1243
            DB::clear_database_is_ready($class);
1244
        }
1245
    }
1246
1247
    /**
1248
     * For the database_is_ready call to return a certain value - used for testing
1249
     *
1250
     * @param bool $isReady
1251
     */
1252
    public static function force_database_is_ready($isReady)
1253
    {
1254
        $toForce = [
1255
            Member::class,
1256
            Group::class,
1257
            Permission::class,
1258
        ];
1259
        foreach ($toForce as $class) {
1260
            DB::force_database_is_ready($class, $isReady);
1261
        }
1262
    }
1263
1264
    /**
1265
     * @config
1266
     * @var string Set the default login dest
1267
     * This is the URL that users will be redirected to after they log in,
1268
     * if they haven't logged in en route to access a secured page.
1269
     * By default, this is set to the homepage.
1270
     */
1271
    private static $default_login_dest = "";
0 ignored issues
show
introduced by
The private property $default_login_dest is not used, and could be removed.
Loading history...
1272
1273
    /**
1274
     * @config
1275
     * @var string Set the default reset password destination
1276
     * This is the URL that users will be redirected to after they change their password,
1277
     * By default, it's redirecting to {@link $login}.
1278
     */
1279
    private static $default_reset_password_dest;
0 ignored issues
show
introduced by
The private property $default_reset_password_dest is not used, and could be removed.
Loading history...
1280
1281
    protected static $ignore_disallowed_actions = false;
1282
1283
    /**
1284
     * Set to true to ignore access to disallowed actions, rather than returning permission failure
1285
     * Note that this is just a flag that other code needs to check with Security::ignore_disallowed_actions()
1286
     * @param bool $flag True or false
1287
     */
1288
    public static function set_ignore_disallowed_actions($flag)
1289
    {
1290
        self::$ignore_disallowed_actions = $flag;
1291
    }
1292
1293
    public static function ignore_disallowed_actions()
1294
    {
1295
        return self::$ignore_disallowed_actions;
1296
    }
1297
1298
    /**
1299
     * Get the URL of the log-in page.
1300
     *
1301
     * To update the login url use the "Security.login_url" config setting.
1302
     *
1303
     * @return string
1304
     */
1305
    public static function login_url()
1306
    {
1307
        return Controller::join_links(Director::baseURL(), self::config()->get('login_url'));
1308
    }
1309
1310
1311
    /**
1312
     * Get the URL of the logout page.
1313
     *
1314
     * To update the logout url use the "Security.logout_url" config setting.
1315
     *
1316
     * @return string
1317
     */
1318
    public static function logout_url()
1319
    {
1320
        $logoutUrl = Controller::join_links(Director::baseURL(), self::config()->get('logout_url'));
1321
        return SecurityToken::inst()->addToUrl($logoutUrl);
1322
    }
1323
1324
    /**
1325
     * Get the URL of the logout page.
1326
     *
1327
     * To update the logout url use the "Security.logout_url" config setting.
1328
     *
1329
     * @return string
1330
     */
1331
    public static function lost_password_url()
1332
    {
1333
        return Controller::join_links(Director::baseURL(), self::config()->get('lost_password_url'));
1334
    }
1335
1336
    /**
1337
     * Defines global accessible templates variables.
1338
     *
1339
     * @return array
1340
     */
1341
    public static function get_template_global_variables()
1342
    {
1343
        return [
1344
            "LoginURL" => "login_url",
1345
            "LogoutURL" => "logout_url",
1346
            "LostPasswordURL" => "lost_password_url",
1347
            "CurrentMember"   => "getCurrentUser",
1348
            "currentUser"     => "getCurrentUser"
1349
        ];
1350
    }
1351
}
1352