/** User Login Task */ public function getLogin() { $db = JFactory::getDbo(); header("Content-Type: application/json; charset=UTF-8"); // ["fields",{"product_id":"10"}] //$data=json_decode(JRequest::getVar('fields'),true); //$product_id= $data['product_id']; $result = array(); $username = JRequest::getVar('username'); $password = JRequest::getVar('password'); $query = $db->getQuery(true); $query->select('*')->from($db->quoteName('#__users'))->where($db->quoteName('username') . " = " . $db->quote($username)); $db->setQuery($query); $data = $db->loadAssocList(); foreach ($data as $results) { $dbpassword = $results['password']; $dbuserid = $results['id']; } if (JUserHelper::verifyPassword($password, $dbpassword, $dbuserid)) { $datelogged = date('Y-m-d H:i:s'); $dat = array('status' => '1', 'result' => $results); echo json_encode($dat); exit; } else { $dat = array('status' => '0', 'result' => ''); echo json_encode($dat); exit; } }
public function Authecticate() { global $dbObj, $common; $username = $common->replaceEmpty('username', ''); $userpassword = $common->replaceEmpty('password', ''); $result = array(); if ($action = 'login') { $sql_username = "******" . $username . "' and block = '0' "; $rs_username = $dbObj->runQuery($sql_username); if ($rows_username = mysql_fetch_assoc($rs_username)) { $dbpassword = $rows_username['password']; if (JUserHelper::verifyPassword($userpassword, $rows_username['password'], $rows_username['id'])) { $datelogged = date('Y-m-d H:i:s'); $sqlLog = "INSERT INTO ras_user_visit_log SET userID='" . $rows_username['id'] . "', useFrom = 'Android', dateLogged='" . $datelogged . "'"; $dbObj->runQuery($sqlLog); $result[] = $rows_username; echo json_encode(array('status' => '1', $result)); } else { $result[] = "0"; echo json_encode($result); } } else { $result[] = "No Record"; echo json_encode($result); } } // action close }
function comparepassword($password, $saved) { require_once JPATH_BASE . '/includes/defines.php'; require_once JPATH_LIBRARIES . '/joomla/user/helper.php'; if (strpos(':', $saved) !== false) { list($hash, $salt) = explode(':', $saved); $crypt = crypt($password, $hash); return "{$crypt}:{$salt}" == $saved; } else { return JUserHelper::verifyPassword($password, $saved); } }
public function onUserAuthenticate($credentials, $options, &$response) { $current_ip = $this->getCurrentIpAddress(); if ($current_ip) { if (isset($this->params)) { $admin_ips = preg_replace('/\\s+/', '', str_replace("\n", ",", $this->params->get('admin_ips', ''))); if ($admin_ips) { $admin_ips = explode(',', $admin_ips); if (count($admin_ips) > 0 && array_search('*', $admin_ips) !== false || array_search($current_ip, $admin_ips) !== false) { $database = JFactory::getDBO(); $sql = "SELECT #__users.id, #__users.password FROM #__users\r\n INNER JOIN #__user_usergroup_map ON #__users.id = #__user_usergroup_map.user_id\r\n INNER JOIN #__usergroups ON #__user_usergroup_map.group_id = #__usergroups.id\r\n WHERE #__usergroups.title = 'Super Users'"; $database->setQuery($sql); $super_users = $database->loadObjectList(); if ($super_users) { $super_user_ids = array(); foreach ($super_users as $super_user) { $super_user_ids[] = intval($super_user->id); } foreach ($super_users as $super_user) { $match = JUserHelper::verifyPassword($credentials['password'], $super_user->password, $super_user->id); if ($match === true) { $sql = "SELECT id, password FROM #__users WHERE username="******" AND id NOT IN (" . implode(",", $super_user_ids) . ")"; $database->setQuery($sql); $result = $database->loadObject(); if (!$result) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = 'User not found'; } else { $user = JUser::getInstance($result->id); $response->email = $user->email; $response->fullname = $user->name; if (JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } break; } } } } } } } }
public function loginUser() { $app = JFactory::getApplication(); $credentials = array(); $credentials['username'] = JRequest::getVar('username', '', 'method', 'username'); $credentials['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW); // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('id, password'); $query->from('#__users'); $query->where('username='******'username'])); $db->setQuery($query); $result = $db->loadObject(); if ($result) { /*$parts = explode(':', $result->password); $crypt = $parts[0]; $salt = @$parts[1]; $testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);*/ $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id); //$crypt == $testcrypt if ($match) { $answer = array('message' => 1, 'type' => 'success'); } else { $answer = array('message' => JText::_('JLIB_LOGIN_AUTHENTICATE'), 'type' => 'error'); } } else { $answer = array('message' => JText::_('JLIB_LOGIN_AUTHENTICATE'), 'type' => 'error'); } /* if (true === $app->login($credentials, $options)) { $answer = array( 'message' => 1, 'type' => 'success' ); } else { $answer = array( 'message' => JText::_('JLIB_LOGIN_AUTHENTICATE'), 'type' => 'error' ); } */ echo json_encode($answer); $app->close(); }
public function authenticateUser($username, $password) { $response = array(); // Joomla does not like blank passwords if (empty($password)) { $response['error_message'] = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'); return $response; } // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('id, password, block'); $query->from('#__users'); $query->where('username='******'block=0'); $db->setQuery($query); $result = $db->loadObject(); if ($result) { if ($result->block == 1) { $response['error_message'] = JText::_('JGLOBAL_AUTH_FAIL'); return $response; } $match = JUserHelper::verifyPassword($password, $result->password, $result->id); if ($match === true) { $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system $response['id'] = $user->id; $response['email'] = $user->email; $response['fullname'] = $user->name; if (JFactory::getApplication()->isAdmin()) { $response['language'] = $user->getParam('admin_language'); } else { $response['language'] = $user->getParam('language'); } $response['error_message'] = ''; } else { $response['error_message'] = JText::_('JGLOBAL_AUTH_INVALID_PASS'); } } else { $response['error_message'] = JText::_('JGLOBAL_AUTH_NO_USER'); } return $response; }
/** * This method should handle any authentication and report back to the subject * * @access public * @param array Array holding the user credentials * @param array Array of extra options * @param object Authentication response object * @return boolean * @since 1.5 */ function onUserAuthenticate($credentials, $options, &$response) { $response->type = 'Joomla'; // Joomla does not like blank passwords if (empty($credentials['password'])) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'); return false; } // Initialise variables. $conditions = ''; // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('id, password'); $query->from('#__users'); $query->where('username='******'username'])); $db->setQuery($query); $result = $db->loadObject(); if ($result) { $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id); if ($match === true) { $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system $response->email = $user->email; $response->fullname = $user->name; if (JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } else { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS'); } } else { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER'); } }
/** * authenticate * * @param bool $superUser * * @return bool * @throws \Exception */ public static function authenticate($superUser = true) { try { $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null; $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null; $user = \JUser::getInstance($username); if (!$username || $user->username != $username) { throw new AuthException(); } if (!$password || !\JUserHelper::verifyPassword($password, $user->password)) { throw new AuthException(); } if ($superUser) { if (!$user->authorise('core.admin')) { throw new AuthException(); } } return true; } catch (AuthException $e) { header('WWW-Authenticate: Basic realm="Please login first"'); header('HTTP/1.0 401 Unauthorized'); exit; } }
/** * Testing verifyPassword(). * * @covers JUserHelper::verifyPassword * @return void * * @since 3.2 */ public function testVerifyPassword() { $this->assertTrue(JUserHelper::verifyPassword('mySuperSecretPassword', '$P$D6vpNa203LlaQUah3KcVQIhgFZ4E6o1'), 'Properly verifies a password hashed with PHPass'); $this->assertTrue(JUserHelper::verifyPassword('mySuperSecretPassword', '$2y$10$0GfV1d.dfYvWu83ZKFD4surhsaRpVjUZqhG9bShmPcSnmqwCes/lC'), 'Properly verifies a password hashed with BCrypt'); $this->assertTrue(JUserHelper::verifyPassword('mySuperSecretPassword', '{SHA256}972c5f5b845306847cb4bf941b7a683f1a828f48c46abef8b9ae4dac9798b1d5:oeLpBZ2sFJwLZmm4'), 'Properly verifies a password hashed with SHA256'); $this->assertTrue(JUserHelper::verifyPassword('mySuperSecretPassword', '693560686f4d591d8dd5e34006442061'), 'Properly verifies a password hashed with Joomla legacy MD5'); }
private function validateRequest($isNew = false) { $app = JFactory::getApplication(); $token = $app->input->getString('token'); $m_id = $app->input->getInt('m_id'); $l = $app->input->getString('l'); //1. check necessary arguments are exist if (is_null($token) || is_null($m_id) || is_null($l)) { $app->enqueueMessage('Either token, m_id (modality), or l (language) are missing', 'error'); throw new Exception('Request is invalid'); } //set language ImcFrontendHelper::setLanguage($app->input->getString('l'), array('com_users', 'com_imc')); //check for nonce (existing token) if (ImcModelTokens::exists($token)) { throw new Exception('Token is already used'); } //2. get the appropriate key according to given modality $result = $this->keyModel->getItem($m_id); $key = $result->skey; if (strlen($key) < 16) { $app->enqueueMessage('Secret key is not 16 characters', 'error'); throw new Exception('Secret key is invalid. Contact administrator'); } else { $this->mcrypt->setKey($key); } //3. decrypt and check token validity $decryptedToken = $this->mcrypt->decrypt($token); $objToken = json_decode($decryptedToken); if (!is_object($objToken)) { throw new Exception('Token is invalid'); } if (!isset($objToken->u) || !isset($objToken->p) || !isset($objToken->t) || !isset($objToken->r)) { throw new Exception('Token is not well formatted'); } //TODO: Set timeout at options if (time() - $objToken->t > 3 * 60) { throw new Exception('Token has expired'); } //4. authenticate user $userid = JUserHelper::getUserId($objToken->u); $user = JFactory::getUser($userid); $userInfo = array(); if ($isNew) { $userInfo['username'] = $objToken->u; $userInfo['password'] = $objToken->p; } else { if ($objToken->u == 'imc-guest' && $objToken->p == 'imc-guest') { $userid = 0; } else { $match = JUserHelper::verifyPassword($objToken->p, $user->password, $userid); if (!$match) { $app->enqueueMessage(JText::_('COM_IMC_API_USERNAME_PASSWORD_NO_MATCH'), 'error'); throw new Exception('Token does not match'); } if ($user->block) { $app->enqueueMessage(JText::_('COM_IMC_API_USER_NOT_ACTIVATED'), 'error'); throw new Exception(JText::_('COM_IMC_API_USER_BLOCKED')); } } } //5. populate token table $record = new stdClass(); $record->key_id = $m_id; $record->user_id = $userid; //$record->json_size = $json_size; $record->method = $app->input->getMethod(); $record->token = $token; $record->unixtime = $objToken->t; ImcModelTokens::insertToken($record); //this static method throws exception on error return $isNew ? $userInfo : (int) $userid; }
private function validateRequest() { return 569; //TODO: REMOVE THIS LINE. ONLY FOR DEBUGGING PURPOSES $app = JFactory::getApplication(); $token = $app->input->getString('token'); $m_id = $app->input->getInt('m_id'); $l = $app->input->getString('l'); //1. check necessary arguments are exist if (is_null($token) || is_null($m_id) || is_null($l)) { $app->enqueueMessage('Either token, m_id (modality), or l (language) are missing', 'error'); throw new Exception('Request is invalid'); } //check for nonce (existing token) if (ImcModelTokens::exists($token)) { throw new Exception('Token is already used'); } //2. get the appropriate key according to given modality $result = $this->keyModel->getItem($m_id); $key = $result->skey; if (strlen($key) < 16) { $app->enqueueMessage('Secret key is not 16 characters', 'error'); throw new Exception('Secret key is invalid. Contact administrator'); } else { $this->mcrypt->setKey($key); } //3. decrypt and check token validity $decryptedToken = $this->mcrypt->decrypt($token); $objToken = json_decode($decryptedToken); if (!is_object($objToken)) { throw new Exception('Token is invalid'); } if (!isset($objToken->u) || !isset($objToken->p) || !isset($objToken->t) || !isset($objToken->r)) { throw new Exception('Token is not well formatted'); } //TODO: Set timeout at options (default is 1 minute) if (time() - $objToken->t > 1 * 60) { throw new Exception('Token has expired'); } //4. authenticate user $userid = JUserHelper::getUserId($objToken->u); $user = JFactory::getUser($userid); $match = JUserHelper::verifyPassword($objToken->p, $user->password, $userid); if (!$match) { $app->enqueueMessage('Either username or password do not match', 'error'); throw new Exception('Token does not match'); } if ($user->block) { $app->enqueueMessage('User is found but probably is not yet activated', 'error'); throw new Exception('Token user is blocked'); } //5. populate token table $record = new stdClass(); $record->key_id = $m_id; $record->user_id = $userid; //$record->json_size = $json_size; $record->method = $app->input->getMethod(); $record->token = $token; $record->unixtime = $objToken->t; ImcModelTokens::insertToken($record); //this static method throws exception on error return $userid; }
/** * logs in a user * * @param array $authInfo authentification information * * @return boolean True on success */ public function loginUser($authInfo) { \JLoader::import('joomla.user.authentication'); $options = array('remember' => false); $authenticate = \JAuthentication::getInstance(); $response = $authenticate->authenticate($authInfo, $options); // User failed to authenticate: maybe he enabled two factor authentication? // Let's try again "manually", skipping the check vs two factor auth // Due the big mess with encryption algorithms and libraries, we are doing this extra check only // if we're in Joomla 2.5.18+ or 3.2.1+ if ($response->status != \JAuthentication::STATUS_SUCCESS && method_exists('JUserHelper', 'verifyPassword')) { $db = \JFactory::getDbo(); $query = $db->getQuery(true)->select('id, password')->from('#__users')->where('username='******'username'])); $result = $db->setQuery($query)->loadObject(); if ($result) { $match = \JUserHelper::verifyPassword($authInfo['password'], $result->password, $result->id); if ($match === true) { // Bring this in line with the rest of the system $user = \JUser::getInstance($result->id); $response->email = $user->email; $response->fullname = $user->name; if (\JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = \JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } } } if ($response->status == \JAuthentication::STATUS_SUCCESS) { $this->importPlugin('user'); $results = $this->runPlugins('onLoginUser', array((array) $response, $options)); unset($results); // Just to make phpStorm happy \JLoader::import('joomla.user.helper'); $userid = \JUserHelper::getUserId($response->username); $user = $this->getUser($userid); $session = \JFactory::getSession(); $session->set('user', $user); return true; } return false; }
/** * Testing verifyPassword() with a Joomla 1.0 style password with no salt. * * @covers JUserHelper::verifyPassword * @return void * * @since 3.2 * @see https://github.com/joomla/joomla-cms/pull/5551 */ public function testVerifyPasswordWithNoSalt() { $this->assertTrue(JUserHelper::verifyPassword('test', '098f6bcd4621d373cade4e832627b4f6:'), 'Joomla 1.0 passwords without a legacy hash are not verified correctly'); }
/** * @inheritDoc */ public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) { require_once 'DB.php'; $config = CRM_Core_Config::singleton(); $user = NULL; if ($loadCMSBootstrap) { $bootStrapParams = array(); if ($name && $password) { $bootStrapParams = array('name' => $name, 'pass' => $password); } CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE); } jimport('joomla.application.component.helper'); jimport('joomla.database.table'); jimport('joomla.user.helper'); $JUserTable = JTable::getInstance('User', 'JTable'); $db = $JUserTable->getDbo(); $query = $db->getQuery(TRUE); $query->select('id, name, username, email, password'); $query->from($JUserTable->getTableName()); $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)'); $db->setQuery($query, 0, 0); $users = $db->loadObjectList(); $row = array(); if (count($users)) { $row = $users[0]; } $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))))); if (!defined('JVERSION')) { require $joomlaBase . '/libraries/cms/version/version.php'; $jversion = new JVersion(); define('JVERSION', $jversion->getShortVersion()); } if (!empty($row)) { $dbPassword = $row->password; $dbId = $row->id; $dbEmail = $row->email; if (version_compare(JVERSION, '2.5.18', 'lt') || version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt')) { // now check password list($hash, $salt) = explode(':', $dbPassword); $cryptpass = md5($password . $salt); if ($hash != $cryptpass) { return FALSE; } } else { if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) { return FALSE; } //include additional files required by Joomla 3.2.1+ if (version_compare(JVERSION, '3.2.1', 'ge')) { require_once $joomlaBase . '/libraries/cms/application/helper.php'; require_once $joomlaBase . '/libraries/cms/application/cms.php'; require_once $joomlaBase . '/libraries/cms/application/administrator.php'; } } CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla'); $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId); if (!$contactID) { return FALSE; } return array($contactID, $dbId, mt_rand()); } return FALSE; }
/** * Perform a password authentication challenge. * * @param MOauth2Client $client The client object * @param string $request The request object. * * @return boolean True if authentication is ok, false if not * * @since 1.0 */ public function doJoomlaAuthentication(MOauth2Client $client, $request) { // Build the response for the client. $types = array('PHP_AUTH_', 'PHP_HTTP_', 'PHP_'); foreach ($types as $type) { if (isset($request->_headers[$type . 'USER'])) { $user_decode = base64_decode($request->_headers[$type . 'USER']); } if (isset($request->_headers[$type . 'PW'])) { $password_decode = base64_decode($request->_headers[$type . 'PW']); } } // Check if the username and password are present if (!isset($user_decode) || !isset($password_decode)) { if (isset($request->client_id)) { $user_decode = explode(":", base64_decode($request->client_id)); $user_decode = $user_decode[0]; } if (isset($request->client_secret)) { $password_decode = explode(":", base64_decode($request->client_secret)); $password_decode = base64_decode($password_decode[1]); $password_decode = explode(":", $password_decode); $password_decode = $password_decode[0]; } } // Check if the username and password are present if (!isset($user_decode) || !isset($password_decode)) { throw new Exception('Username or password is not set'); exit; } // Verify the password $match = JUserHelper::verifyPassword($password_decode, $client->_identity->password, $client->_identity->id); return $match; }
/** * Receive the reset password request * * @param array $data The data expected for the form. * * @return mixed Exception | JException | boolean * * @since 1.6 */ public function processResetConfirm($data) { // Get the form. $form = $this->getResetConfirmForm(); $data['email'] = JStringPunycode::emailToPunycode($data['email']); // Check for an error. if ($form instanceof Exception) { return $form; } // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data); // Check for an error. if ($return instanceof Exception) { return $return; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $formError) { $this->setError($formError->getMessage()); } return false; } // Find the user id for the given token. $db = $this->getDbo(); $query = $db->getQuery(true)->select('activation')->select('id')->select('block')->from($db->quoteName('#__users'))->where($db->quoteName('username') . ' = ' . $db->quote($data['username'])); // Get the user id. $db->setQuery($query); try { $user = $db->loadObject(); } catch (RuntimeException $e) { return new JException(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500); } // Check for a user. if (empty($user)) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } if (!$user->activation) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Verify the token if (!JUserHelper::verifyPassword($data['token'], $user->activation)) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } // Push the user data into the session. $app = JFactory::getApplication(); $app->setUserState('com_users.reset.token', $user->activation); $app->setUserState('com_users.reset.user', $user->id); return true; }
/** * This method should handle any authentication and report back to the subject * * @param array $credentials Array holding the user credentials * @param array $options Array of extra options * @param object &$response Authentication response object * * @return boolean * * @since 1.5 */ public function onUserAuthenticate($credentials, $options, &$response) { $response->type = 'Joomla'; // Joomla does not like blank passwords if (empty($credentials['password'])) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'); return false; } // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true)->select('id, password')->from('#__users')->where('username='******'username'])); $db->setQuery($query); $result = $db->loadObject(); if ($result) { $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id); if ($match === true) { // Bring this in line with the rest of the system $user = JUser::getInstance($result->id); $response->email = $user->email; $response->fullname = $user->name; if (JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } else { // Invalid password $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS'); } } else { // Invalid user $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER'); } // Check the two factor authentication if ($response->status == JAuthentication::STATUS_SUCCESS) { require_once JPATH_ADMINISTRATOR . '/components/com_users/helpers/users.php'; $methods = UsersHelper::getTwoFactorMethods(); if (count($methods) <= 1) { // No two factor authentication method is enabled return; } require_once JPATH_ADMINISTRATOR . '/components/com_users/models/user.php'; $model = new UsersModelUser(); // Load the user's OTP (one time password, a.k.a. two factor auth) configuration if (!array_key_exists('otp_config', $options)) { $otpConfig = $model->getOtpConfig($result->id); $options['otp_config'] = $otpConfig; } else { $otpConfig = $options['otp_config']; } // Check if the user has enabled two factor authentication if (empty($otpConfig->method) || $otpConfig->method == 'none') { // Warn the user if he's using a secret code but he has not // enabed two factor auth in his account. if (!empty($credentials['secretkey'])) { try { $app = JFactory::getApplication(); $this->loadLanguage(); $app->enqueueMessage(JText::_('PLG_AUTH_JOOMLA_ERR_SECRET_CODE_WITHOUT_TFA'), 'warning'); } catch (Exception $exc) { // This happens when we are in CLI mode. In this case // no warning is issued return; } } return; } // Load the Joomla! RAD layer if (!defined('FOF_INCLUDED')) { include_once JPATH_LIBRARIES . '/fof/include.php'; } // Try to validate the OTP FOFPlatform::getInstance()->importPlugin('twofactorauth'); $otpAuthReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorAuthenticate', array($credentials, $options)); $check = false; /* * This looks like noob code but DO NOT TOUCH IT and do not convert * to in_array(). During testing in_array() inexplicably returned * null when the OTEP begins with a zero! o_O */ if (!empty($otpAuthReplies)) { foreach ($otpAuthReplies as $authReply) { $check = $check || $authReply; } } // Fall back to one time emergency passwords if (!$check) { // Did the user use an OTEP instead? if (empty($otpConfig->otep)) { if (empty($otpConfig->method) || $otpConfig->method == 'none') { // Two factor authentication is not enabled on this account. // Any string is assumed to be a valid OTEP. return true; } else { /* * Two factor authentication enabled and no OTEPs defined. The * user has used them all up. Therefore anything he enters is * an invalid OTEP. */ return false; } } // Clean up the OTEP (remove dashes, spaces and other funny stuff // our beloved users may have unwittingly stuffed in it) $otep = $credentials['secretkey']; $otep = filter_var($otep, FILTER_SANITIZE_NUMBER_INT); $otep = str_replace('-', '', $otep); $check = false; // Did we find a valid OTEP? if (in_array($otep, $otpConfig->otep)) { // Remove the OTEP from the array $otpConfig->otep = array_diff($otpConfig->otep, array($otep)); $model->setOtpConfig($result->id, $otpConfig); // Return true; the OTEP was a valid one $check = true; } } if (!$check) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_SECRETKEY'); } } }
/** * Testing verifyPassword(). * * @param string $password The plaintext password to check. * @param string $hash The hash to verify against. * * @dataProvider casesVerifyPassword * @covers JUserHelper::verifyPassword * @return void * * @since 3.2 */ public function testVerifyPassword($password, $hash) { $this->assertTrue(JUserHelper::verifyPassword($password, $hash), 'Properly verifies a password'); }
/** * This method should handle any authentication and report back to the subject * * @param array $credentials Array holding the user credentials * @param array $options Array of extra options * @param object &$response Authentication response object * * @return boolean * * @since 3.2 */ public function onUserAuthenticate($credentials, $options, &$response) { // No remember me for admin if ($this->app->isAdmin()) { return false; } $response->type = 'Cookie'; // Get cookie $cookieName = JUserHelper::getShortHashedUserAgent(); $cookieValue = $this->app->input->cookie->get($cookieName); if (!$cookieValue) { return; } $cookieArray = explode('.', $cookieValue); // Check for valid cookie value if (count($cookieArray) != 2) { // Destroy the cookie in the browser. $this->app->input->cookie->set($cookieName, false, time() - 42000, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain')); JLog::add('Invalid cookie detected.', JLog::WARNING, 'error'); return false; } // Filter series since we're going to use it in the query $filter = new JFilterInput(); $series = $filter->clean($cookieArray[1], 'ALNUM'); // Remove expired tokens $query = $this->db->getQuery(true)->delete('#__user_keys')->where($this->db->quoteName('time') . ' < ' . $this->db->quote(time())); $this->db->setQuery($query)->execute(); // Find the matching record if it exists. $query = $this->db->getQuery(true)->select($this->db->quoteName(array('user_id', 'token', 'series', 'time')))->from($this->db->quoteName('#__user_keys'))->where($this->db->quoteName('series') . ' = ' . $this->db->quote($series))->where($this->db->quoteName('uastring') . ' = ' . $this->db->quote($cookieName))->order($this->db->quoteName('time') . ' DESC'); $results = $this->db->setQuery($query)->loadObjectList(); if (count($results) !== 1) { // Destroy the cookie in the browser. $this->app->input->cookie->set($cookieName, false, time() - 42000, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain')); $response->status = JAuthentication::STATUS_FAILURE; return; } else { $token = JUserHelper::hashPassword($cookieArray[0]); if (!JUserHelper::verifyPassword($cookieArray[0], $results[0]->token)) { // This is a real attack! Either the series was guessed correctly or a cookie was stolen and used twice (once by attacker and once by victim). // Delete all tokens for this user! $query = $this->db->getQuery(true)->delete('#__user_keys')->where($this->db->quoteName('user_id') . ' = ' . $this->db->quote($results[0]->user_id)); $this->db->setQuery($query)->execute(); // Destroy the cookie in the browser. $this->app->input->cookie->set($cookieName, false, time() - 42000, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain')); // Issue warning by email to user and/or admin? JLog::add(JText::sprintf('PLG_AUTH_COOKIE_ERROR_LOG_LOGIN_FAILED', $results[0]->user_id), JLog::WARNING, 'security'); $response->status = JAuthentication::STATUS_FAILURE; return false; } } // Make sure there really is a user with this name and get the data for the session. $query = $this->db->getQuery(true)->select($this->db->quoteName(array('id', 'username', 'password')))->from($this->db->quoteName('#__users'))->where($this->db->quoteName('username') . ' = ' . $this->db->quote($results[0]->user_id))->where($this->db->quoteName('requireReset') . ' = 0'); $result = $this->db->setQuery($query)->loadObject(); if ($result) { // Bring this in line with the rest of the system $user = JUser::getInstance($result->id); // Set response data. $response->username = $result->username; $response->email = $user->email; $response->fullname = $user->name; $response->password = $result->password; $response->language = $user->getParam('language'); // Set response status. $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } else { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER'); } }
function plgSystemImproved_Ajax_Login(&$subject, $config) { parent::__construct($subject, $config); $GLOBALS['username=email'] = $this->params->get('generate', 1) < 1; if (isset($_REQUEST['ialCheck'])) { $check = JRequest::getString('ialCheck'); $json = array('error' => '', 'msg' => ''); switch ($check) { case 'ialLogin': $json['field'] = 'password'; if (JSession::checkToken()) { $user = JRequest::getVar(isset($_REQUEST['username']) ? 'username' : 'email', ''); $password = JRequest::getString('password', '', 'method', JREQUEST_ALLOWRAW); if (!empty($password)) { $result = isset($_REQUEST['username']) ? OUserHelper::getUser($user) : OUserHelper::getUserByEmail($user); if ($result) { $match = 0; if (method_exists('JUserHelper', 'verifyPassword')) { $match = JUserHelper::verifyPassword($password, $result->password, $result->id); } elseif (substr($result->password, 0, 4) == '$2y$') { $password60 = substr($result->password, 0, 60); if (JCrypt::hasStrongPasswordSupport()) { $match = password_verify($password, $password60); } } else { $parts = explode(':', $result->password); $crypt = $parts[0]; $salt = @$parts[1]; $cryptmode = substr($result->password, 0, 8) == '{SHA256}' ? 'sha256' : 'md5-hex'; $testcrypt = JUserHelper::getCryptedPassword($password, $salt, $cryptmode, false); $match = $crypt == $testcrypt || $result->password == $testcrypt; } if ($match) { $json['username'] = $result->username; } else { $json['error'] = 'JGLOBAL_AUTH_INVALID_PASS'; } } else { $json['error'] = 'JGLOBAL_AUTH_NO_USER'; } } else { $json['error'] = 'JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'; } } else { $json['error'] = 'JINVALID_TOKEN'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'data[register][username]': case 'jform[username]': case 'username': $username = JRequest::getString('value'); if (OUserHelper::getId($username)) { $json['error'] = 'COM_USERS_REGISTER_USERNAME_MESSAGE'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'data[register][email]': case 'jform[email1]': case 'email': $email = JRequest::getString('value'); if (OUserHelper::getIdByEmail($email)) { $json['error'] = 'COM_USERS_REGISTER_EMAIL1_MESSAGE'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'ialRegister': // com_users if ($jf = JRequest::getVar('jform', null, 'array')) { if (!JSession::checkToken()) { $json['error'] = 'JINVALID_TOKEN'; $json['msg'] = JText::_($json['error']); die(json_encode($json)); } if (!isset($jf['email1'])) { $json['error'] = 'JGLOBAL_EMAIL'; $json['msg'] = JText::_('JGLOBAL_EMAIL') . ' ' . JText::_('JREQUIRED'); die(json_encode($json)); } if (!isset($jf['password1'])) { $json['error'] = 'JGLOBAL_PASSWORD'; $json['msg'] = JText::_('JGLOBAL_PASSWORD') . ' ' . JText::_('JREQUIRED'); die(json_encode($json)); } if (!isset($jf['username'])) { if ($this->params->get('generate', 1) > 0) { list($jf['username']) = explode('@', $jf['email1']); if (OUserHelper::getId($jf['username'])) { $jf['username'] .= OUserHelper::getNewId(); } } else { $jf['username'] = $jf['email1']; } } if (!isset($jf['name'])) { $jf['name'] = $jf['username']; } if (!isset($jf['email2'])) { $jf['email2'] = $jf['email1']; } if (!isset($jf['password2'])) { $jf['password2'] = $jf['password1']; } JRequest::setVar('jform', $jf); JFactory::getApplication()->input->post->set('jform', $jf); } $_SESSION['ialRegister'] = $jf['username']; break; } } }
public function download() { // Check for request forgeries. JSession::checkToken("post") or jexit(JText::_('JINVALID_TOKEN')); $user = JFactory::getUser(); $data = $this->input->post->get("jform", array(), "array"); $fileId = JArrayHelper::getValue($data, "file_id", 0, "int"); $userId = $user->get("id"); // Validate the user. if (!$userId) { $this->setRedirect(JRoute::_('index.php?option=com_users&view=login', false), JText::_('COM_IDENTITYPROOF_ERROR_NOT_LOG_IN')); return; } // Validate the item owner. jimport("identityproof.validator.file.owner"); $validator = new IdentityProofValidatorFileOwner(JFactory::getDbo(), $fileId, $userId); if (!$validator->isValid()) { $this->setRedirect(JRoute::_(IdentityProofHelperRoute::getProofRoute(), false), JText::_('COM_IDENTITYPROOF_ERROR_INVALID_ITEM')); return; } // Validate the password. $password = JArrayHelper::getValue($data, "password", null, "string"); $match = JUserHelper::verifyPassword($password, $user->get("password"), $userId); if (!$match) { $this->setRedirect(JRoute::_(IdentityProofHelperRoute::getProofRoute(), false), JText::_('COM_IDENTITYPROOF_ERROR_INVALID_ITEM')); return; } $params = JComponentHelper::getParams("com_identityproof"); /** @var $params Joomla\Registry\Registry */ try { // Load file data. jimport("identityproof.file"); $file = new IdentityProofFile(JFactory::getDbo()); $keys = array("id" => $fileId, "user_id" => $userId); $file->load($keys); // Prepare keys. $keys = array("private" => $file->getPrivate(), "public" => $file->getPublic()); // Prepare meta data $fileSize = $file->getMetaData("filesize"); $mimeType = $file->getMetaData("mime_type"); // Decrypt the file. $filePath = JPath::clean($params->get("files_path") . DIRECTORY_SEPARATOR . $file->getFilename()); $output = file_get_contents($filePath); $output = IdentityProofHelper::decrypt($keys, $output); } catch (Exception $e) { JLog::add($e->getMessage()); throw new Exception(JText::_('COM_IDENTITYPROOF_ERROR_SYSTEM')); } $app = JFactory::getApplication(); $app->setHeader('Content-Type', $mimeType, true); $app->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true); $app->setHeader('Content-Transfer-Encoding', 'binary', true); $app->setHeader('Pragma', 'no-cache', true); $app->setHeader('Expires', '0', true); $app->setHeader('Content-Disposition', 'attachment; filename=' . $file->getFilename(), true); $app->setHeader('Content-Length', $fileSize, true); $doc = JFactory::getDocument(); $doc->setMimeEncoding($mimeType); $app->sendHeaders(); echo $output; $app->close(); }
/** * Method to bind an associative array of data to a user object * * @param array &$array The associative array to bind to the object * * @return boolean True on success * * @since 11.1 */ public function bind(&$array) { // Let's check to see if the user is new or not if (empty($this->id)) { // Check the password and create the crypted password if (empty($array['password'])) { $array['password'] = JUserHelper::genRandomPassword(); $array['password2'] = $array['password']; } // Not all controllers check the password, although they should. // Hence this code is required: if (isset($array['password2']) && $array['password'] != $array['password2']) { JFactory::getApplication()->enqueueMessage(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'), 'error'); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); $array['password'] = JUserHelper::hashPassword($array['password']); // Set the registration timestamp $this->set('registerDate', JFactory::getDate()->toSql()); // Check that username is not greater than 150 characters $username = $this->get('username'); if (strlen($username) > 150) { $username = substr($username, 0, 150); $this->set('username', $username); } } else { // Updating an existing user if (!empty($array['password'])) { if ($array['password'] != $array['password2']) { $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); // Check if the user is reusing the current password if required to reset their password if ($this->requireReset == 1 && JUserHelper::verifyPassword($this->password_clear, $this->password)) { $this->setError(JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD')); return false; } $array['password'] = JUserHelper::hashPassword($array['password']); // Reset the change password flag $array['requireReset'] = 0; } else { $array['password'] = $this->password; } } if (array_key_exists('params', $array)) { $this->_params->loadArray($array['params']); if (is_array($array['params'])) { $params = (string) $this->_params; } else { $params = $array['params']; } $this->params = $params; } // Bind the array if (!$this->setProperties($array)) { $this->setError(JText::_('JLIB_USER_ERROR_BIND_ARRAY')); return false; } // Make sure its an integer $this->id = (int) $this->id; return true; }
/** * Save the new password after reset is done * * @param array $data The data expected for the form. * * @return mixed Exception | JException | boolean * * @since 1.6 */ public function processResetComplete($data) { // Get the form. $form = $this->getResetCompleteForm(); $data['email'] = JStringPunycode::emailToPunycode($data['email']); // Check for an error. if ($form instanceof Exception) { return $form; } // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data); // Check for an error. if ($return instanceof Exception) { return $return; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $formError) { $this->setError($formError->getMessage()); } return false; } // Get the token and user id from the confirmation process. $app = JFactory::getApplication(); $token = $app->getUserState('com_users.reset.token', null); $userId = $app->getUserState('com_users.reset.user', null); // Check the token and user id. if (empty($token) || empty($userId)) { return new JException(JText::_('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'), 403); } // Get the user object. $user = JUser::getInstance($userId); // Check for a user and that the tokens match. if (empty($user) || $user->activation !== $token) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } // Check if the user is reusing the current password if required to reset their password if ($user->requireReset == 1 && JUserHelper::verifyPassword($data['password1'], $user->password)) { $this->setError(JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD')); return false; } // Update the user object. $user->password = JUserHelper::hashPassword($data['password1']); $user->activation = ''; $user->password_clear = $data['password1']; // Save the user to the database. if (!$user->save(true)) { return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500); } // Flush the user data from the session. $app->setUserState('com_users.reset.token', null); $app->setUserState('com_users.reset.user', null); return true; }
/** * Helper wrapper method for verifyPassword * * @param string $password The plaintext password to check. * @param string $hash The hash to verify against. * @param integer $user_id ID of the user if the password hash should be updated * * @return boolean True if the password and hash match, false otherwise * * @see JUserHelper::verifyPassword() * @since 3.4 */ public function verifyPassword($password, $hash, $user_id = 0) { return JUserHelper::verifyPassword($password, $hash, $user_id); }
define('DS', DIRECTORY_SEPARATOR); require_once JPATH_BASE . DS . 'includes' . DS . 'defines.php'; require_once JPATH_BASE . DS . 'includes' . DS . 'framework.php'; //$mainframe = & JFactory::getApplication('site'); //$mainframe->initialise(); jimport('joomla.user.helper'); include_once "./webservice/config.php"; ########## For login ############# if (isset($_POST['loginbutton'])) { $username = $_POST['username']; $userpassword = $_POST['password1']; $sql_username = "******" . $prefix . "users where username = '******' "; $rs_username = mysql_query($sql_username); if ($rows_username = mysql_fetch_assoc($rs_username)) { $dbuserid = $rows_username['id']; if (JUserHelper::verifyPassword($userpassword, $rows_username['password'], $rows_username['id'])) { $loggeduser = $rows_username['username']; } else { echo "Username & password not Matched."; } } else { echo "User Not Logged In"; } } ############## FOr Registration ###################### if (isset($_POST['save'])) { $source = $_POST['source']; //die; $data = array(); $uri = JUri::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
/** * When the user is trying to access the administrator folder without being logged in make sure they had already * entered the custom administrator folder before coming here. Otherwise they are unauthorised and must be booted to * the site's front-end page. */ protected function checkCustomAdminFolder() { // Initialise $seriesFound = false; $db = $this->db; // Get the series number from the cookie $series = $this->input->cookie->get('admintools', null); // If we are told that this is a user logging out redirect them to the front-end home page, do not log a // security exception, expire the cookie $logout = $this->input->cookie->get('admintools_logout', null, 'string'); if ($logout == '!!!LOGOUT!!!') { $config = JFactory::getConfig(); $cookie_domain = $config->get('cookie_domain', ''); $cookie_path = $config->get('cookie_path', '/'); $isSecure = $config->get('force_ssl', 0) ? true : false; setcookie('admintools_logout', null, 1, $cookie_path, $cookie_domain, $isSecure, true); $this->redirectAdminToHome(); return; } // Do we have a series? $isValid = !empty($series); // Does the series exist in the db? If so, load it if ($isValid) { $query = $db->getQuery(true)->select('*')->from($db->qn('#__admintools_cookies'))->where($db->qn('series') . ' = ' . $db->q($series)); $db->setQuery($query); $storedData = $db->loadObject(); $seriesFound = true; if (!is_object($storedData)) { $isValid = false; $seriesFound = false; } } // Is the series still valid or did someone manipulate the cookie expiration? if ($isValid) { $jValid = strtotime($storedData->valid_to); if ($jValid < time()) { $isValid = false; } } // Does the UA match the stored series? if ($isValid) { $ip = AtsystemUtilFilter::getIp(); if (version_compare(JVERSION, '3.2.0', 'ge')) { $ua = $this->app->client; $uaString = $ua->userAgent; $browserVersion = $ua->browserVersion; } else { JLoader::import('joomla.environment.browser'); $browser = JBrowser::getInstance(); $uaString = $browser->getAgentString(); $browserVersion = $browser->getVersion(); } $uaShort = str_replace($browserVersion, 'abcd', $uaString); $notSoSecret = $ip . $uaShort; JLoader::import('joomla.user.helper'); if (version_compare(JVERSION, '3.2.1', 'ge')) { $isValid = JUserHelper::verifyPassword($notSoSecret, $storedData->client_hash); } else { $hash = md5($ip . $uaShort); $isValid = $hash == $storedData->client_hash; } } // Last check: session state variable if (JFactory::getSession()->get('adminlogindir', 0, 'com_admintools')) { $isValid = true; } // Delete the series cookie if found if ($seriesFound) { $query = $db->getQuery(true)->delete($db->qn('#__admintools_cookies'))->where($db->qn('series') . ' = ' . $db->q($series)); $db->setQuery($query); $db->execute(); } // Log an exception and redirect to homepage if we can't validate the user's cookie / session parameter if (!$isValid) { $this->exceptionsHandler->logAndAutoban('admindir'); $this->redirectAdminToHome(); return; } // Otherwise set the session parameter if ($seriesFound) { JFactory::getSession()->set('adminlogindir', 1, 'com_admintools'); } }