/** * Validate the user session based on user name and password hash. * * @param string $user_name -- The user name to create a session for * @param string $password -- The MD5 sum of the user's password * @return true -- If the session is created * @return false -- If the session is not created */ function validate_user($user_name, $password) { global $server, $current_user, $sugar_config; $user = BeanFactory::getBean('Users'); $user->user_name = $user_name; $authController = AuthenticationController::getInstance(); // Check to see if the user name and password are consistent. if ($user->authenticate_user($password)) { // we also need to set the current_user. $user->retrieve($user->id); $current_user = $user; login_success(); return true; } else { if (function_exists('mcrypt_cbc')) { $password = decrypt_string($password); if ($authController->login($user_name, $password) && isset($_SESSION['authenticated_user_id'])) { $user->retrieve($_SESSION['authenticated_user_id']); $current_user = $user; login_success(); return true; } } else { $GLOBALS['log']->fatal("SECURITY: failed attempted login for {$user_name} using SOAP api"); $server->setError("Invalid username and/or password"); return false; } } }
/** * Grant access tokens for basic user credentials. * * Check the supplied username and password for validity. * * You can also use the $client_id param to do any checks required based * on a client, if you need that. * * Required for OAuth2::GRANT_TYPE_USER_CREDENTIALS. * * @param $client_id * Client identifier to be check with. * @param $username * Username to be check with. * @param $password * Password to be check with. * * @return * TRUE if the username and password are valid, and FALSE if it isn't. * Moreover, if the username and password are valid, and you want to * verify the scope of a user's access, return an associative array * with the scope values as below. We'll check the scope you provide * against the requested scope before providing an access token: * @code * return array( * 'scope' => <stored scope values (space-separated string)>, * ); * @endcode * * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.3 * * @ingroup oauth2_section_4 */ public function checkUserCredentials(IOAuth2GrantUser $storage, $client_id, $username, $password) { $clientInfo = $storage->getClientDetails($client_id); if ($clientInfo === false) { return false; } // Is just a regular Sugar User $auth = AuthenticationController::getInstance(); // noHooks since we'll take care of the hooks on API level, to make it more generalized $loginSuccess = $auth->login($username, $password, array('passwordEncrypted' => false, 'noRedirect' => true, 'noHooks' => true)); if ($loginSuccess && !empty($auth->nextStep)) { // Set it here, and then load it in to the session on the next pass // TODO: How do we pass the next required step to the client via the REST API? $GLOBALS['nextStep'] = $auth->nextStep; } if ($loginSuccess) { $this->userBean = $this->loadUserFromName($username); return array('user_id' => $this->userBean->id); } else { if (!empty($_SESSION['login_error'])) { $message = $_SESSION['login_error']; } else { $message = null; } throw new SugarApiExceptionNeedLogin($message); } }
/** * Log the user into the application * * @param UserAuth array $user_auth -- Set user_name and password (password needs to be * in the right encoding for the type of authentication the user is setup for. For Base * sugar validation, password is the MD5 sum of the plain text password. * @param String $application -- The name of the application you are logging in from. (Currently unused). * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported * @return Array - id - String id is the session_id of the session that was created. * - module_name - String - module name of user * - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name, * - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat * @exception 'SoapFault' -- The SOAP error, if any */ public function login($user_auth, $application, $name_value_list = array()) { $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login'); global $sugar_config; $error = new SoapError(); $user = BeanFactory::getBean('Users'); $success = false; $authController = AuthenticationController::getInstance(); if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN' && $authController->authController->userAuthenticateClass != "LDAPAuthenticateUser") { $user_auth['password'] = md5($user_auth['password']); } $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true)); $usr_id = $user->retrieve_user_id($user_auth['user_name']); if ($usr_id) { $user->retrieve($usr_id); } if ($isLoginSuccess) { if ($_SESSION['hasExpiredPassword'] == '1') { $error->set_error('password_expired'); $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); self::$helperObject->setFaultObject($error); return; } if (!empty($user) && !empty($user->id) && !$user->is_group) { $success = true; global $current_user; $current_user = $user; } } else { if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') { $error->set_error('lockout_reached'); $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); self::$helperObject->setFaultObject($error); return; } else { if ($authController->authController->userAuthenticateClass == "LDAPAuthenticateUser" && (empty($user_auth['encryption']) || $user_auth['encryption'] !== 'PLAIN')) { $error->set_error('ldap_error'); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); self::$helperObject->setFaultObject($error); return; } else { if (function_exists('mcrypt_cbc')) { $password = self::$helperObject->decrypt_string($user_auth['password']); if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) { $success = true; } } } } } if ($success) { session_start(); global $current_user; //$current_user = $user; self::$helperObject->login_success($name_value_list); $current_user->loadPreferences(); $_SESSION['is_valid_session'] = true; $_SESSION['ip_address'] = query_client_ip(); $_SESSION['user_id'] = $current_user->id; $_SESSION['type'] = 'user'; $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user); $_SESSION['authenticated_user_id'] = $current_user->id; $_SESSION['unique_key'] = $sugar_config['unique_key']; $current_user->call_custom_logic('after_login'); $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login'); $nameValueArray = array(); global $current_language; $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id); $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name); $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language); $cur_id = $current_user->getPreference('currency'); $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id); $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user)); $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team); $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef')); $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef')); $num_grp_sep = $current_user->getPreference('num_grp_sep'); $dec_sep = $current_user->getPreference('dec_sep'); $nameValueArray['user_number_seperator'] = self::$helperObject->get_name_value('user_number_seperator', empty($num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $num_grp_sep); $nameValueArray['user_decimal_seperator'] = self::$helperObject->get_name_value('user_decimal_seperator', empty($dec_sep) ? $sugar_config['default_decimal_seperator'] : $dec_sep); $nameValueArray['mobile_max_list_entries'] = self::$helperObject->get_name_value('mobile_max_list_entries', $sugar_config['wl_list_max_entries_per_page']); $nameValueArray['mobile_max_subpanel_entries'] = self::$helperObject->get_name_value('mobile_max_subpanel_entries', $sugar_config['wl_list_max_entries_per_subpanel']); if ($application == 'mobile') { $modules = $availModuleNames = array(); $availModules = array_keys($_SESSION['avail_modules']); //ACL check already performed. $modules = self::$helperObject->get_visible_mobile_modules($availModules); $nameValueArray['available_modules'] = $modules; //Get the vardefs md5 foreach ($modules as $mod_def) { $availModuleNames[] = $mod_def['module_key']; } $nameValueArray['vardefs_md5'] = self::get_module_fields_md5(session_id(), $availModuleNames); } $currencyObject = BeanFactory::getBean('Currencies', $cur_id); $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name); $_SESSION['user_language'] = $current_language; return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray); } LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); $error->set_error('invalid_login'); self::$helperObject->setFaultObject($error); $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login'); }
/** * Load the authenticated user. If there is not an authenticated user then redirect to login screen. */ function loadUser() { global $authController, $sugar_config; // Double check the server's unique key is in the session. Make sure this is not an attempt to hijack a session $user_unique_key = isset($_SESSION['unique_key']) ? $_SESSION['unique_key'] : ''; $server_unique_key = isset($sugar_config['unique_key']) ? $sugar_config['unique_key'] : ''; if (!empty($this->controller->allowed_actions)) { $allowed_actions = $this->controller->allowed_actions; } else { $allowed_actions = array('Authenticate', 'Login', 'LoggedOut'); } if ($user_unique_key != $server_unique_key && !in_array($this->controller->action, $allowed_actions) && !isset($_SESSION['login_error'])) { session_destroy(); if (!empty($this->controller->action)) { if (strtolower($this->controller->action) == 'delete') { $this->controller->action = 'DetailView'; } elseif (strtolower($this->controller->action) == 'save') { $this->controller->action = 'EditView'; } elseif (strtolower($this->controller->action) == 'quickcreate') { $this->controller->action = 'index'; $this->controller->module = 'home'; } elseif (isset($_REQUEST['massupdate']) || isset($_GET['massupdate']) || isset($_POST['massupdate'])) { $this->controller->action = 'index'; } elseif (!in_array($this->controller->action, $this->whiteListActions) && $this->isModifyAction()) { $this->controller->action = 'index'; } } header('Location: ' . $this->getUnauthenticatedHomeUrl(true)); exit; } $authController = AuthenticationController::getInstance(); $GLOBALS['current_user'] = BeanFactory::getBean('Users'); if (isset($_SESSION['authenticated_user_id'])) { // set in modules/Users/Authenticate.php if (!$authController->sessionAuthenticate()) { // if the object we get back is null for some reason, this will break - like user prefs are corrupted $GLOBALS['log']->fatal('User retrieval for ID: (' . $_SESSION['authenticated_user_id'] . ') does not exist in database or retrieval failed catastrophically. Calling session_destroy() and sending user to Login page.'); session_destroy(); SugarApplication::redirect($this->getUnauthenticatedHomeUrl()); die; } else { $trackerManager = TrackerManager::getInstance(); $monitor = $trackerManager->getMonitor('tracker_sessions'); $active = $monitor->getValue('active'); if ($active == 0 && (!isset($GLOBALS['current_user']->portal_only) || $GLOBALS['current_user']->portal_only != 1)) { // We are starting a new session $result = $GLOBALS['db']->query("SELECT id FROM " . $monitor->name . " WHERE user_id = '" . $GLOBALS['db']->quote($GLOBALS['current_user']->id) . "' AND active = 1 AND session_id <> '" . $GLOBALS['db']->quote($monitor->getValue('session_id')) . "' ORDER BY date_end DESC"); $activeCount = 0; while ($row = $GLOBALS['db']->fetchByAssoc($result)) { $activeCount++; if ($activeCount > 1) { $GLOBALS['db']->query("UPDATE " . $monitor->name . " SET active = 0 WHERE id = '" . $GLOBALS['db']->quote($row['id']) . "'"); } } } } } $GLOBALS['log']->debug('Current user is: ' . $GLOBALS['current_user']->user_name); $GLOBALS['logic_hook']->call_custom_logic('', 'after_load_user'); // Reset ACLs in case after_load_user hook changed ACL setups SugarACL::resetACLs(); //set cookies if (isset($_SESSION['authenticated_user_theme'])) { $GLOBALS['log']->debug("setting cookie ck_login_theme_20 to " . $_SESSION['authenticated_user_theme']); self::setCookie('ck_login_theme_20', $_SESSION['authenticated_user_theme'], time() + 86400 * 90); } if (isset($_SESSION['authenticated_user_theme_color'])) { $GLOBALS['log']->debug("setting cookie ck_login_theme_color_20 to " . $_SESSION['authenticated_user_theme_color']); self::setCookie('ck_login_theme_color_20', $_SESSION['authenticated_user_theme_color'], time() + 86400 * 90); } if (isset($_SESSION['authenticated_user_theme_font'])) { $GLOBALS['log']->debug("setting cookie ck_login_theme_font_20 to " . $_SESSION['authenticated_user_theme_font']); self::setCookie('ck_login_theme_font_20', $_SESSION['authenticated_user_theme_font'], time() + 86400 * 90); } if (isset($_SESSION['authenticated_user_language'])) { $GLOBALS['log']->debug("setting cookie ck_login_language_20 to " . $_SESSION['authenticated_user_language']); self::setCookie('ck_login_language_20', $_SESSION['authenticated_user_language'], time() + 86400 * 90); } //check if user can access }
/** * Handles authentication of the current user * * @param string $platform The platform type for this request * @returns bool Was the login successful * @throws SugarApiExceptionRequestTooLarge gets thrown on file uploads if the request failed */ protected function authenticateUser() { $valid = false; $token = $this->grabToken(); if (!empty($token)) { try { $oauthServer = SugarOAuth2Server::getOAuth2Server(); $oauthServer->verifyAccessToken($token); if (isset($_SESSION['authenticated_user_id'])) { $authController = AuthenticationController::getInstance(); // This will return false if anything is wrong with the session // (mismatched IP, mismatched unique_key, etc) $valid = $authController->apiSessionAuthenticate(); if ($valid) { $valid = $this->userAfterAuthenticate($_SESSION['authenticated_user_id'], $oauthServer); } if (!$valid) { // Need to populate the exception here so later code // has it and can send the correct status back to the client $e = new SugarApiExceptionInvalidGrant(); } } } catch (OAuth2AuthenticateException $e) { // This was failing if users were passing an oauth token up to a public url. $valid = false; } catch (SugarApiException $e) { // If we get an exception during this we'll assume authentication failed $valid = false; } } if (!$valid) { // If token is invalid, clear the session for bwc // It looks like a big upload can cause no auth error, // so we do it here instead of the catch block above $_SESSION = array(); $exception = isset($e) ? $e : false; return array('isLoggedIn' => false, 'exception' => $exception); } return array('isLoggedIn' => true, 'exception' => false); }
/** * Log the user into the application * * @param UserAuth array $user_auth -- Set user_name and password (password needs to be * in the right encoding for the type of authentication the user is setup for. For Base * sugar validation, password is the MD5 sum of the plain text password. * @param String $application -- The name of the application you are logging in from. (Currently unused). * @return Array(session_id, error) -- session_id is the id of the session that was * created. Error is set if there was any error during creation. */ function login($user_auth, $application) { global $sugar_config, $system_config; $error = new SoapError(); $user = BeanFactory::getBean('Users'); $success = false; $authController = AuthenticationController::getInstance(); $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true)); $usr_id = $user->retrieve_user_id($user_auth['user_name']); if ($usr_id) { $user->retrieve($usr_id); } if ($isLoginSuccess) { if ($_SESSION['hasExpiredPassword'] == '1') { $error->set_error('password_expired'); $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); return array('id' => -1, 'error' => $error); } // if if (!empty($user) && !empty($user->id) && !$user->is_group) { $success = true; global $current_user; $current_user = $user; } // if } else { if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') { $error->set_error('lockout_reached'); $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); return array('id' => -1, 'error' => $error); } else { if (function_exists('mcrypt_cbc')) { $password = decrypt_string($user_auth['password']); $authController = AuthenticationController::getInstance(); $authController->loggedIn = false; // reset login attempt to try again with decrypted password if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) { $success = true; } // if } } } // else if if ($success) { session_start(); global $current_user; //$current_user = $user; login_success(); $current_user->loadPreferences(); $_SESSION['is_valid_session'] = true; $_SESSION['ip_address'] = query_client_ip(); $_SESSION['user_id'] = $current_user->id; $_SESSION['type'] = 'user'; $_SESSION['avail_modules'] = get_user_module_list($current_user); $_SESSION['authenticated_user_id'] = $current_user->id; $_SESSION['unique_key'] = $sugar_config['unique_key']; $current_user->call_custom_logic('after_login'); return array('id' => session_id(), 'error' => $error); } $error->set_error('invalid_login'); $GLOBALS['log']->fatal('SECURITY: User authentication for ' . $user_auth['user_name'] . ' failed'); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); return array('id' => -1, 'error' => $error); }
/** * Log the user into the application * * @param UserAuth array $user_auth -- Set user_name and password (password needs to be * in the right encoding for the type of authentication the user is setup for. For Base * sugar validation, password is the MD5 sum of the plain text password. * @param String $application -- The name of the application you are logging in from. (Currently unused). * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported * @return Array - id - String id is the session_id of the session that was created. * - module_name - String - module name of user * - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name, * - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat * @exception 'SoapFault' -- The SOAP error, if any */ public function login($user_auth, $application, $name_value_list) { $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login'); global $sugar_config; $error = new SoapError(); $user = BeanFactory::getBean('Users'); $success = false; if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN') { $user_auth['password'] = md5($user_auth['password']); } $authController = AuthenticationController::getInstance(); $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true)); $usr_id = $user->retrieve_user_id($user_auth['user_name']); if ($usr_id) { $user->retrieve($usr_id); } if ($isLoginSuccess) { if ($_SESSION['hasExpiredPassword'] == '1') { $error->set_error('password_expired'); $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); self::$helperObject->setFaultObject($error); return; } if (!empty($user) && !empty($user->id) && !$user->is_group) { $success = true; global $current_user; $current_user = $user; } } else { if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') { $error->set_error('lockout_reached'); $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']); LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); self::$helperObject->setFaultObject($error); return; } else { if (function_exists('mcrypt_cbc')) { $password = self::$helperObject->decrypt_string($user_auth['password']); $authController->loggedIn = false; // reset login attempt to try again with decrypted password if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) { $success = true; } } } } if ($success) { session_start(); global $current_user; //$current_user = $user; self::$helperObject->login_success($name_value_list); $current_user->loadPreferences(); $_SESSION['is_valid_session'] = true; $_SESSION['ip_address'] = query_client_ip(); $_SESSION['user_id'] = $current_user->id; $_SESSION['type'] = 'user'; $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user); $_SESSION['authenticated_user_id'] = $current_user->id; $_SESSION['unique_key'] = $sugar_config['unique_key']; $current_user->call_custom_logic('after_login'); $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login'); $nameValueArray = array(); global $current_language; $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id); $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name); $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language); $cur_id = $current_user->getPreference('currency'); $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id); $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user)); $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team); $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef')); $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef')); $currencyObject = BeanFactory::getBean('Currencies', $cur_id); $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name); $_SESSION['user_language'] = $current_language; return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray); } LogicHook::initialize(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed'); $error->set_error('invalid_login'); self::$helperObject->setFaultObject($error); $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login'); }
public function logout($api, $args) { $oauth2Server = $this->getOAuth2Server($args); if (!empty($api->user)) { $api->user->call_custom_logic('before_logout'); } if (isset($args['refresh_token'])) { // Nuke the refresh token as well. // No security checks needed here to make sure the refresh token is theirs, // because if someone else has your refresh token logging out is the nicest possible thing they could do. $oauth2Server->unsetRefreshToken($args['refresh_token']); } setcookie(RestService::DOWNLOAD_COOKIE . '_' . $api->platform, false, -1, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), true); // The OAuth access token is actually just a session, so we can nuke that here. $_SESSION = array(); session_regenerate_id(true); // Whack the cookie that was set in BWC mode $this->killSessionCookie(); $GLOBALS['logic_hook']->call_custom_logic('Users', 'after_logout'); $auth = AuthenticationController::getInstance(); $res = array('success' => true); if ($auth->isExternal()) { $logout = $auth->getLogoutUrl(); if ($logout) { $res['url'] = $logout; } } return $res; }
/** * Handle the situation where the API needs login * @param Exception $e Exception that caused the login problem, if any * @throws SugarApiExceptionNeedLogin */ public function needLogin(Exception $e = null) { if ($e) { $message = $e->getMessage(); } else { // @TODO Localize exception strings $message = "No valid authentication for user."; } $login_exc = new SugarApiExceptionNeedLogin($message); $auth = AuthenticationController::getInstance(); if ($auth->isExternal()) { $login_exc->setExtraData("url", $auth->getLoginUrl(array('platform' => $this->platform)))->setExtraData('platform', $this->platform); } throw $login_exc; }