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