login/list: profile class to access user data
[minimedit.git] / auth.inc.php
1 <?php
2 date_default_timezone_set('Europe/Amsterdam');
3
4 class User
5 {
6         function __construct($dir)
7         {
8                 $this->dir = $dir;
9                 $this->login = basename($dir);
10         }
11 }
12
13 function login_password_verify($input, $test)
14 {
15         if (substr($test, 0, 1) != '$') {
16                 # plaintext match for uncrypted passwords
17                 return $input === $test;
18         }
19         return password_verify($input, $test);
20 }
21
22 function login_setcookie()
23 {
24         global $User;
25         return setcookie('login', $User['auth'], 0, '/');
26 }
27
28 function login($inuser, $inpass = NULL)
29 {
30         if (empty($inuser)) return;
31         if (!isset($inpass)) {
32                 @list ($inuser, $inauth) = explode(':', $inuser, 2);
33         }
34
35         # find password data by user name
36         $userdir = 'profile/'.preg_replace('/[^a-z0-9]+/', '-', strtolower($inuser));
37         $pwfile = "$userdir/.passwd";
38         if (!file_exists($pwfile)) return;
39         $usertest = trim(file_get_contents($pwfile));
40         if (!$usertest) return;
41
42         # verify password
43         $authhash = md5($usertest);
44         if (isset($inpass)) {
45                 if (!login_password_verify($inpass, $usertest)) return;
46         }
47         else {
48                 if ($inauth !== $authhash) return;
49         }
50
51         if (function_exists('apache_note')) apache_note('user', $inuser);
52
53         if ($log = @fopen("$userdir/last.log", 'w')) {
54                 fwrite($log, "{$_SERVER['REMOTE_ADDR']} {$_SERVER['HTTP_USER_AGENT']}\n");
55         }
56
57         return [
58                 'name'  => $inuser,
59                 'dir'   => $userdir,
60                 'admin' => file_exists("$userdir/.admin"),
61                 'pass'  => $usertest,
62                 'auth'  => "$inuser:$authhash",
63         ];
64 }
65
66 if (isset($_COOKIE['login'])) {
67         global $User;
68         $User = login($_COOKIE['login']);
69 }
70