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