improvements to test suite to allow it to run from a clean repository
[openemr.git] / library / auth.inc
bloba998e85b7dea7b9cdce1fc330b6611d0486bab4d
1 <?php
2 //----------THINGS WE ALWAYS DO
4 require_once("{$GLOBALS['srcdir']}/log.inc");
5 require_once("{$GLOBALS['srcdir']}/sql.inc");
6 // added for the phpGACL group check -- JRM
7 require_once("{$GLOBALS['srcdir']}/acl.inc");
8 require_once("$srcdir/formdata.inc.php");
10 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
11     isset($_POST['authPass']) && isset($_POST['authProvider']))
13     // set the language
14     if (!empty($_POST['languageChoice'])) {
15         $_SESSION['language_choice'] = $_POST['languageChoice'];
16     }
17     else {
18         $_SESSION['language_choice'] = 1;
19     }
20 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
21     if($GLOBALS['password_expiration_days'] != 0){
22         authCheckExpired();
23     }
24     $ip=$_SERVER['REMOTE_ADDR'];
25     if (!authNewSession($_POST['authUser'], $_POST['authPass'], $_POST['authProvider']))
26     {
27         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "failure: $ip");
28         $_SESSION['loginfailure'] = 1;
29         authLoginScreen();
30     }
31     newEvent("login", $_POST['authUser'], $_POST['authProvider'], 1, "success: $ip");
32     $_SESSION['loginfailure'] = null;
33     unset($_SESSION['loginfailure']);
34     //store the very first initial timestamp for timeout errors
35     $_SESSION["last_update"] = time();
37 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
39     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
40     authCloseSession();
41     authLoginScreen();
43 else
45     if (authCheckSession())
46     {
47         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
48         {
49             require_once("{$GLOBALS['srcdir']}/patient.inc");
50             /**
51             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
52             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
53                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
54                 $_SESSION['encounter']);
55             **/
56         }
57         //LOG EVERYTHING
58         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
59     }
60     else {
61         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
62         authLoginScreen();
63     }
66 if (!isset($_SESSION["last_update"])) {
67     authLoginScreen();
68 } else {
69      //if page has not been updated in a given period of time, we call login screen
70     if ((time() - $_SESSION["last_update"]) > $timeout) {
71         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
72         authCloseSession();
73         authLoginScreen();
74     } else {
75         if (empty($GLOBALS['DAEMON_FLAG'])) $_SESSION["last_update"] = time();
76     }
79 //----------THINGS WE DO IF WE STILL LIKE YOU
81 function authNewSession ($user, $pass, $provider)
83     // check to see if the user belongs to *any* OpenEMR groups in phpGACL -- JRM
84     global $phpgacl_location;
85     if (isset ($phpgacl_location)) {
86         if (acl_get_group_titles($user) == 0) return false;
87     }
89     // get details about the user
90     $authDB = sqlQuery("select id, password, authorized, see_auth".
91                         ", cal_ui, active ".
92                         " from users where username = '$user'");
94     // if the user is NOT active, get out
95     if ($authDB['active'] != 1) { return false; }
97     // start the HTTP SESSION
98     if(!session_id()) { session_start(); }
100     // compare the submitted password with the stored password
101     if ($authDB['password'] == $pass)
102     {
103         //here, we check to see if the user is in fact a member of the correct group:
104         if ($authGroup = sqlQuery("select * from groups where user='$user' and name='$provider'"))
105         {
106             $_SESSION['authUser'] = $user;
107             $_SESSION['authGroup'] = $authGroup['name'];
108             $_SESSION['authUserID'] = $authDB['id'];
109             $_SESSION['authPass'] = $pass;
110             $_SESSION['authProvider'] = $provider;
111             $_SESSION['authId'] = $authDB{'id'};
112             $_SESSION['cal_ui'] = $authDB['cal_ui'];
113             $_SESSION['userauthorized'] = $authDB['authorized'];
114             // Some users may be able to authorize without being providers:
115             if ($authDB['see_auth'] > '2') $_SESSION['userauthorized'] = '1';
116             return true;
117         } else {
118             return false;
119         }
120     }
121     else
122         return false;
125 function authCheckSession ()
127     if (isset($_SESSION['authId'])) {
128         $authDB = sqlQuery("select username, password from users where id = '" .
129             $_SESSION['authId']."'");
130         if ($_SESSION['authUser'] == $authDB['username'] &&
131             $_SESSION['authPass'] == $authDB['password'])
132         {
133             return true;
134         }
135         else {
136             return false;
137         }
138     }
139     else {
140         return false;
141     }
144 function authCloseSession ()
146     ob_start();
147     session_unset();
148 //    $_SESSION = array();
149     session_destroy();
150     //setcookie(session_name(),"","","/");
151     //the following does the same as the above line:
152     //if(isset($_COOKIE[session_name()])) {
153     // session_start();
154     // session_destroy();
155     unset($_COOKIE[session_name()]);
156     //}
159 function authLoginScreen()
161     //header("Location: https://{$_SERVER['HTTP_HOST']}{$GLOBALS['login_screen']}");
162     header("Location: {$GLOBALS['login_screen']}?error=1");
163     exit;
166 // Check if the user's password has expired beyond the grace limit.
167 // If so, deactivate the user
168 function authCheckExpired()
170   $auser=formData('authUser','P');
171   $result = sqlStatement("select pwd_expiration_date from users where username = '".$auser."'");
172   if($row = sqlFetchArray($result)) 
173   {
174     $pwd_expires = $row['pwd_expiration_date'];
175   }
176   $current_date = date("Y-m-d");
177   if($pwd_expires != "0000-00-00")
178   {
179     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
180   }
181   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
182   {
183     sqlStatement("update users set active=0 where username = '".$auser."'");
184     $_SESSION['loginfailure'] = 1;
185   }
189 function addUser ($username, $password_md5, $info, $authorized = 'yes')
191     return sqlInsert("insert into users (username, password, info, authorized) values ('$username', '$password_md5', '$info', '$authorized')");
194 function delUser ($id)
196     return sqlQuery("delete from users where id = '$id' limit 0,1");
199 function changePasword ($id, $new_md5)
201     return sqlQuery("update users set password = '$new_md5' where id = '$id'");
204 function getUserList ($cols = '*', $limit = 'all', $start = '0')
206     if ($limit = "all")
207         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
208     else
209         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
210     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
211         $tbl[$iter] = $row;
212     return $tbl;
215 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
217     if ($limit = "all")
218         $rez = sqlStatement("select $cols from groups order by date DESC");
219     else
220         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
221     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
222         $tbl[$iter] = $row;
223     return $tbl;
226 function addGroup ($groupname)
228     return sqlInsert("insert into groups (name) values ('$groupname')");
231 function delGroup ($group_id)
233     return sqlQuery("delete from groups where id = '$group_id' limit 0,1");
236 /***************************************************************
237 //pennfirm
238 //Function currently user by new post calendar code to determine
239 //if a given user is in a group with another user
240 //and if so to allow editing of that users events
242 //*************************************************************/
244 function validateGroupStatus ($user_to_be_checked, $group_user) {
245     if (isset($user_to_be_checked) && isset($group_user)) {
246         if ($user_to_be_checked == $group_user) {
248             return true;
249         }
250         elseif ($_SESSION['authorizeduser'] == 1)
251             return true;
253         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($user_to_be_checked) . "\" " .
254                  "AND users.username = groups.user group by groups.name";
255         $result = sqlStatement($query);
257         $usertbcGroups = array();
259         while ($row = mysql_fetch_array($result)) {
260             $usertbcGroups[] = $row[0];
261         }
263         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($group_user) . "\" " .
264                  "AND users.username = groups.user group by groups.name";
265         $result = sqlStatement($query);
267         $usergGroups = array();
269         while ($row = mysql_fetch_array($result)) {
270             $usergGroups[] = $row[0];
271         }
272         foreach ($usertbcGroups as $group) {
273               if(in_array($group,$usergGroups)) {
274               return true;
275             }
276         }
278     }
280     return false;
284 // Attempt to update the user's password, password history, and password expiration.
285 // Verify that the new password does not match the last three passwords used.
286 // Return true if successfull, false on failure
287 function UpdatePasswordHistory($userid,$pwd)
289     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = $userid");
290     if ($row = sqlFetchArray($result)) {
291         $previous_pwd1=$row['password'];
292         $previous_pwd2=$row['pwd_history1'];
293         $previous_pwd3=$row['pwd_history2'];
294     }
295     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
296         sqlStatement("update users set pwd_history2='$previous_pwd2', pwd_history1='$previous_pwd1',password='$pwd' where id=$userid");
297         if($GLOBALS['password_expiration_days'] != 0){
298         $exp_days=$GLOBALS['password_expiration_days'];
299         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
300         sqlStatement("update users set pwd_expiration_date='$exp_date' where id=$userid");
301         }
302         return true;
303     } 
304     else {
305         return false;
306     }