login: replace http authentication by cookie system
[minimedit.git] / auth.inc.php
index ecd29b5cc36ca971c9183f9a11ddd31d180d9f24..363fc71538b0527be14ac901fe3fb9c99692c604 100755 (executable)
@@ -1,19 +1,13 @@
 <?php
-global $User, $Admin;
-
-call_user_func(function () {
-       if (isset($_SERVER['PHP_AUTH_USER'])) {
-               $authinfo = [ $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ];
-       }
-       elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
-               // cgi compatibility
-               $authinfo = explode(':' , base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
-       }
-       else {
-               return;
+function login($inuser, $inpass = NULL)
+{
+       if (empty($inuser)) return;
+       if (!isset($inpass)) {
+               @list ($inuser, $inauth) = explode(':', $inuser, 2);
        }
 
-       $pwdata = file_get_contents(__DIR__.'/.htpasswd');
+       # create pwlist table from htpasswd
+       $pwdata = file_get_contents('./.htpasswd');
        $pwlist = [];
        foreach (explode("\n", $pwdata) as $line) {
                if (!$line) continue;
@@ -21,15 +15,28 @@ call_user_func(function () {
                $pwlist[$username] = $pass;
        }
 
-       list ($authname, $authpass) = $authinfo;
-       $usertest = $pwlist[ strtolower($authname) ];
+       # find user by name
+       $usertest = @$pwlist[ strtolower($inuser) ];
        if (!$usertest) return;
 
-       $salt = substr($usertest, 0, 2);
-       if (crypt($authpass, $salt) != $usertest) return;
+       # verify password
+       $authhash = md5($usertest);
+       if (isset($inpass)) {
+               if (!password_verify($inpass, $usertest)) return;
+       }
+       else {
+               if ($inauth !== $authhash) return;
+       }
+
+       return [
+               'name'  => $inuser,
+               'admin' => !empty($inuser) && strtolower($inuser) != 'lid',
+               'auth'  => "$inuser:$authhash",
+       ];
+}
 
-       global $User, $Admin;
-       $User = $authname;
-       $Admin = !empty($User) && $User != 'lid' ? $User : FALSE;
-});
+if (isset($_COOKIE['login'])) {
+       global $User;
+       $User = login($_COOKIE['login']);
+}