minor improvement to tabs style
[openemr.git] / library / auth.inc
blob200f6c11841aeb3a3e27bf4f211e3fcb3efb1a2d
1 <?php
2 /**
3  * Authorization functions.
4  *
5  * LICENSE: This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
15  *
16  * @package OpenEMR
17  * @author  Rod Roark <rod@sunsetsystems.com>
18  * @author  Brady Miller <brady.g.miller@gmail.com>
19  * @author  Kevin Yeh <kevin.y@integralemr.com>
20  * @author  ViCarePlus <visolve_emr@visolve.com>
21  * @author  cfapress
22  * @link    http://www.open-emr.org
23  */
25 //----------THINGS WE ALWAYS DO
27 require_once("{$GLOBALS['srcdir']}/log.inc");
28 // added for the phpGACL group check -- JRM
29 require_once("{$GLOBALS['srcdir']}/acl.inc");
30 require_once("$srcdir/authentication/login_operations.php");
32 $incoming_site_id = '';
34 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
35     isset($_POST['clearPass']) && isset($_POST['authProvider']))
37     $clearPass=$_POST['clearPass'];
38     // set the language
39     if (!empty($_POST['languageChoice'])) {
40         $_SESSION['language_choice'] = $_POST['languageChoice'];
41     }
42     else {
43         $_SESSION['language_choice'] = 1;
44     }
45     // set language direction according to language choice. Later in globals.php we'll override main theme name if needed.
46     $_SESSION['language_direction'] = getLanguageDir($_SESSION['language_choice']  );
48     if(!validate_user_password($_POST['authUser'],$clearPass,$_POST['authProvider']) ||  !verify_user_gacl_group($_POST['authUser']))
49     {
50         $_SESSION['loginfailure'] = 1;
51         authLoginScreen();
52     }
53 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
55     if($GLOBALS['password_expiration_days'] != 0){
56         if(authCheckExpired($_POST['authUser']))
57         {
58             authLoginScreen();
59         }
60     }
61     $ip=$_SERVER['REMOTE_ADDR'];
62     $_SESSION['loginfailure'] = null;
63     unset($_SESSION['loginfailure']);
64     //store the very first initial timestamp for timeout errors
65     $_SESSION["last_update"] = time();
67 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
69     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
70     authCloseSession();
71     authLoginScreen(true);
73 else
75     if (authCheckSession())
76     {
77         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
78         {
79             require_once("{$GLOBALS['srcdir']}/patient.inc");
80             /**
81             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
82             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
83                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
84                 $_SESSION['encounter']);
85             **/
86         }
87         //LOG EVERYTHING
88         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
89     }
90     else {
91         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
92         authLoginScreen();
93     }
96 if (!isset($_SESSION["last_update"])) {
97     authLoginScreen();
98 } else {
99      //if page has not been updated in a given period of time, we call login screen
100      //--Note can't perform nice logout if skip_timeout_reset is set since these are called
101      //via ajax scripts where this output is not getting sent to browser.
102      //--Note DAEMON_FLAG is ok because it is run from a frame in the browser.
103     if ( ((time() - $_SESSION["last_update"]) > $timeout) && empty($_REQUEST['skip_timeout_reset']) ) {
104         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
105         authCloseSession();
106         authLoginScreen(true);
107     } else {
108         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
109         //  can be used by scripts that continually request information from the server; for example the Messages
110         //  and Reminders automated intermittent requests that happen in the Messages Center script and in
111         //  the left navigation menu script.
112         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) $_SESSION["last_update"] = time();
113     }
118 //----------THINGS WE DO IF WE STILL LIKE YOU
120 function authCheckSession ()
122     if (isset($_SESSION['authId'])) {
123          // If active directory was used, check a different session variable (as there is no password in database).
124         if($GLOBALS['use_active_directory'])
125         {
126             if($_SESSION['active_directory_auth'])
127             {
128                 return true;
129             }
130             else
131             {
132                 return false;
133             }
134         }
135         $authDB = privQuery("select ".implode(",",array(TBL_USERS.".".COL_ID,
136                                                         TBL_USERS.".".COL_UNM,
137                                                         TBL_USERS_SECURE.".".COL_PWD,
138                                                         TBL_USERS_SECURE.".".COL_ID))
139                 . " FROM ". implode(",",array(TBL_USERS,TBL_USERS_SECURE))
140                 . " WHERE ". TBL_USERS.".".COL_ID." = ? "
141                 . " AND ". TBL_USERS.".".COL_UNM . "=" . TBL_USERS_SECURE.".".COL_UNM
142                 . " AND ". TBL_USERS.".".COL_ACTIVE . "=1"
143                 ,array($_SESSION['authId']));
144         if ($_SESSION['authUser'] == $authDB['username']
145             && $_SESSION['authPass'] == $authDB['password'] )
146         {
147             return true;
148         }
149         else {
150             return false;
151         }
152     }
153     else {
154         return false;
155     }
158 function authCloseSession ()
160   // Before destroying the session, save its site_id so that the next
161   // login will default to that same site.
162   global $incoming_site_id;
163   $incoming_site_id = $_SESSION['site_id'];
164   ob_start();
165   session_unset();
166   session_destroy();
167   unset($_COOKIE[session_name()]);
170 function authLoginScreen($timed_out = false)
172   // See comment in authCloseSession().
173   global $incoming_site_id;
175 <script>
176  // Find the top level window for this instance of OpenEMR, set a flag indicating
177  // session timeout has occurred, and reload the login page into it.  This is so
178  // that beforeunload event handlers will not obstruct the process in this case.
179  var w = window;
180  while (w.opener) { // in case we are in a dialog window
181   var wtmp = w;
182   w = w.opener;
183   wtmp.close();
185 <?php if ($timed_out) { ?>
186  w.top.timed_out = true;
187 <?php } ?>
188  w.top.location.href = '<?php echo "{$GLOBALS['login_screen']}?error=1&site=$incoming_site_id"; ?>';
189 </script>
190 <?php
191   exit;
194 // Check if the user's password has expired beyond the grace limit.
195 // If so, deactivate the user
196 function authCheckExpired($user)
198   $result = sqlStatement("select pwd_expiration_date from users where username = ?",array($user));
199   if($row = sqlFetchArray($result))
200   {
201     $pwd_expires = $row['pwd_expiration_date'];
202   }
203   $current_date = date("Y-m-d");
204   if($pwd_expires != "0000-00-00")
205   {
206     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
207   }
208   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
209   {
210     sqlStatement("update users set active=0 where username = ?",array($user));
211     $_SESSION['loginfailure'] = 1;
212     return true;
213   }
214   return false;
217 function getUserList ($cols = '*', $limit = 'all', $start = '0')
219     if ($limit = "all")
220         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
221     else
222         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
223     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
224         $tbl[$iter] = $row;
225     return $tbl;
228 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
230     if ($limit = "all")
231         $rez = sqlStatement("select $cols from groups order by date DESC");
232     else
233         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
234     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
235         $tbl[$iter] = $row;
236     return $tbl;
239 function addGroup ($groupname)
241     return sqlInsert("insert into groups (name) values (?)", array($groupname));
244 function delGroup ($group_id)
246     return sqlQuery("delete from groups where id = ? limit 0,1", array($group_id));
249 /***************************************************************
250 //pennfirm
251 //Function currently user by new post calendar code to determine
252 //if a given user is in a group with another user
253 //and if so to allow editing of that users events
255 //*************************************************************/
257 function validateGroupStatus ($user_to_be_checked, $group_user) {
258     if (isset($user_to_be_checked) && isset($group_user)) {
259         if ($user_to_be_checked == $group_user) {
261             return true;
262         }
263         elseif ($_SESSION['authorizeduser'] == 1)
264             return true;
266         $query = "SELECT groups.name FROM users,groups WHERE users.username = ? " .
267                  "AND users.username = groups.user group by groups.name";
268         $result = sqlStatement($query, array($user_to_be_checked));
270         $usertbcGroups = array();
272         while ($row = sqlFetchArray($result)) {
273             $usertbcGroups[] = $row[0];
274         }
276         $query = "SELECT groups.name FROM users,groups WHERE users.username =  ? " .
277                  "AND users.username = groups.user group by groups.name";
278         $result = sqlStatement($query, array($group_user));
280         $usergGroups = array();
282         while ($row = sqlFetchArray($result)) {
283             $usergGroups[] = $row[0];
284         }
285         foreach ($usertbcGroups as $group) {
286               if(in_array($group,$usergGroups)) {
287               return true;
288             }
289         }
291     }
293     return false;
297 // Attempt to update the user's password, password history, and password expiration.
298 // Verify that the new password does not match the last three passwords used.
299 // Return true if successfull, false on failure
300 function UpdatePasswordHistory($userid,$pwd)
302     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?",array($userid));
303     if ($row = sqlFetchArray($result)) {
304         $previous_pwd1=$row['password'];
305         $previous_pwd2=$row['pwd_history1'];
306         $previous_pwd3=$row['pwd_history2'];
307     }
308     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
309         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?",array($previous_pwd2,$previous_pwd1,$pwd,$userid));
310         if($GLOBALS['password_expiration_days'] != 0){
311         $exp_days=$GLOBALS['password_expiration_days'];
312         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
313         sqlStatement("update users set pwd_expiration_date=? where id=?",array($exp_date,$userid));
314         }
315         return true;
316     }
317     else {
318         return false;
319     }