Logic fix in user verification.
[openemr.git] / library / auth.inc
blobc70f0f064e298656d1a2e51c4d22c44cd2ee9de5
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 //----------THINGS WE ALWAYS DO
9 require_once("{$GLOBALS['srcdir']}/log.inc");
10 require_once("{$GLOBALS['srcdir']}/sql.inc");
11 // added for the phpGACL group check -- JRM
12 require_once("{$GLOBALS['srcdir']}/acl.inc");
13 require_once("$srcdir/formdata.inc.php");
14 require_once("$srcdir/authentication/login_operations.php");
16 $incoming_site_id = '';
19 if(isset($_POST['authPass']))
21     require_once("authentication/rsa.php");
22     $cp=$_POST['authPass'];
23     $rsa=new rsa_key_manager();
24     $pubKey=$_POST['pk'];
25     $rsa->load_from_db($pubKey);
26     $clearPass=$rsa->decrypt($cp);
28 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
29     isset($_POST['authPass']) && isset($_POST['authProvider']))
31     // set the language
32     if (!empty($_POST['languageChoice'])) {
33         $_SESSION['language_choice'] = $_POST['languageChoice'];
34     }
35     else {
36         $_SESSION['language_choice'] = 1;
37     }
38     
39     if(!validate_user_password($_POST['authUser'],$clearPass,$_POST['authProvider']) ||  !verify_user_gacl_group($_POST['authUser']))
40     {
41         $_SESSION['loginfailure'] = 1;
42         authLoginScreen();
43     }
44 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
45     
46     if($GLOBALS['password_expiration_days'] != 0){
47         if(authCheckExpired($_POST['authUser']))
48         {
49             authLoginScreen();
50         }
51     }
52     $ip=$_SERVER['REMOTE_ADDR'];
53     $_SESSION['loginfailure'] = null;
54     unset($_SESSION['loginfailure']);
55     //store the very first initial timestamp for timeout errors
56     $_SESSION["last_update"] = time();
58 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
60     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
61     authCloseSession();
62     authLoginScreen();
64 else
66     if (authCheckSession())
67     {
68         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
69         {
70             require_once("{$GLOBALS['srcdir']}/patient.inc");
71             /**
72             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
73             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
74                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
75                 $_SESSION['encounter']);
76             **/
77         }
78         //LOG EVERYTHING
79         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
80     }
81     else {
82         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
83         authLoginScreen();
84     }
87 if (!isset($_SESSION["last_update"])) {
88     authLoginScreen();
89 } else {
90      //if page has not been updated in a given period of time, we call login screen
91     if ((time() - $_SESSION["last_update"]) > $timeout) {
92         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
93         authCloseSession();
94         authLoginScreen();
95     } else {
96         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
97         //  can be used by scripts that continually request information from the server; for example the Messages
98         //  and Reminders automated intermittent requests that happen in the Messages Center script and in 
99         //  the left navigation menu script.
100         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) $_SESSION["last_update"] = time();
101     }
104 //----------THINGS WE DO IF WE STILL LIKE YOU
106 function authCheckSession ()
108     if (isset($_SESSION['authId'])) {
109         $authDB = sqlQuery("select username, password from users where id = ?",array($_SESSION['authId']));
110         if ($_SESSION['authUser'] == $authDB['username'] )
111         {
112             return true;
113         }
114         else {
115             return false;
116         }
117     }
118     else {
119         return false;
120     }
123 function authCloseSession ()
125   // Before destroying the session, save its site_id so that the next
126   // login will default to that same site.
127   global $incoming_site_id;
128   $incoming_site_id = $_SESSION['site_id'];
129   ob_start();
130   session_unset();
131   session_destroy();
132   unset($_COOKIE[session_name()]);
135 function authLoginScreen()
137   // See comment in authCloseSession().
138   global $incoming_site_id;
139   header("Location: {$GLOBALS['login_screen']}?error=1&site=$incoming_site_id");
140   exit;
143 // Check if the user's password has expired beyond the grace limit.
144 // If so, deactivate the user
145 function authCheckExpired($user)
147   $result = sqlStatement("select pwd_expiration_date from users where username = ?",array($user));
148   if($row = sqlFetchArray($result)) 
149   {
150     $pwd_expires = $row['pwd_expiration_date'];
151   }
152   $current_date = date("Y-m-d");
153   if($pwd_expires != "0000-00-00")
154   {
155     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
156   }
157   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
158   {
159     sqlStatement("update users set active=0 where username = ?",array($user));
160     $_SESSION['loginfailure'] = 1;
161     return true;
162   }
163   return false;
166 function getUserList ($cols = '*', $limit = 'all', $start = '0')
168     if ($limit = "all")
169         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
170     else
171         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
172     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
173         $tbl[$iter] = $row;
174     return $tbl;
177 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
179     if ($limit = "all")
180         $rez = sqlStatement("select $cols from groups order by date DESC");
181     else
182         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
183     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
184         $tbl[$iter] = $row;
185     return $tbl;
188 function addGroup ($groupname)
190     return sqlInsert("insert into groups (name) values ('$groupname')");
193 function delGroup ($group_id)
195     return sqlQuery("delete from groups where id = '$group_id' limit 0,1");
198 /***************************************************************
199 //pennfirm
200 //Function currently user by new post calendar code to determine
201 //if a given user is in a group with another user
202 //and if so to allow editing of that users events
204 //*************************************************************/
206 function validateGroupStatus ($user_to_be_checked, $group_user) {
207     if (isset($user_to_be_checked) && isset($group_user)) {
208         if ($user_to_be_checked == $group_user) {
210             return true;
211         }
212         elseif ($_SESSION['authorizeduser'] == 1)
213             return true;
215         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($user_to_be_checked) . "\" " .
216                  "AND users.username = groups.user group by groups.name";
217         $result = sqlStatement($query);
219         $usertbcGroups = array();
221         while ($row = mysql_fetch_array($result)) {
222             $usertbcGroups[] = $row[0];
223         }
225         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($group_user) . "\" " .
226                  "AND users.username = groups.user group by groups.name";
227         $result = sqlStatement($query);
229         $usergGroups = array();
231         while ($row = mysql_fetch_array($result)) {
232             $usergGroups[] = $row[0];
233         }
234         foreach ($usertbcGroups as $group) {
235               if(in_array($group,$usergGroups)) {
236               return true;
237             }
238         }
240     }
242     return false;
246 // Attempt to update the user's password, password history, and password expiration.
247 // Verify that the new password does not match the last three passwords used.
248 // Return true if successfull, false on failure
249 function UpdatePasswordHistory($userid,$pwd)
251     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?",array($userid));
252     if ($row = sqlFetchArray($result)) {
253         $previous_pwd1=$row['password'];
254         $previous_pwd2=$row['pwd_history1'];
255         $previous_pwd3=$row['pwd_history2'];
256     }
257     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
258         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?",array($previous_pwd2,$previous_pwd1,$pwd,$userid));
259         if($GLOBALS['password_expiration_days'] != 0){
260         $exp_days=$GLOBALS['password_expiration_days'];
261         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
262         sqlStatement("update users set pwd_expiration_date=? where id=?",array($exp_date,$userid));
263         }
264         return true;
265     } 
266     else {
267         return false;
268     }