login/list: retrieve optional user data on demand
[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         function __get($col)
13         {
14                 return $this->$col = $this->$col();  # run method and cache
15         }
16
17         function name()
18         {
19                 return @file_get_contents("{$this->dir}/name.txt");
20         }
21 }
22
23 function login_password_verify($input, $test)
24 {
25         if (substr($test, 0, 1) != '$') {
26                 # plaintext match for uncrypted passwords
27                 return $input === $test;
28         }
29         return password_verify($input, $test);
30 }
31
32 function login_setcookie()
33 {
34         global $User;
35         return setcookie('login', $User['auth'], 0, '/');
36 }
37
38 function login($inuser, $inpass = NULL)
39 {
40         if (empty($inuser)) return;
41         if (!isset($inpass)) {
42                 @list ($inuser, $inauth) = explode(':', $inuser, 2);
43         }
44
45         # find password data by user name
46         $userdir = 'profile/'.preg_replace('/[^a-z0-9]+/', '-', strtolower($inuser));
47         $pwfile = "$userdir/.passwd";
48         if (!file_exists($pwfile)) return;
49         $usertest = trim(file_get_contents($pwfile));
50         if (!$usertest) return;
51
52         # verify password
53         $authhash = md5($usertest);
54         if (isset($inpass)) {
55                 if (!login_password_verify($inpass, $usertest)) return;
56         }
57         else {
58                 if ($inauth !== $authhash) return;
59         }
60
61         if (function_exists('apache_note')) apache_note('user', $inuser);
62
63         if ($log = @fopen("$userdir/last.log", 'w')) {
64                 fwrite($log, "{$_SERVER['REMOTE_ADDR']} {$_SERVER['HTTP_USER_AGENT']}\n");
65         }
66
67         return [
68                 'name'  => $inuser,
69                 'dir'   => $userdir,
70                 'admin' => file_exists("$userdir/.admin"),
71                 'pass'  => $usertest,
72                 'auth'  => "$inuser:$authhash",
73         ];
74 }
75
76 if (isset($_COOKIE['login'])) {
77         global $User;
78         $User = login($_COOKIE['login']);
79 }
80