1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the PHP Generics package. |
5
|
|
|
* |
6
|
|
|
* @package Generics |
7
|
|
|
*/ |
8
|
|
|
namespace Generics\Util; |
9
|
|
|
|
10
|
|
|
use Generics\GenericsException; |
11
|
|
|
use Generics\Client\HttpStatus; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* This class provides http basic auth provider |
15
|
|
|
* |
16
|
|
|
* @author Maik Greubel <[email protected]> |
17
|
|
|
* |
18
|
|
|
*/ |
19
|
|
|
class BasicAuth |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* The basic auth user |
24
|
|
|
* |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $user; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* The basic auth password |
31
|
|
|
* |
32
|
|
|
* @var string |
33
|
|
|
*/ |
34
|
|
|
private $password; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* The list of files to skip authentication |
38
|
|
|
* |
39
|
|
|
* @var array |
40
|
|
|
*/ |
41
|
|
|
private $whitelist; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Realm name |
45
|
|
|
* |
46
|
|
|
* @var string |
47
|
|
|
*/ |
48
|
|
|
private $realm; |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Create a new basic auth instance |
52
|
|
|
* |
53
|
|
|
* @param string $user |
54
|
|
|
* The username |
55
|
|
|
* @param string $password |
56
|
|
|
* The password |
57
|
|
|
* @param array $whitelist |
58
|
|
|
* The list of files to skip authentication |
59
|
|
|
* @param string $realm |
60
|
|
|
* The name of the realm |
61
|
|
|
*/ |
62
|
|
|
public function __construct($user, $password, $whitelist = array(), $realm = "Authentication realm") |
63
|
|
|
{ |
64
|
|
|
$this->user = $user; |
65
|
|
|
$this->password = $password; |
66
|
|
|
$this->whitelist = $whitelist; |
67
|
|
|
$this->realm = $realm; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Perform authentication |
72
|
|
|
* |
73
|
|
|
* @param string $file |
74
|
|
|
* @throws GenericsException |
75
|
|
|
* @return bool |
76
|
|
|
*/ |
77
|
|
|
public function auth($file = ''): bool |
78
|
|
|
{ |
79
|
|
|
if (php_sapi_name() == 'cli') { |
80
|
|
|
throw new GenericsException("CLI does not support basic auth!"); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if ($file && in_array($file, $this->whitelist)) { |
84
|
|
|
return true; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
$user = null; |
88
|
|
|
$password = null; |
89
|
|
|
|
90
|
|
|
if (isset($_SERVER['PHP_AUTH_USER'])) { |
91
|
|
|
$user = $_SERVER['PHP_AUTH_USER']; |
92
|
|
|
} |
93
|
|
|
if (isset($_SERVER['PHP_AUTH_PW'])) { |
94
|
|
|
$password = $_SERVER['PHP_AUTH_PW']; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
if ($user && $password && $user == $this->user && $password == $this->password) { |
98
|
|
|
return true; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
$httpStatus = new HttpStatus(401, '1.0'); |
102
|
|
|
header('WWW-Authenticate: Basic realm=' . $this->realm); |
103
|
|
|
header(sprintf('HTTP/%s', $httpStatus)); |
104
|
|
|
echo "Forbidden!"; |
105
|
|
|
return false; |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|