-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
BasicAuth.php
56 lines (50 loc) · 1.83 KB
/
BasicAuth.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
<?php
/**
* A class for HTTP Basic Authentication
*/
class BasicAuth {
private $users;
public function __construct($passwordFile)
{
// If the password file exists, use it
if (file_exists($passwordFile)) {
$this->users = parse_ini_file($passwordFile);
} else {
// Use admin:admin if there is no password file
$this->users = [
'admin' => '$2y$10$rEulQUCZfaIYREVwmbPDG.VV4e7MwJnW1joS8TgXEjSO9Pxjf5RPq'
];
}
}
// Authenticate the user
public function auth() {
// If the username and password are not empty
if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
error_log("Not empty");
// If this user ID exists in our array
if (array_key_exists($_SERVER['PHP_AUTH_USER'], $this->users)) {
error_log("User exists");
// Grab the hash for this user from the array
$storedHash = $this->users[$_SERVER['PHP_AUTH_USER']];
// Verify the password against the hash
if (password_verify($_SERVER['PHP_AUTH_PW'], $storedHash)) {
error_log("Password verified");
// Verified
return true;
}
}
}
// Send back the header requesting authentication
header('WWW-Authenticate: Basic realm="Example Service"');
header('HTTP/1.0 401 Unauthorized');
// Some text to display if the user hits cancel
echo 'Unauthorized';
// Return false because the user isn't authenticated
return false;
}
// Bcrypt the password and return a hash
public function hash($password) {
$hash = password_hash($password, PASSWORD_BCRYPT);
return $hash;
}
}