]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Users/authentication/SugarAuthenticate/SugarAuthenticate.php
Release 6.1.5
[Github/sugarcrm.git] / modules / Users / authentication / SugarAuthenticate / SugarAuthenticate.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39
40
41 /**
42  * This file is used to control the authentication process.
43  * It will call on the user authenticate and controll redirection
44  * based on the users validation
45  *
46  */
47 class SugarAuthenticate{
48         var $userAuthenticateClass = 'SugarAuthenticateUser';
49         var $authenticationDir = 'SugarAuthenticate';
50         /**
51          * Constructs SugarAuthenticate
52          * This will load the user authentication class
53          *
54          * @return SugarAuthenticate
55          */
56         function SugarAuthenticate(){
57                 require_once('modules/Users/authentication/'. $this->authenticationDir . '/'. $this->userAuthenticateClass . '.php');
58                 $this->userAuthenticate = new $this->userAuthenticateClass();
59
60         }
61         /**
62          * Authenticates a user based on the username and password
63          * returns true if the user was authenticated false otherwise
64          * it also will load the user into current user if he was authenticated
65          *
66          * @param string $username
67          * @param string $password
68          * @return boolean
69          */
70         function loginAuthenticate($username, $password, $fallback=false, $PARAMS = array ()){
71                 global $mod_strings;
72                 unset($_SESSION['login_error']);
73                 $usr= new user();
74                 $usr_id=$usr->retrieve_user_id($username);
75                 $usr->retrieve($usr_id);
76                 $_SESSION['login_error']='';
77                 $_SESSION['waiting_error']='';
78                 $_SESSION['hasExpiredPassword']='0';
79                 if ($this->userAuthenticate->loadUserOnLogin($username, $password, $fallback, $PARAMS)) {
80                         require_once('modules/Users/password_utils.php');
81                         if(hasPasswordExpired($username)) {
82                                 $_SESSION['hasExpiredPassword'] = '1';
83                         }
84                         // now that user is authenticated, reset loginfailed
85                         if ($usr->getPreference('loginfailed') != '' && $usr->getPreference('loginfailed') != 0) {
86                                 $usr->setPreference('loginfailed','0');
87                                 $usr->savePreferencesToDB();
88                         }
89                         return $this->postLoginAuthenticate();
90
91                 }
92                 else
93                 {
94                         if(!empty($usr_id) && $res['lockoutexpiration'] > 0){
95                                 if (($logout=$usr->getPreference('loginfailed'))=='')
96                                 $usr->setPreference('loginfailed','1');
97                         else
98                                 $usr->setPreference('loginfailed',$logout+1);
99                         $usr->savePreferencesToDB();
100                 }
101                 }
102                 if(strtolower(get_class($this)) != 'sugarauthenticate'){
103                         $sa = new SugarAuthenticate();
104                         $error = (!empty($_SESSION['login_error']))?$_SESSION['login_error']:'';
105                         if($sa->loginAuthenticate($username, $password, true, $PARAMS)){
106                                 return true;
107                         }
108                         $_SESSION['login_error'] = $error;
109                 }
110
111
112                 $_SESSION['login_user_name'] = $username;
113                 $_SESSION['login_password'] = $password;
114                 if(empty($_SESSION['login_error'])){
115                         $_SESSION['login_error'] = translate('ERR_INVALID_PASSWORD', 'Users');
116                 }
117
118                 return false;
119
120         }
121
122         /**
123          * Once a user is authenticated on login this function will be called. Populate the session with what is needed and log anything that needs to be logged
124          *
125          */
126         function postLoginAuthenticate(){
127
128                 global $reset_theme_on_default_user, $reset_language_on_default_user, $sugar_config;
129                 //THIS SECTION IS TO ENSURE VERSIONS ARE UPTODATE
130
131                 require_once ('modules/Versions/CheckVersions.php');
132                 $invalid_versions = get_invalid_versions();
133                 if (!empty ($invalid_versions)) {
134                         if (isset ($invalid_versions['Rebuild Relationships'])) {
135                                 unset ($invalid_versions['Rebuild Relationships']);
136
137                                 // flag for pickup in DisplayWarnings.php
138                                 $_SESSION['rebuild_relationships'] = true;
139                         }
140
141                         if (isset ($invalid_versions['Rebuild Extensions'])) {
142                                 unset ($invalid_versions['Rebuild Extensions']);
143
144                                 // flag for pickup in DisplayWarnings.php
145                                 $_SESSION['rebuild_extensions'] = true;
146                         }
147
148                         $_SESSION['invalid_versions'] = $invalid_versions;
149                 }
150
151
152                 //just do a little house cleaning here
153                 unset($_SESSION['login_password']);
154                 unset($_SESSION['login_error']);
155                 unset($_SESSION['login_user_name']);
156                 unset($_SESSION['ACL']);
157
158                 //set the server unique key
159                 if (isset ($sugar_config['unique_key']))$_SESSION['unique_key'] = $sugar_config['unique_key'];
160
161                 //set user language
162                 if (isset ($reset_language_on_default_user) && $reset_language_on_default_user && $$GLOBALS['current_user']->user_name == $sugar_config['default_user_name']) {
163                         $authenticated_user_language = $sugar_config['default_language'];
164                 } else {
165                         $authenticated_user_language = isset($_REQUEST['login_language']) ? $_REQUEST['login_language'] : (isset ($_REQUEST['ck_login_language_20']) ? $_REQUEST['ck_login_language_20'] : $sugar_config['default_language']);
166                 }
167
168                 $_SESSION['authenticated_user_language'] = $authenticated_user_language;
169
170                 $GLOBALS['log']->debug("authenticated_user_language is $authenticated_user_language");
171
172                 // Clear all uploaded import files for this user if it exists
173
174                 $tmp_file_name = $sugar_config['import_dir']."IMPORT_".$GLOBALS['current_user']->id;
175
176                 if (file_exists($tmp_file_name)) {
177                         unlink($tmp_file_name);
178                 }
179
180
181
182                 return true;
183         }
184
185         /**
186          * On every page hit this will be called to ensure a user is authenticated
187          * @return boolean
188          */
189         function sessionAuthenticate(){
190
191                 global $module, $action, $allowed_actions;
192                 $authenticated = false;
193                 $allowed_actions = array ("Authenticate", "Login"); // these are actions where the user/server keys aren't compared
194                 if (isset ($_SESSION['authenticated_user_id'])) {
195
196                         $GLOBALS['log']->debug("We have an authenticated user id: ".$_SESSION["authenticated_user_id"]);
197
198                         $authenticated = $this->postSessionAuthenticate();
199
200                 } else
201                 if (isset ($action) && isset ($module) && $action == "Authenticate" && $module == "Users") {
202                         $GLOBALS['log']->debug("We are authenticating user now");
203                 } else {
204                         $GLOBALS['log']->debug("The current user does not have a session.  Going to the login page");
205                         $action = "Login";
206                         $module = "Users";
207                         $_REQUEST['action'] = $action;
208                         $_REQUEST['module'] = $module;
209                 }
210                 if (empty ($GLOBALS['current_user']->id) && !in_array($action, $allowed_actions)) {
211
212                         $GLOBALS['log']->debug("The current user is not logged in going to login page");
213                         $action = "Login";
214                         $module = "Users";
215                         $_REQUEST['action'] = $action;
216                         $_REQUEST['module'] = $module;
217
218                 }
219
220                 if($authenticated && ((empty($_REQUEST['module']) || empty($_REQUEST['action'])) || ($_REQUEST['module'] != 'Users' || $_REQUEST['action'] != 'Logout'))){
221                         $this->validateIP();
222                 }
223                 return $authenticated;
224         }
225
226
227
228
229         /**
230          * Called after a session is authenticated - if this returns false the sessionAuthenticate will return false and destroy the session
231          * and it will load the  current user
232          * @return boolean
233          */
234
235         function postSessionAuthenticate(){
236
237                 global $action, $allowed_actions, $sugar_config;
238                 $_SESSION['userTime']['last'] = time();
239                 $user_unique_key = (isset ($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : '';
240                 $server_unique_key = (isset ($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : '';
241
242                 //CHECK IF USER IS CROSSING SITES
243                 if (($user_unique_key != $server_unique_key) && (!in_array($action, $allowed_actions)) && (!isset ($_SESSION['login_error']))) {
244
245                         session_destroy();
246                         $post_login_nav = '';
247                         if (!empty ($record) && !empty ($action) && !empty ($module)) {
248                                 $post_login_nav = "&login_module=".$module."&login_action=".$action."&login_record=".$record;
249                         }
250                         $GLOBALS['log']->debug('Destroying Session User has crossed Sites');
251                         header("Location: index.php?action=Login&module=Users".$post_login_nav);
252                         sugar_cleanup(true);
253                 }
254                 if (!$this->userAuthenticate->loadUserOnSession($_SESSION['authenticated_user_id'])) {
255                         session_destroy();
256                         header("Location: index.php?action=Login&module=Users&loginErrorMessage=LBL_SESSION_EXPIRED");
257                         $GLOBALS['log']->debug('Current user session does not exist redirecting to login');
258                         sugar_cleanup(true);
259                 }
260                 $GLOBALS['log']->debug('Current user is: '.$GLOBALS['current_user']->user_name);
261                 return true;
262         }
263
264         /**
265          * Make sure a user isn't stealing sessions so check the ip to ensure that the ip address hasn't dramatically changed
266          *
267          */
268         function validateIP() {
269                 global $sugar_config;
270                 // grab client ip address
271                 $clientIP = query_client_ip();
272                 $classCheck = 0;
273                 // check to see if config entry is present, if not, verify client ip
274                 if (!isset ($sugar_config['verify_client_ip']) || $sugar_config['verify_client_ip'] == true) {
275                         // check to see if we've got a current ip address in $_SESSION
276                         // and check to see if the session has been hijacked by a foreign ip
277                         if (isset ($_SESSION["ipaddress"])) {
278                                 $session_parts = explode(".", $_SESSION["ipaddress"]);
279                                 $client_parts = explode(".", $clientIP);
280                 if(count($session_parts) < 4) {
281                     $classCheck = 0;
282                 }
283                 else {
284                                 // match class C IP addresses
285                                 for ($i = 0; $i < 3; $i ++) {
286                                         if ($session_parts[$i] == $client_parts[$i]) {
287                                                 $classCheck = 1;
288                                                 continue;
289                                         } else {
290                                                 $classCheck = 0;
291                                                 break;
292                                         }
293                                 }
294                 }
295                                 // we have a different IP address
296                                 if ($_SESSION["ipaddress"] != $clientIP && empty ($classCheck)) {
297                                         $GLOBALS['log']->fatal("IP Address mismatch: SESSION IP: {$_SESSION['ipaddress']} CLIENT IP: {$clientIP}");
298                                         session_destroy();
299                                         die("Your session was terminated due to a significant change in your IP address.  <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
300                                 }
301                         } else {
302                                 $_SESSION["ipaddress"] = $clientIP;
303                         }
304                 }
305
306         }
307
308
309
310
311         /**
312          * Called when a user requests to logout
313          *
314          */
315         function logout(){
316                         session_destroy();
317                         ob_clean();
318                         header('Location: index.php?module=Users&action=Login');
319                         sugar_cleanup(true);
320         }
321
322
323         /**
324          * Encodes a users password. This is a static function and can be called at any time.
325          *
326          * @param STRING $password
327          * @return STRING $encoded_password
328          */
329         function encodePassword($password){
330                 return strtolower(md5($password));
331         }
332
333         /**
334          * If a user may change there password through the Sugar UI
335          *
336          */
337         function canChangePassword(){
338                 return true;
339         }
340         /**
341          * If a user may change there user name through the Sugar UI
342          *
343          */
344         function canChangeUserName(){
345                 return true;
346         }
347
348
349
350
351 }