Passed
Push — master ( 15ba7a...7142ee )
by Thomas
02:15
created

AdminBasicAuth::protect()   B

Complexity

Conditions 7
Paths 48

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
c 1
b 0
f 0
nc 48
nop 2
dl 0
loc 19
rs 8.8333
1
<?php
2
3
namespace LeKoala\DevToolkit;
4
5
use SilverStripe\Core\Environment;
6
7
/**
8
 * A dead simple alternative to built-in basic auth that is controlled with SS_USE_BASIC_AUTH
9
 * This one will simply check for .env admin and use native php functions to return the response
10
 */
11
class AdminBasicAuth
12
{
13
    /**
14
     * Require admin login
15
     *
16
     * @param string $user
17
     * @param string $password
18
     * @return void
19
     */
20
    public static function protect($user = null, $password = null)
21
    {
22
        if (!$user) {
23
            $user = Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME');
24
        }
25
        if (!$password) {
26
            $password = Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD');
27
        }
28
        header('Cache-Control: no-cache, must-revalidate, max-age=0');
29
        $hasSuppliedCredentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
30
        if ($hasSuppliedCredentials) {
31
            $isNotAuthenticated = ($_SERVER['PHP_AUTH_USER'] != $user || $_SERVER['PHP_AUTH_PW'] != $password);
32
        } else {
33
            $isNotAuthenticated = true;
34
        }
35
        if ($isNotAuthenticated) {
36
            header('HTTP/1.1 401 Authorization Required');
37
            header('WWW-Authenticate: Basic realm="Access denied"');
38
            exit;
39
        }
40
    }
41
}
42