b5dc5b6094fe5af62f67620b2af40387f475bef2
[racktables] / inc / auth.php
1 <?php
2 /*
3
4 Authentication library for RackTables.
5
6 */
7
8 // This function ensures that we don't continue without a legitimate
9 // username and password.
10 function authenticate ()
11 {
12 if (array_search (PASSWORD_HASH, hash_algos()) === FALSE)
13 {
14 showError ('Password hash not supported, authentication impossible.');
15 die();
16 }
17 if
18 (
19 !isset ($_SERVER['PHP_AUTH_USER']) or
20 !isset ($_SERVER['PHP_AUTH_PW']) or
21 !authenticated ($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) or
22 isset ($_REQUEST['logout'])
23 )
24 {
25 header ('WWW-Authenticate: Basic realm="' . getConfigVar ('enterprise') . ' RackTables access"');
26 header ('HTTP/1.0 401 Unauthorized');
27 showError ('This system requires authentication. You should use a username and a password.');
28 die();
29 }
30 }
31
32 // Show error unless the user is allowed access here.
33 function authorize ()
34 {
35 global $remote_username, $pageno, $tabno;
36 if (!authorized ($remote_username, $pageno, $tabno))
37 {
38 showError ("User '${remote_username}' is not allowed to access here.");
39 die();
40 }
41 }
42
43 // This function returns TRUE, if username and password are valid.
44 function authenticated ($username, $password)
45 {
46 global $accounts;
47 if (!isset ($accounts[$username]['user_password_hash']))
48 return FALSE;
49 if ($accounts[$username]['user_enabled'] != 'yes')
50 return FALSE;
51 if ($accounts[$username]['user_password_hash'] == hash (PASSWORD_HASH, $password))
52 return TRUE;
53 return FALSE;
54 }
55
56 // This function returns TRUE, if specified user has access to the
57 // page and tab.
58 function authorized ($username, $pageno, $tabno)
59 {
60 global $perms;
61 // Deny access by default, then accumulate all corrections from database.
62 // Order of nested cycles is important here!
63 // '%' as page or tab name has a special value and means "any".
64 // 0 as user_id means "any user".
65 $answer = 'no';
66 foreach (array ('%', $username) as $u)
67 foreach (array ('%', $tabno) as $t)
68 foreach (array ('%', $pageno) as $p)
69 if (isset ($perms[$u][$p][$t]))
70 $answer = $perms[$u][$p][$t];
71 if ($answer == 'yes')
72 return TRUE;
73 return FALSE;
74 }
75
76 // This function returns password hash for given user ID.
77 function getHashByID ($user_id = 0)
78 {
79 if ($user_id <= 0)
80 {
81 showError ('Invalid user_id in getHashByID()');
82 return NULL;
83 }
84 global $accounts;
85 foreach ($accounts as $account)
86 if ($account['user_id'] == $user_id)
87 return $account['user_password_hash'];
88 return NULL;
89 }
90
91 ?>