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