Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / auth.inc
blobe0030d92d3dfe814cc4b933fefd1a57ace08930c
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 // added for the phpGACL group check -- JRM
28 require_once("{$GLOBALS['srcdir']}/acl.inc");
29 require_once("$srcdir/authentication/login_operations.php");
31 use OpenEMR\Common\Logging\EventAuditLogger;
33 $incoming_site_id = '';
35 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
36     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     } else {
42         $_SESSION['language_choice'] = 1;
43     }
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'])
49      || !verify_user_gacl_group($_POST['authUser'], $_POST['authProvider'])) {
50         $_SESSION['loginfailure'] = 1;
51         authLoginScreen();
52     }
54 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
56     if ($GLOBALS['password_expiration_days'] != 0) {
57         if (authCheckExpired($_POST['authUser'])) {
58             authLoginScreen();
59         }
60     }
62     $_SESSION['loginfailure'] = null;
63     unset($_SESSION['loginfailure']);
64     //store the very first initial timestamp for timeout errors
65     $_SESSION["last_update"] = time();
66 } else if ((isset($_GET['auth'])) && ($_GET['auth'] == "logout")) {
67     //If session has timed out / been destroyed, logout record for null user/provider will be invalid.
68     if (!empty($_SESSION['authUser']) && !empty($_SESSION['authProvider'])) {
69         EventAuditLogger::instance()->newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
70     }
71     authCloseSession();
72     authLoginScreen(true);
73 } else {
74     if (authCheckSession()) {
75         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG'])) {
76             require_once("{$GLOBALS['srcdir']}/patient.inc");
77             /**
78             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
79             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
80                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
81                 $_SESSION['encounter']);
82             **/
83         }
85         //LOG EVERYTHING
86         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
87     } else {
88         EventAuditLogger::instance()->newEvent("login", $_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
89         authLoginScreen();
90     }
93 if (!isset($_SESSION["last_update"])) {
94     authLoginScreen();
95 } else {
96      //if page has not been updated in a given period of time, we call login screen
97      //--Note can't perform nice logout if skip_timeout_reset is set since these are called
98      //via ajax scripts where this output is not getting sent to browser.
99      //--Note DAEMON_FLAG is ok because it is run from a frame in the browser.
100     if (((time() - $_SESSION["last_update"]) > $timeout) && empty($_REQUEST['skip_timeout_reset'])) {
101         EventAuditLogger::instance()->newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
102         authCloseSession();
103         authLoginScreen(true);
104     } else {
105         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
106         //  can be used by scripts that continually request information from the server; for example the Messages
107         //  and Reminders automated intermittent requests that happen in the Messages Center script and in
108         //  the left navigation menu script.
109         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) {
110             $_SESSION["last_update"] = time();
111         }
112     }
117 //----------THINGS WE DO IF WE STILL LIKE YOU
119 function authCheckSession()
121     if (isset($_SESSION['authId'])) {
122          // If active directory was used, check a different session variable (as there is no password in database).
123         if ($GLOBALS['use_active_directory']) {
124             if ($_SESSION['active_directory_auth']) {
125                 return true;
126             } else {
127                 return false;
128             }
129         }
131         $authDB = privQuery("select ".implode(",", array(TBL_USERS.".".COL_ID,
132                                                         TBL_USERS.".".COL_UNM,
133                                                         TBL_USERS_SECURE.".".COL_PWD,
134                                                         TBL_USERS_SECURE.".".COL_ID))
135                 . " FROM ". implode(",", array(TBL_USERS,TBL_USERS_SECURE))
136                 . " WHERE ". TBL_USERS.".".COL_ID." = ? "
137                 . " AND ". TBL_USERS.".".COL_UNM . "=" . TBL_USERS_SECURE.".".COL_UNM
138                 . " AND ". TBL_USERS.".".COL_ACTIVE . "=1", array($_SESSION['authId']));
139         if ($_SESSION['authUser'] == $authDB['username']
140             && $_SESSION['authPass'] == $authDB['password'] ) {
141             return true;
142         } else {
143             return false;
144         }
145     } else {
146         return false;
147     }
150 function authCloseSession()
152   // Before destroying the session, save its site_id so that the next
153   // login will default to that same site.
154     global $incoming_site_id;
155     $incoming_site_id = $_SESSION['site_id'];
156     ob_start();
157     session_unset();
158     session_destroy();
159     unset($_COOKIE[session_name()]);
162 function authLoginScreen($timed_out = false)
164   // See comment in authCloseSession().
165     global $incoming_site_id;
167 <script>
168  // Find the top level window for this instance of OpenEMR, set a flag indicating
169  // session timeout has occurred, and reload the login page into it.  This is so
170  // that beforeunload event handlers will not obstruct the process in this case.
171  var w = window;
172  while (w.opener) { // in case we are in a dialog window
173   var wtmp = w;
174   w = w.opener;
175   wtmp.close();
177 <?php if ($timed_out) { ?>
178  w.top.timed_out = true;
179 <?php } ?>
180  w.top.location.href = '<?php echo "{$GLOBALS['login_screen']}?error=1&site=$incoming_site_id"; ?>';
181 </script>
182 <?php
183   exit;
186 // Check if the user's password has expired beyond the grace limit.
187 // If so, deactivate the user
188 function authCheckExpired($user)
190     $result = sqlStatement("select pwd_expiration_date from users where username = ?", array($user));
191     if ($row = sqlFetchArray($result)) {
192         $pwd_expires = $row['pwd_expiration_date'];
193     }
195     $current_date = date("Y-m-d");
196     if ($pwd_expires != "0000-00-00") {
197         $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
198     }
200     if (($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1)) {
201         sqlStatement("update users set active=0 where username = ?", array($user));
202         $_SESSION['loginfailure'] = 1;
203         return true;
204     }
206     return false;
212 function addGroup($groupname)
214     return sqlInsert("insert into `groups` (name) values (?)", array($groupname));
217 function delGroup($group_id)
219     return sqlQuery("delete from `groups` where id = ? limit 0,1", array($group_id));
222 /***************************************************************
223 //pennfirm
224 //Function currently user by new post calendar code to determine
225 //if a given user is in a group with another user
226 //and if so to allow editing of that users events
228 //*************************************************************/
230 function validateGroupStatus($user_to_be_checked, $group_user)
232     if (isset($user_to_be_checked) && isset($group_user)) {
233         if ($user_to_be_checked == $group_user) {
234             return true;
235         } elseif ($_SESSION['authorizeduser'] == 1) {
236             return true;
237         }
239         $query = "SELECT `groups`.`name` FROM `users`,`groups` WHERE users.username = ? " .
240                  "AND users.username = `groups`.`user` group by `groups`.`name`";
241         $result = sqlStatement($query, array($user_to_be_checked));
243         $usertbcGroups = array();
245         while ($row = sqlFetchArray($result)) {
246             $usertbcGroups[] = $row[0];
247         }
249         $query = "SELECT `groups`.`name` FROM `users`,`groups` WHERE users.username =  ? " .
250                  "AND users.username = `groups`.`user` group by `groups`.`name`";
251         $result = sqlStatement($query, array($group_user));
253         $usergGroups = array();
255         while ($row = sqlFetchArray($result)) {
256             $usergGroups[] = $row[0];
257         }
259         foreach ($usertbcGroups as $group) {
260             if (in_array($group, $usergGroups)) {
261                 return true;
262             }
263         }
264     }
266     return false;
270 // Attempt to update the user's password, password history, and password expiration.
271 // Verify that the new password does not match the last three passwords used.
272 // Return true if successfull, false on failure
273 function UpdatePasswordHistory($userid, $pwd)
275     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?", array($userid));
276     if ($row = sqlFetchArray($result)) {
277         $previous_pwd1=$row['password'];
278         $previous_pwd2=$row['pwd_history1'];
279         $previous_pwd3=$row['pwd_history2'];
280     }
282     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
283         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?", array($previous_pwd2,$previous_pwd1,$pwd,$userid));
284         if ($GLOBALS['password_expiration_days'] != 0) {
285             $exp_days=$GLOBALS['password_expiration_days'];
286             $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
287             sqlStatement("update users set pwd_expiration_date=? where id=?", array($exp_date,$userid));
288         }
290         return true;
291     } else {
292         return false;
293     }