2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
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
47 class SugarAuthenticate{
48 var $userAuthenticateClass = 'SugarAuthenticateUser';
49 var $authenticationDir = 'SugarAuthenticate';
51 * Constructs SugarAuthenticate
52 * This will load the user authentication class
54 * @return SugarAuthenticate
56 function SugarAuthenticate()
58 // check in custom dir first, in case someone want's to override an auth controller
59 if (file_exists('custom/modules/Users/authentication/'.$this->authenticationDir.'/' . $this->userAuthenticateClass . '.php')) {
60 require_once('custom/modules/Users/authentication/'.$this->authenticationDir.'/' . $this->userAuthenticateClass . '.php');
62 elseif (file_exists('modules/Users/authentication/'.$this->authenticationDir.'/' . $this->userAuthenticateClass . '.php')) {
63 require_once('modules/Users/authentication/'.$this->authenticationDir.'/' . $this->userAuthenticateClass . '.php');
66 $this->userAuthenticate = new $this->userAuthenticateClass();
69 * Authenticates a user based on the username and password
70 * returns true if the user was authenticated false otherwise
71 * it also will load the user into current user if he was authenticated
73 * @param string $username
74 * @param string $password
77 function loginAuthenticate($username, $password, $fallback=false, $PARAMS = array ()){
79 unset($_SESSION['login_error']);
81 $usr_id=$usr->retrieve_user_id($username);
82 $usr->retrieve($usr_id);
83 $_SESSION['login_error']='';
84 $_SESSION['waiting_error']='';
85 $_SESSION['hasExpiredPassword']='0';
86 if ($this->userAuthenticate->loadUserOnLogin($username, $password, $fallback, $PARAMS)) {
87 require_once('modules/Users/password_utils.php');
88 if(hasPasswordExpired($username)) {
89 $_SESSION['hasExpiredPassword'] = '1';
91 // now that user is authenticated, reset loginfailed
92 if ($usr->getPreference('loginfailed') != '' && $usr->getPreference('loginfailed') != 0) {
93 $usr->setPreference('loginfailed','0');
94 $usr->savePreferencesToDB();
96 return $this->postLoginAuthenticate();
101 if(!empty($usr_id) && $res['lockoutexpiration'] > 0){
102 if (($logout=$usr->getPreference('loginfailed'))=='')
103 $usr->setPreference('loginfailed','1');
105 $usr->setPreference('loginfailed',$logout+1);
106 $usr->savePreferencesToDB();
109 if(strtolower(get_class($this)) != 'sugarauthenticate'){
110 $sa = new SugarAuthenticate();
111 $error = (!empty($_SESSION['login_error']))?$_SESSION['login_error']:'';
112 if($sa->loginAuthenticate($username, $password, true, $PARAMS)){
115 $_SESSION['login_error'] = $error;
119 $_SESSION['login_user_name'] = $username;
120 $_SESSION['login_password'] = $password;
121 if(empty($_SESSION['login_error'])){
122 $_SESSION['login_error'] = translate('ERR_INVALID_PASSWORD', 'Users');
130 * 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
133 function postLoginAuthenticate(){
135 global $reset_theme_on_default_user, $reset_language_on_default_user, $sugar_config;
136 //THIS SECTION IS TO ENSURE VERSIONS ARE UPTODATE
138 require_once ('modules/Versions/CheckVersions.php');
139 $invalid_versions = get_invalid_versions();
140 if (!empty ($invalid_versions)) {
141 if (isset ($invalid_versions['Rebuild Relationships'])) {
142 unset ($invalid_versions['Rebuild Relationships']);
144 // flag for pickup in DisplayWarnings.php
145 $_SESSION['rebuild_relationships'] = true;
148 if (isset ($invalid_versions['Rebuild Extensions'])) {
149 unset ($invalid_versions['Rebuild Extensions']);
151 // flag for pickup in DisplayWarnings.php
152 $_SESSION['rebuild_extensions'] = true;
155 $_SESSION['invalid_versions'] = $invalid_versions;
159 //just do a little house cleaning here
160 unset($_SESSION['login_password']);
161 unset($_SESSION['login_error']);
162 unset($_SESSION['login_user_name']);
163 unset($_SESSION['ACL']);
165 //set the server unique key
166 if (isset ($sugar_config['unique_key']))$_SESSION['unique_key'] = $sugar_config['unique_key'];
169 if (isset ($reset_language_on_default_user) && $reset_language_on_default_user && $GLOBALS['current_user']->user_name == $sugar_config['default_user_name']) {
170 $authenticated_user_language = $sugar_config['default_language'];
172 $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']);
175 $_SESSION['authenticated_user_language'] = $authenticated_user_language;
177 $GLOBALS['log']->debug("authenticated_user_language is $authenticated_user_language");
179 // Clear all uploaded import files for this user if it exists
180 require_once('modules/Import/ImportCacheFiles.php');
181 $tmp_file_name = ImportCacheFiles::getImportDir()."/IMPORT_" . $GLOBALS['current_user']->id;
183 if (file_exists($tmp_file_name)) {
184 unlink($tmp_file_name);
191 * On every page hit this will be called to ensure a user is authenticated
194 function sessionAuthenticate(){
196 global $module, $action, $allowed_actions;
197 $authenticated = false;
198 $allowed_actions = array ("Authenticate", "Login"); // these are actions where the user/server keys aren't compared
199 if (isset ($_SESSION['authenticated_user_id'])) {
201 $GLOBALS['log']->debug("We have an authenticated user id: ".$_SESSION["authenticated_user_id"]);
203 $authenticated = $this->postSessionAuthenticate();
206 if (isset ($action) && isset ($module) && $action == "Authenticate" && $module == "Users") {
207 $GLOBALS['log']->debug("We are authenticating user now");
209 $GLOBALS['log']->debug("The current user does not have a session. Going to the login page");
212 $_REQUEST['action'] = $action;
213 $_REQUEST['module'] = $module;
215 if (empty ($GLOBALS['current_user']->id) && !in_array($action, $allowed_actions)) {
217 $GLOBALS['log']->debug("The current user is not logged in going to login page");
220 $_REQUEST['action'] = $action;
221 $_REQUEST['module'] = $module;
225 if($authenticated && ((empty($_REQUEST['module']) || empty($_REQUEST['action'])) || ($_REQUEST['module'] != 'Users' || $_REQUEST['action'] != 'Logout'))){
228 return $authenticated;
235 * Called after a session is authenticated - if this returns false the sessionAuthenticate will return false and destroy the session
236 * and it will load the current user
240 function postSessionAuthenticate(){
242 global $action, $allowed_actions, $sugar_config;
243 $_SESSION['userTime']['last'] = time();
244 $user_unique_key = (isset ($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : '';
245 $server_unique_key = (isset ($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : '';
247 //CHECK IF USER IS CROSSING SITES
248 if (($user_unique_key != $server_unique_key) && (!in_array($action, $allowed_actions)) && (!isset ($_SESSION['login_error']))) {
250 $GLOBALS['log']->debug('Destroying Session User has crossed Sites');
252 header("Location: index.php?action=Login&module=Users".$GLOBALS['app']->getLoginRedirect());
255 if (!$this->userAuthenticate->loadUserOnSession($_SESSION['authenticated_user_id'])) {
257 header("Location: index.php?action=Login&module=Users&loginErrorMessage=LBL_SESSION_EXPIRED");
258 $GLOBALS['log']->debug('Current user session does not exist redirecting to login');
261 $GLOBALS['log']->debug('Current user is: '.$GLOBALS['current_user']->user_name);
266 * Make sure a user isn't stealing sessions so check the ip to ensure that the ip address hasn't dramatically changed
269 function validateIP() {
270 global $sugar_config;
271 // grab client ip address
272 $clientIP = query_client_ip();
274 // check to see if config entry is present, if not, verify client ip
275 if (!isset ($sugar_config['verify_client_ip']) || $sugar_config['verify_client_ip'] == true) {
276 // check to see if we've got a current ip address in $_SESSION
277 // and check to see if the session has been hijacked by a foreign ip
278 if (isset ($_SESSION["ipaddress"])) {
279 $session_parts = explode(".", $_SESSION["ipaddress"]);
280 $client_parts = explode(".", $clientIP);
281 if(count($session_parts) < 4) {
285 // match class C IP addresses
286 for ($i = 0; $i < 3; $i ++) {
287 if ($session_parts[$i] == $client_parts[$i]) {
296 // we have a different IP address
297 if ($_SESSION["ipaddress"] != $clientIP && empty ($classCheck)) {
298 $GLOBALS['log']->fatal("IP Address mismatch: SESSION IP: {$_SESSION['ipaddress']} CLIENT IP: {$clientIP}");
300 die("Your session was terminated due to a significant change in your IP address. <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
303 $_SESSION["ipaddress"] = $clientIP;
313 * Called when a user requests to logout
319 header('Location: index.php?module=Users&action=Login');
325 * Encodes a users password. This is a static function and can be called at any time.
327 * @param STRING $password
328 * @return STRING $encoded_password
330 function encodePassword($password){
331 return strtolower(md5($password));
335 * If a user may change there password through the Sugar UI
338 function canChangePassword(){
342 * If a user may change there user name through the Sugar UI
345 function canChangeUserName(){
353 * This function allows the SugarAuthenticate subclasses to perform some pre login initialization as needed
357 if (isset($_SESSION['authenticated_user_id']))
360 // fixing bug #46837: Previosly links/URLs to records in Sugar from MSO Excel/Word were referred to the home screen and not the record
361 // It used to appear when default browser was not MS IE
362 header("Location: ".$GLOBALS['app']->getLoginRedirect());
368 * Redirect to login page
370 * @param SugarApplication $app
372 public function redirectToLogin(SugarApplication $app)
374 $loginVars = $app->createLoginVars();
375 $app->redirect('index.php?action=Login&module=Users' . $loginVars);