69 lines
2.8 KiB
PHP
69 lines
2.8 KiB
PHP
<?php
|
|
namespace ktk\MusicServe;
|
|
|
|
class BasicAuth {
|
|
static private $realm = "ktk_MusicServe";
|
|
static private $auth_file = "BasicAuth";
|
|
static private $creds = array();
|
|
|
|
static public function onInit() {
|
|
self::$creds = MusicServe::loadConf(self::$auth_file);
|
|
if (!isset($_SESSION['logged'])) {
|
|
self::doAuth();
|
|
}
|
|
}
|
|
static public function onRender() {
|
|
echo ' <div id="ktk_MusicServe_BasicAuth">'.PHP_EOL;
|
|
echo ' <form action="" method="POST">';
|
|
echo ' <input type="hidden" name="m" value="BasicAuth" />';
|
|
echo ' <input type="hidden" name="c" value="doLogout" />';
|
|
echo ' <input type="submit" name="" value="Exit" />';
|
|
echo ' </form>';
|
|
echo ' </div>';
|
|
}
|
|
static public function doLogout() {
|
|
if (ini_get("session.use_cookies")) {
|
|
$params = session_get_cookie_params();
|
|
setcookie(session_name(), '', time() - 42000,
|
|
$params["path"], $params["domain"],
|
|
$params["secure"], $params["httponly"]
|
|
);
|
|
session_destroy();
|
|
session_unset($_SESSION['logged']);
|
|
header('HTTP/1.1 401 Unauthorized');
|
|
die("Logged out, please <a href=\"".$_SERVER['PHP_SELF']."\">click here</a> to login");
|
|
}
|
|
}
|
|
static public function doAuth() {
|
|
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
|
|
header('HTTP/1.1 401 Unauthorized');
|
|
header('WWW-Authenticate: Digest realm="'.self::$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.md5(self::$realm).'"');
|
|
die("Canceled - refresh or <a href=\"".$_SERVER['PHP_SELF']."\">click here</a> to try again");
|
|
}
|
|
if (!($data = self::parseHttpDigest($_SERVER['PHP_AUTH_DIGEST'])) || !isset(self::$creds[$data['username']])) {
|
|
header('HTTP/1.1 401 Unauthorized');
|
|
die("Incorrect credentials, please <a href=\"".$_SERVER['PHP_SELF']."\">click here</a> to try again");
|
|
}
|
|
$A1 = md5($data['username'] . ':' . self::$realm . ':' . self::$creds[$data['username']]);
|
|
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
|
|
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
|
|
if ($data['response'] != $valid_response) {
|
|
header('HTTP/1.1 401 Unauthorized');
|
|
die("Incorrect credentials, please <a href=\"".$_SERVER['PHP_SELF']."\">click here</a> to try again");
|
|
}
|
|
$_SESSION['logged'] = TRUE;
|
|
}
|
|
static public function parseHttpDigest($text) {
|
|
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
|
|
$data = array();
|
|
$keys = implode('|', array_keys($needed_parts));
|
|
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $text, $matches, PREG_SET_ORDER);
|
|
foreach ($matches as $m) {
|
|
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
|
|
unset($needed_parts[$m[1]]);
|
|
}
|
|
return $needed_parts ? false : $data;
|
|
}
|
|
}
|
|
?>
|