1
|
|
|
<?php namespace Rde\Auth; |
2
|
|
|
|
3
|
|
|
use Closure; |
4
|
|
|
|
5
|
|
|
class Basic |
6
|
|
|
{ |
7
|
|
|
protected $rule = null; |
8
|
|
|
protected $realm; |
9
|
|
|
|
10
|
1 |
|
public function __construct($config) |
11
|
|
|
{ |
12
|
1 |
|
if (is_array($config)) { |
13
|
|
|
$this->rule = function($username, $password) use($config) { |
14
|
|
|
|
15
|
|
|
return is_string($username) && |
16
|
|
|
isset($config[$username]) && |
17
|
|
|
password_verify($password, $config[$username]); |
18
|
|
|
}; |
19
|
1 |
|
} elseif ($config instanceof Closure) { |
20
|
|
|
$this->rule = $config; |
21
|
|
|
} |
22
|
1 |
|
} |
23
|
|
|
|
24
|
1 |
|
public function realm($name) |
25
|
|
|
{ |
26
|
1 |
|
$this->realm = $name; |
27
|
1 |
|
} |
28
|
|
|
|
29
|
|
|
public function isAuthorized() |
|
|
|
|
30
|
|
|
{ |
31
|
|
|
if ($this->rule instanceof Closure) { |
32
|
|
|
|
33
|
|
|
if (isset($_SERVER['HTTP_AUTHORIZATION'])) { |
34
|
|
|
$authorization = preg_replace('/^Basic\s/', '', $_SERVER['HTTP_AUTHORIZATION']); |
35
|
|
|
$authorization = base64_decode($authorization); |
36
|
|
|
|
37
|
|
|
if (preg_match('/^(\w*):(.*)$/', $authorization, $params)) { |
38
|
|
|
return true === call_user_func($this->rule, $params[1], $params[2]); |
39
|
|
|
} |
40
|
|
|
} elseif (isset($_SERVER['PHP_AUTH_PW']) && isset($_SERVER['PHP_AUTH_USER'])) { |
41
|
|
|
return true === call_user_func($this->rule, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return false; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function challenge() |
49
|
|
|
{ |
50
|
|
|
header($this->buildAuthentication()); |
51
|
|
|
header('HTTP/1.1 401 Unauthorized'); |
52
|
|
|
exit; |
|
|
|
|
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
public function buildAuthentication() |
56
|
|
|
{ |
57
|
1 |
|
return sprintf('WWW-Authenticate: Basic realm="%s"', $this->realm ?: 'admin realm'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function logout() |
61
|
|
|
{ |
62
|
|
|
header('HTTP/1.1 401 Unauthorized'); |
63
|
|
|
exit; |
|
|
|
|
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: