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