public function upload() { $app = JFactory::getApplication(); $this->getInputData(); try { jimport('joomla.user.authentication'); $auth =& JAuthentication::getInstance(); $credentials = array('username' => $this->username, 'password' => $this->password); $response = $auth->authenticate($credentials, array()); if ($response->status !== JAUTHENTICATE_STATUS_SUCCESS) { throw new Exception("Authentification error: {$response->status}"); } $tmpdir = JPath::clean($app->getCfg("tmp_path")); if (!JFolder::exists($tmpdir)) { throw new Exception("Could not open temporary directory"); } if (!is_array($this->xmlfile)) { throw new Exception("No xml file found"); } $xmlpath = $tmpdir . "/" . $this->xmlfile["name"]; if (!JFile::upload($this->xmlfile["tmp_name"], $xmlpath)) { throw new Exception("Error uploading xml file"); } $xml = new SimpleXMLElement($xmlpath, 0, true); $data = array(); $mode = (string) $xml->getName(); foreach ($xml->THE_FIRM as $firm) { $item = array(); $item["inn"] = (string) $firm["inn"]; $itemDT = DateTime::createFromFormat("d.m.Y H:i:s", (string) $firm->DateTime); $item["adding_date"] = $itemDT->format("Y-m-d H:i:s"); if ($mode == "AddChange") { $item["name"] = (string) $firm->Name; $item["address"] = (string) $firm->Address; $item["certificate1"] = (string) $firm->Number; } $data[$item["inn"]] = $item; } $model = $this->getModel("Items", "SroModel"); if (!$model->update($data, $mode)) { throw new Exception($model->getError()); } if (is_array($this->docfile)) { $config = SroHelper::getConfig(); $docpath = $config->get("rootfolder"); $docpath = JPATH_SITE . "/" . JPath::clean($docpath) . "/" . $this->docfile["name"]; if (!JFile::upload($this->docfile["tmp_name"], $docpath)) { throw new Exception("Error uploading data file"); } } } catch (Exception $e) { if ($this->talk) { echo $e->getMessage(); } } $app->close(); }
public function onBeforeBrowse() { // If we have a username/password pair, log in the user if he's a guest $username = $this->input->getString('username', ''); $password = $this->input->getString('password', ''); $user = JFactory::getUser(); if ($user->guest && !empty($username) && !empty($password)) { JLoader::import('joomla.user.authentication'); $credentials = array('username' => $username, 'password' => $password); $app = JFactory::getApplication(); $options = array('remember' => false); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status == JAuthentication::STATUS_SUCCESS) { JPluginHelper::importPlugin('user'); $results = $app->triggerEvent('onLoginUser', array((array) $response, $options)); JLoader::import('joomla.user.helper'); $userid = JUserHelper::getUserId($response->username); $user = JFactory::getUser($userid); $parameters['username'] = $user->get('username'); $parameters['id'] = $user->get('id'); } } // If we still have a guest user, show the login page if ($user->guest) { // Show login page $juri = JURI::getInstance(); $myURI = base64_encode($juri->toString()); $com = version_compare(JVERSION, '1.6.0', 'ge') ? 'users' : 'user'; JFactory::getApplication()->redirect(JURI::base() . 'index.php?option=com_' . $com . '&view=login&return=' . $myURI); return false; } // Does the user have core.manage access or belongs to SA group? $isAdmin = $user->authorise('core.manage', 'com_akeebasubs'); if ($this->input->getInt('allUsers', 0) && $isAdmin) { $this->getThisModel()->user_id(null); } else { $this->getThisModel()->user_id(JFactory::getUser()->id); } if ($this->input->getInt('allStates', 0) && $isAdmin) { $this->getThisModel()->paystate(null); } else { $this->getThisModel()->paystate('C,P'); } // Let me cheat. If the request doesn't specify how many records to show, show them all! if ($this->input->getCmd('format', 'html') != 'html') { if (!$this->input->getInt('limit', 0) && !$this->input->getInt('limitstart', 0)) { $this->getThisModel()->limit(0); $this->getThisModel()->limitstart(0); } } return true; }
public function getxCredentials() { //if (!isset($this->msg)) //{ $this->username = JRequest::getVar('user', ''); $this->password = JRequest::getVar('password', ''); $this->checkParameters(); $auth = JAuthentication::getInstance(); $credentials = array('username' => $this->username, 'password' => $this->password); JFactory::getApplication()->login(array('username' => $this->username, 'password' => $this->password)); $options = array(); $response = $auth->authenticate($credentials, $options); return $response; }
/** * Handles the onAfterInitialise event in Joomla!, logging in the user using * the one time password and forwarding him to the action URL */ public function onAfterInitialise() { $app = JFactory::getApplication(); // Only fire in administrator requests if (in_array($app->getName(), array('administrator', 'admin'))) { // Make sure it's an OneClickAction request $otp = JFactory::getApplication()->input->getCmd('oneclickaction', ''); if (empty($otp)) { return; } // Check that we do have a table! self::_checkInstallation(); // Perform expiration control self::_expirationControl(); // Make sure this OTP exists $db = JFactory::getDBO(); $sql = $db->getQuery(true)->select('*')->from($db->qn('#__oneclickaction_actions'))->where($db->qn('otp') . ' = ' . $db->q($otp)); $db->setQuery($sql); $oca = $db->loadObject(); if (empty($oca)) { return; } // Login the user $user = JFactory::getUser($oca->userid); JLoader::import('joomla.user.authentication'); $app = JFactory::getApplication(); $authenticate = JAuthentication::getInstance(); $response = new JAuthenticationResponse(); $response->status = JAuthentication::STATUS_SUCCESS; $response->type = 'joomla'; $response->username = $user->username; $response->email = $user->email; $response->fullname = $user->name; $response->error_message = ''; JPluginHelper::importPlugin('user'); $options = array(); JLoader::import('joomla.user.helper'); $results = $app->triggerEvent('onLoginUser', array((array) $response, $options)); JFactory::getSession()->set('user', $user); // Delete all similar OCA records $sql = $db->getQuery(true)->delete($db->qn('#__oneclickaction_actions'))->where($db->qn('actionurl') . ' = ' . $db->q($oca->actionurl)); $db->setQuery($sql); $db->execute(); // Forward to the requested URL $app->redirect($oca->actionurl); $app->close(); } }
/** * Logs in the user * * @since 1.3 * @access public * @param string * @return */ public static function login($username, $password) { // Get the global JAuthentication object jimport('joomla.user.authentication'); $auth = JAuthentication::getInstance(); $credentials = array('username' => $username, 'password' => $password); $options = array(); $app = JFactory::getApplication(); $response = $app->login($credentials); // Try to authenticate the user with Joomla if ($response === true) { $my = JFactory::getUser(); if ($my->guest) { return new xmlrpcresp(0, 403, JText::_('Login Failed')); } return true; } return new xmlrpcresp(0, 403, JText::_('Login Failed')); }
function checkAccount($username, $password, $email, &$userid, $conf) { $app = JFactory::getApplication(); $query = 'SELECT id,username' . ' FROM `#__users`' . ' WHERE email=' . $this->_db->Quote($email); $this->_db->setQuery($query); $user = $this->_db->loadObject(); if (isset($user)) { $credentials = array(); $username = $user->username; $credentials['username'] = $username; $credentials['password'] = $password; jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, array()); if (defined('JAUTHENTICATE_STATUS_SUCCESS')) { define('TAUTHENTICATE_STATUS_SUCCESS', JAUTHENTICATE_STATUS_SUCCESS); } else { define('TAUTHENTICATE_STATUS_SUCCESS', JAuthentication::STATUS_SUCCESS); } if ($response->status === TAUTHENTICATE_STATUS_SUCCESS) { $app->login(array('username' => $username, 'password' => $password), array()); $user = JFactory::getUser($username); $userid = $user->id; return null; } else { //Login Failed return "bad_password"; } } else { $username = $username; $userid = $this->saveRegistration($conf->comprofiler); if ($userid == false) { return "bad_password"; } else { $app->login(array('username' => $username, 'password' => $password), array()); $user = JFactory::getUser($username); $userid = $user->id; } return null; } }
public function loadUserByCredentials($user, $pass) { jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate(array('username' => $user, 'password' => $pass)); if ($response->status === JAuthentication::STATUS_SUCCESS) { $instance = JUser::getInstance($response->username); if ($instance === false) { $this->setError(JError::getError()); return false; } } else { if (isset($response->error_message)) { $this->setError($response->error_message); } else { $this->setError($response->getError()); } return false; } return $instance; }
function execute() { jimport('joomla.user.authentication'); jimport('joomla.application.component.helper'); // jimport( 'joomla.session.session' ); // jimport('joomla.plugin.plugin'); // jimport( 'plugins.user.joomla.joomla' ); // echo JPATH_BASE; //require_once ( JPATH_BASE .DS.'plugins'.DS.'user'.DS.'joomla'.DS.'joomla.php' ); // import plugins/user/joomla/joomla.php; //import libraries/joomla/application/component/helper.php $mainframe =& JFactory::getApplication('site'); $mainframe->initialise(); $mainframe->login(); $auth = JAuthentication::getInstance(); $credentials = array('username' => $this->username, 'password' => $this->password); JFactory::getApplication()->login(array('username' => $this->username, 'password' => $this->password)); //print_r($credentials); $options = array(); $response = $auth->authenticate($credentials, $options); //$response = $auth->authenticate($result, $options); // $session =& JFactory::getSession(); //$myUser = $session->get( 'myUser', 'empty' ); //$session =& JFactory::getSession(); //$session->set( 'myvar', 'helloworld' ); //onUserLogin::onUserLogin(); //var_dump($session);exit(); echo json_encode($response); echo $response->status; // echo JAUTHENTICATE_STATUS_SUCCESS; //print_r($response); // success /* return ($response->status === JAUTHENTICATE_STATUS_SUCCESS) { $response->status = true; } else { // failed $response->status = false; } echo json_encode($response);*/ }
/** * Checks the super admin credentials are valid for the currently logged in users * * @param array $credentials The credentials to authenticate the user with * * @return bool * * @since 3.6.0 */ public function captiveLogin($credentials) { // Make sure the username matches $username = isset($credentials['username']) ? $credentials['username'] : null; $user = JFactory::getUser(); if ($user->username != $username) { return false; } // Make sure the user we're authorising is a Super User if (!$user->authorise('core.admin')) { return false; } // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials); if ($response->status !== JAuthentication::STATUS_SUCCESS) { return false; } return true; }
public static function authenticateUser($username, $password) { // Get the global JAuthentication object jimport('joomla.user.authentication'); $auth = JAuthentication::getInstance(); $credentials = array('username' => $username, 'password' => $password); $options = array(); $app = JFactory::getApplication(); $response = $app->login($credentials); if ($response === true) { $my = JFactory::getUser($username); if ($my->id == 0) { return false; } else { return true; } } else { return false; } }
/** * 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); if ($response->status == JAuthentication::STATUS_SUCCESS) { $this->importPlugin('user'); $results = $this->runPlugins('onLoginUser', array((array) $response, $options)); 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; }
/** * User login into CMS framework * * @param string $username The username * @param string|boolean $password if boolean FALSE: login without password if possible * @param booleean $rememberme 1 for "remember-me" cookie method * @param int $userId used for "remember-me" login function only * @return boolean Login success */ function login( $username, $password, $rememberme = 0, $userId = null ) { header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); // needed for IE6 to accept this anti-spam cookie in higher security setting. if ( checkJversion() >= 1 ) { // Joomla 1.5 RC and above: if ( $password !== false ) { $result = $this->_baseFramework->login( array( 'username' => $username, 'password' => $password ), array( 'remember' => $rememberme ) ); } else { // login without password: jimport( 'joomla.user.authentication' ); // load user plugins: JPluginHelper::importPlugin( 'user' ); // get JAuthentication object: $authenticate =& JAuthentication::getInstance(); $dispatcher =& JDispatcher::getInstance(); $response = new JAuthenticationResponse(); // prepare our SUCCESS login response including user data: global $_CB_database; $row = new moscomprofilerUser( $_CB_database ); $row->loadByUsername( stripslashes( $username ) ); $response->status = JAUTHENTICATE_STATUS_SUCCESS; $response->username = $username; $response->fullname = $row->name; // now we attempt user login and check results: if ( checkJversion() == 2 ) { $login = $dispatcher->trigger( 'onUserLogin', array( (array) $response, array( 'action' => 'core.login.site' ) ) ); } else { $login = $dispatcher->trigger( 'onLoginUser', array( (array) $response, array() ) ); } $result = ! in_array( false, $login, true ); } if ( $result ) { $user =& JFactory::getUser(); $this->_myId = (int) $user->id; $this->_myUsername = $user->username; $this->_myUserType = $user->usertype; $this->_myCmsGid = $user->get('aid', 0); $lang =& JFactory::getLanguage(); if ( checkJversion() == 2 ) { $this->_myLanguage = strtolower( preg_replace( '/^(\w+).*$/i', '\1', $lang->getName() ) ); } else { $this->_myLanguage = $lang->getBackwardLang(); } } } else { // Mambo 4.5.x and Joomla before 1.0.13+ (in fact RC3+) do need hashed password for login() method: if ( $password !== false ) { $hashedPwdLogin = ( ( checkJversion() == 0 ) && ! function_exists( 'josHashPassword' ) ); // more reliable version-checking than the often hacked version.php file! if ( $hashedPwdLogin ) { // Joomla 1.0.12 and below: $dummyRow = new moscomprofilerUser( $_CB_database ); $this->_baseFramework->login( $username, $dummyRow->hashAndSaltPassword( $password ), $rememberme, $userId ); } else { $this->_baseFramework->login( $username, $password, $rememberme, $userId ); } // Joomla 1.0 redirects bluntly if login fails! so we need to check by ourselves below: $result = true; } else { // login without password: //TBD MAMBO 4.6 support here ! global $_CB_database, $mainframe, $_VERSION; $row = new moscomprofilerUser( $_CB_database ); $row->loadByUsername( stripslashes( $username ) ); // prepare login session with user data: $session =& $mainframe->_session; $session->guest = 0; $session->username = $row->username; $session->userid = (int) $row->id; $session->usertype = $row->usertype; $session->gid = (int) $row->gid; // attempt to login user: if ( $session->update() ) { $result = true; } // check if site is demo or production: if ( $_VERSION->SITE ) { // site is production; remove duplicate sessions: $query = 'DELETE FROM ' . $_CB_database->NameQuote( '#__session' ) . "\n WHERE " . $_CB_database->NameQuote( 'session_id' ) . ' != ' . $_CB_database->Quote( $session->session_id ) . "\n AND " . $_CB_database->NameQuote( 'username' ) . ' = ' . $_CB_database->Quote( $row->username ) . "\n AND " . $_CB_database->NameQuote( 'userid' ) . ' = ' . (int) $row->id . "\n AND " . $_CB_database->NameQuote( 'gid' ) . ' = ' . (int) $row->gid . "\n AND " . $_CB_database->NameQuote( 'guest' ) . ' = 0'; $_CB_database->setQuery( $query ); if ( ! $_CB_database->query() ) { trigger_error( 'loginUser 1 SQL error: ' . $_CB_database->stderr( true ), E_USER_WARNING ); } } // get current datetime: $currentDate = date( 'Y-m-d H:i:s', $this->now() ); // update user last login with current datetime: $query = 'UPDATE ' . $_CB_database->NameQuote( '#__users' ) . "\n SET " . $_CB_database->NameQuote( 'lastvisitDate' ) . " = " . $_CB_database->Quote( $currentDate ) . "\n WHERE " . $_CB_database->NameQuote( 'id' ) . " = " . (int) $session->userid; $_CB_database->setQuery( $query ); if ( ! $_CB_database->query() ) { trigger_error( 'loginUser 2 SQL error: ' . $_CB_database->stderr( true ), E_USER_WARNING ); } // clean old cache: mosCache::cleanCache(); } if ( checkJversion() == 0 ) { global $mainframe; $mymy = $mainframe->getUser(); $this->_myId = (int) $mymy->id; $this->_myUsername = $mymy->username; $this->_myUserType = $mymy->usertype; $this->_myCmsGid = $mymy->gid; if ( ! $this->_myId ) { $result = false; } } //TBD MAMBO 4.6 support here ! } return $result; }
/** * Login authentication function. * * Username and encoded password are passed the onUserLogin event which * is responsible for the user validation. A successful validation updates * the current session record with the user's details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean True on success. * * @since 3.2 */ public function login($credentials, $options = array()) { // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); // Import the user plugin group. JPluginHelper::importPlugin('user'); if ($response->status === JAuthentication::STATUS_SUCCESS) { $session = JFactory::getSession($options); // Fork the session to prevent session fixation issues if it's already active if ($session->getState() != 'active') { $session->start(); } else { $session->fork(); } /* * Validate that the user should be able to login (different to being authenticated). * This permits authentication plugins blocking the user. */ $authorisations = $authenticate->authorise($response, $options); foreach ($authorisations as $authorisation) { $denied_states = array(JAuthentication::STATUS_EXPIRED, JAuthentication::STATUS_DENIED); if (in_array($authorisation->status, $denied_states)) { // Trigger onUserAuthorisationFailure Event. $this->triggerEvent('onUserAuthorisationFailure', array((array) $authorisation)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // Return the error. switch ($authorisation->status) { case JAuthentication::STATUS_EXPIRED: JFactory::getApplication()->enqueueMessage(JText::_('JLIB_LOGIN_EXPIRED'), 'error'); return false; break; case JAuthentication::STATUS_DENIED: JFactory::getApplication()->enqueueMessage(JText::_('JLIB_LOGIN_DENIED'), 'error'); return false; break; default: JFactory::getApplication()->enqueueMessage(JText::_('JLIB_LOGIN_AUTHORISATION'), 'error'); return false; break; } } } // OK, the credentials are authenticated and user is authorised. Let's fire the onLogin event. $results = $this->triggerEvent('onUserLogin', array((array) $response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ $user = JFactory::getUser(); if ($response->type == 'Cookie') { $user->set('cookieLogin', true); } if (in_array(false, $results, true) == false) { $options['user'] = $user; $options['responseType'] = $response->type; // The user is successfully logged in. Run the after login events $this->triggerEvent('onUserAfterLogin', array($options)); } return true; } // Trigger onUserLoginFailure Event. $this->triggerEvent('onUserLoginFailure', array((array) $response)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will have been raised by the user plugin if ($response->status !== JAuthentication::STATUS_SUCCESS) { JLog::add($response->error_message, JLog::WARNING, 'jerror'); } return false; }
/** * Login validation function * * Username and encoded password is compared to db entries in the mos_users * table. A successful validation returns true, otherwise false */ function vmCheckPass() { global $database, $perm, $my, $mainframe; // only allow access to admins or storeadmins if ($perm->check("admin,storeadmin")) { $username = $my->username; $passwd_plain = $passwd = trim(vmGet($_POST, 'passwd', '')); if (empty($passwd_plain)) { $GLOBALS['vmLogger']->err('Password empty!'); return false; } $passwd = md5($passwd); $bypost = 1; if (!$username || !$passwd || $_REQUEST['option'] != "com_virtuemart") { return false; } elseif (vmIsJoomla('1.5')) { $credentials = array(); $credentials['username'] = $username; $credentials['password'] = $passwd_plain; $options = array(); jimport('joomla.user.authentication'); $authenticate =& JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) { return true; } else { return false; } } else { if (vmIsJoomla('1.0.12', '<=', false)) { $database->setQuery("SELECT id, gid, block, usertype" . "\nFROM #__users" . "\nWHERE username='******' AND password='******'"); $row = null; $res = $database->loadObject($row); } else { $query = "SELECT id, name, username, password, usertype, block, gid" . "\n FROM #__users" . "\n WHERE username = " . $database->Quote($username); $database->setQuery($query); $row = null; $database->loadObject($row); list($hash, $salt) = explode(':', $row->password); $cryptpass = md5($passwd_plain . $salt); $res = $hash == $cryptpass; } if ($res) { return true; } else { $GLOBALS['vmLogger']->err('The Password you\'ve entered is not correct for your User Account'); return false; } } } return false; }
/** * This checks for the correct response to authorising a user * * @param string $input User name * @param string $expect Expected user id * @param string $message Expected error info * * @return void * * @dataProvider casesAuthorise * @since 11.1 * @covers JAuthentication::authorise */ public function testAuthorise($input, $expect, $message) { $authentication = JAuthentication::getInstance(); $this->assertEquals($expect, $authentication->authorise($input), $message); }
/** * Testing authenticate * * @return void * @todo Implement testAuthenticate(). */ public function testAuthenticate() { include_once JPATH_BASE . '/libraries/joomla/plugin/helper.php'; include_once JPATH_BASE . '/libraries/joomla/user/user.php'; include_once JPATH_BASE . '/libraries/joomla/session/session.php'; $user = new JUser; /* * The lines below are commented out because they cause an error, but I don't understand why * they do, so I'm leaving them here in case it's a bug that is later fixed and they're needed. */ $mockSession = $this->getMock('JSession', array( '_start', 'get')); //$mockSession->expects($this->any())->method('get')->with($this->equalTo('user'))->will( // $this->returnValue($user) //); JFactory::$session = $mockSession; $this->object = JAuthentication::getInstance(); $tester = $this->getDatabaseTester(); $tester->onSetUp(); $credentials['username'] = '******'; $credentials['password'] = '******'; $options = array(); $response = $this->object->authenticate($credentials, $options); $this->assertThat( true, $this->equalTo((bool)$response->status) ); }
/** * Login authentication function. * * Username and encoded password are passed the the onUserLogin event which * is responsible for the user validation. A successful validation updates * the current session record with the user's details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean True on success. * * @since 11.1 */ public function login($credentials, $options = array()) { // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) { // Import the user plugin group. JPluginHelper::importPlugin('user'); // OK, the credentials are authenticated. Lets fire the onLogin event. $results = $this->triggerEvent('onUserLogin', array((array) $response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ if (!in_array(false, $results, true)) { // Set the remember me cookie if enabled. if (isset($options['remember']) && $options['remember']) { jimport('joomla.utilities.simplecrypt'); jimport('joomla.utilities.utility'); // Create the encryption key, apply extra hardening using the user agent string. $key = JUtility::getHash(@$_SERVER['HTTP_USER_AGENT']); $crypt = new JSimpleCrypt($key); $rcookie = $crypt->encrypt(serialize($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; // Use domain and path set in config for cookie if it exists. $cookie_domain = $this->getCfg('cookie_domain', ''); $cookie_path = $this->getCfg('cookie_path', '/'); setcookie(JUtility::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain); } return true; } } // Trigger onUserLoginFailure Event. $this->triggerEvent('onUserLoginFailure', array((array) $response)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will ahve been raised by the user plugin if ($response->status !== JAUTHENTICATE_STATUS_SUCCESS) { JError::raiseWarning('SOME_ERROR_CODE', JText::_('JLIB_LOGIN_AUTHENTICATE')); } return false; }
/** * Login authentication function. * * Username and encoded password are passed the the onLoginUser event which * is responsible for the user validation. A successful validation updates * the current session record with the users details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array Array( 'username' => string, 'password' => string ) * @return boolean True on success. * @access public * @since 1.5 */ function login($credentials, $options = array()) { //Force the site $options['site'] = $this->_site; // Get the global JAuthentication object jimport( 'joomla.user.authentication'); $authenticate = & JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) { $session = &JFactory::getSession(); // we fork the session to prevent session fixation issues $session->fork(); $this->_loadSession($session->getId()); // Import the user plugin group JPluginHelper::importPlugin('user'); // OK, the credentials are authenticated. Lets fire the onLogin event $results = $this->triggerEvent('onLoginUser', array((array)$response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ if (!in_array(false, $results, true)) { return true; } } // Trigger onLoginFailure Event $this->triggerEvent('onLoginFailure', array((array)$response)); // If silent is set, just return false if (isset($options['silent']) && $options['silent']) { return false; } // Return the error return JError::raiseWarning('SOME_ERROR_CODE', JText::_('E_LOGIN_AUTHENTICATE')); }
public function actionAuth() { if (empty($this->request->user->username) || empty($this->request->user->password)) { $this->error = 'must provide username and password to authenticate'; $this->response->result = false; return; } $credentials = array(); $credentials['username'] = $this->request->user->username; $credentials['password'] = $this->request->user->password; // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, array()); $this->response->result = $response->status === JAUTHENTICATE_STATUS_SUCCESS; }
/** * Log in a user if necessary * * @return boolean True if a user was logged in */ public function loginUser() { // No need to log in a user if the user is already logged in if (!$this->container->platform->getUser()->guest) { return false; } // This is Joomla!'s login and user helpers \JPluginHelper::importPlugin('user'); JLoader::import('joomla.user.helper'); // Get the query parameters $dlid = $this->input->getString('dlid', null); $credentials = array(); $credentials['username'] = $this->input->getUsername('username', ''); $credentials['password'] = $this->input->get('password', '', 'raw', 3); // Initialise $user_id = 0; // First attempt to log in by download ID if (!empty($dlid)) { try { $user_id = Filter::getUserFromDownloadID($dlid)->id; } catch (\Exception $exc) { $user_id = 0; } } // If the dlid failed, used he legacy username/password pair if ($user_id === 0 && !empty($credentials['username']) && !empty($credentials['password'])) { \JLoader::import('joomla.user.authentication'); $options = array('remember' => false); $authenticate = \JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status == \JAuthentication::STATUS_SUCCESS) { $user_id = \JUserHelper::getUserId($response->username); } } // Log in the user if ($user_id !== 0) { // Mark the user login so we can log him out later on $this->haveLoggedInAUser = true; // This line returns an empty JUser object $newUserObject = new \JUser(); // This line FORCE RELOADS the user record. $newUserObject->load($user_id); // Mark the user as logged in $newUserObject->block = 0; $newUserObject->set('guest', 0); // Register the needed session variables $session = \JFactory::getSession(); $session->set('user', $newUserObject); $db = $this->container->db; // Check to see the the session already exists. $app = \JFactory::getApplication(); $app->checkSession(); // Update the user related fields for the Joomla sessions table. $query = $db->getQuery(true)->update($db->qn('#__session'))->set(array($db->qn('guest') . ' = ' . $db->q($newUserObject->get('guest')), $db->qn('username') . ' = ' . $db->q($newUserObject->get('username')), $db->qn('userid') . ' = ' . (int) $newUserObject->get('id')))->where($db->qn('session_id') . ' = ' . $db->q($session->getId())); $db->setQuery($query); $db->execute(); // Hit the user last visit field $newUserObject->setLastVisit(); } return $this->haveLoggedInAUser; }
/** * 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; }
/** * Test... * * @covers JAuthentication::getInstance * * @return void */ public function testGetInstance() { $instance = JAuthentication::getInstance(); $this->assertThat($instance, $this->isInstanceOf('JAuthentication')); }
/** * Authenticate a person and create a new session If a username password is passed then the user is first logged in. * * @param KCommandContext $context Command chain context * * @throws LibBaseControllerExceptionUnauthorized If authentication failed * @throws LibBaseControllerExceptionForbidden If person is authenticated but forbidden * @throws RuntimeException for unkown error */ protected function _actionAdd(KCommandContext $context) { $data = $context->data; if ($data->return) { $_SESSION['return'] = $this->getService('com://site/people.filter.return')->sanitize($data->return); $context->url = base64UrlDecode($data->return); } else { $_SESSION['return'] = null; } jimport('joomla.user.authentication'); $authentication =& JAuthentication::getInstance(); $credentials = array('username' => $data->username, 'password' => $data->password, 'remember' => $data->remember); $options = array(); $authResponse = $authentication->authenticate($credentials, $options); if ($authResponse->status === JAUTHENTICATE_STATUS_SUCCESS) { $this->getService('com:people.helper.person')->login($credentials, $credentials['remember']); $this->getResponse()->status = KHttpResponse::ACCEPTED; $this->getResponse()->setRedirect($context->url); $_SESSION['return'] = null; } else { $this->setMessage('COM-PEOPLE-AUTHENTICATION-FAILED', 'error'); JFactory::getApplication()->triggerEvent('onLoginFailure', array((array) $authResponse)); throw new LibBaseControllerExceptionUnauthorized('Authentication Failed. Check username/password'); $this->getResponse()->status = KHttpResponse::FORBIDDEN; $this->getResponse()->setRedirect(JRoute::_('option=com_people&view=session')); } return true; }
/** * User login into CMS framework * * @param string $username The username * @param string|boolean $password if boolean FALSE: login without password if possible * @param int $rememberMe 1 for "remember-me" cookie method * @param int $userId used for "remember-me" login function only * @param string $secretKey used for "two step authentication" login function only * @return boolean Login success */ public function login($username, $password, $rememberMe = 0, $userId = null, $secretKey = null) { header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); // needed for IE6 to accept this anti-spam cookie in higher security setting. if ($password !== false) { $result = $this->_baseFramework->login(array('username' => $username, 'password' => $password, 'secretkey' => $secretKey), array('remember' => $rememberMe)); } else { // login without password: jimport('joomla.user.authentication'); // load user plugins: JPluginHelper::importPlugin('user'); // get JAuthentication object: JAuthentication::getInstance(); $dispatcher = JDispatcher::getInstance(); // 2.5 has only JDispatcher. Only 3.0 introduced JEventDispatcher $response = new JAuthenticationResponse(); // prepare our SUCCESS login response including user data: $row = new UserTable(); $row->loadByUsername(stripslashes($username)); $response->status = JAuthentication::STATUS_SUCCESS; $response->username = $username; $response->fullname = $row->name; // now we attempt user login and check results: $login = $dispatcher->trigger('onUserLogin', array((array) $response, array('action' => 'core.login.site'))); $result = !in_array(false, $login, true); } return $result; }
/** * Remebers handling. */ public function onAfterInitialise() { global $mainframe; $viewer = get_viewer(); if (!$viewer->guest() && !$viewer->enabled) { KService::get('com://site/people.helper.person')->logout(); } // No remember me for admin if ($mainframe->isAdmin()) { return; } jimport('joomla.utilities.utility'); jimport('joomla.utilities.simplecrypt'); $user = array(); $remember = JUtility::getHash('JLOGIN_REMEMBER'); // for json requests obtain the username and password from the $_SERVER array // else if the remember me cookie exists, decrypt and obtain the username and password from it if ($viewer->guest() && KRequest::has('server.PHP_AUTH_USER') && KRequest::has('server.PHP_AUTH_PW') && KRequest::format() == 'json') { $user['username'] = KRequest::get('server.PHP_AUTH_USER', 'raw'); $user['password'] = KRequest::get('server.PHP_AUTH_PW', 'raw'); } elseif ($viewer->guest() && isset($_COOKIE[$remember]) && $_COOKIE[$remember] != '') { $key = JUtility::getHash(KRequest::get('server.HTTP_USER_AGENT', 'raw')); if ($key) { $crypt = new JSimpleCrypt($key); $cookie = $crypt->decrypt($_COOKIE[$remember]); $user = (array) @unserialize($cookie); } } else { return; } if ($viewer->guest() && count($user)) { try { jimport('joomla.user.authentication'); $authentication =& JAuthentication::getInstance(); $authResponse = $authentication->authenticate($user, array()); if ($authResponse->status == JAUTHENTICATE_STATUS_SUCCESS) { KService::get('com://site/people.helper.person')->login($user, true); } } catch (RuntimeException $e) { //only throws exception if we are using JSON format //otherwise let the current app handle it if (KRequest::format() == 'json') { throw $e; } } } return; }
protected function authenticateUser($username, $password) { jimport( 'joomla.user.authentication'); if(!isset($username) || !isset($password)) return false; $auth = JAuthentication::getInstance(); $credentials['username'] = $username; $credentials['password'] = $password; $authuser = $auth->authenticate($credentials, null); if($authuser->status == JAuthentication::STATUS_FAILURE || empty($authuser->username) || empty($authuser->password) || empty($authuser->email)){ return false; } $user = JUser::getInstance($authuser->username); //Check Status if(empty($user->id) || $user->block || !empty($user->activation)){ return false; } JFactory::getSession()->set('user', $user); return $user; }
/** * Login authentication function. * * Username and encoded password are passed the the onLoginUser event which * is responsible for the user validation. A successful validation updates * the current session record with the users details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array Array( 'username' => string, 'password' => string ) * @param array Array( 'remember' => boolean ) * @return boolean True on success. * @access public * @since 1.5 */ function login($credentials, $options = array()) { // Get the global JAuthentication object jimport('joomla.user.authentication'); $authenticate =& JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAUTHENTICATE_STATUS_SUCCESS) { $session =& JFactory::getSession(); // we fork the session to prevent session fixation issues $session->fork(); $this->_createSession($session->getId()); // Import the user plugin group JPluginHelper::importPlugin('user'); // OK, the credentials are authenticated. Lets fire the onLogin event $results = $this->triggerEvent('onLoginUser', array((array) $response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ if (!in_array(false, $results, true)) { // Set the remember me cookie if enabled if (isset($options['remember']) && $options['remember']) { jimport('joomla.utilities.simplecrypt'); jimport('joomla.utilities.utility'); //Create the encryption key, apply extra hardening using the user agent string $agent = @$_SERVER['HTTP_USER_AGENT']; // Ignore empty and crackish user agents if ($agent != '' && $agent != 'JLOGIN_REMEMBER') { $key = JUtility::getHash($agent); $crypt = new JSimpleCrypt($key); $rcookie = $crypt->encrypt(serialize($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; setcookie(JUtility::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, '/'); } } return true; } } // Trigger onLoginFailure Event $this->triggerEvent('onLoginFailure', array((array) $response)); // If silent is set, just return false if (isset($options['silent']) && $options['silent']) { return false; } // Return the error return JError::raiseWarning('SOME_ERROR_CODE', JText::_('E_LOGIN_AUTHENTICATE')); }
function authenticateUser($username, $password) { // Get the global JAuthentication object jimport('joomla.user.authentication'); $auth =& JAuthentication::getInstance(); $credentials = array('username' => $username, 'password' => $password); $options = array(); $response = $auth->authenticate($credentials, $options); //TODO CHECK that registred users do not have access //$user =& JFactory::getUser($username); //plgXMLRPCOpenERP2VmHelper::getUserAid( $user ); return $response->status === JAUTHENTICATE_STATUS_SUCCESS; }
/** * Login authentication function. * * Username and encoded password are passed the onUserLogin event which * is responsible for the user validation. A successful validation updates * the current session record with the user's details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean True on success. * * @since 11.1 */ public function login($credentials, $options = array()) { // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAuthentication::STATUS_SUCCESS) { // validate that the user should be able to login (different to being authenticated) // this permits authentication plugins blocking the user $authorisations = $authenticate->authorise($response, $options); foreach ($authorisations as $authorisation) { $denied_states = array(JAuthentication::STATUS_EXPIRED, JAuthentication::STATUS_DENIED); if (in_array($authorisation->status, $denied_states)) { // Trigger onUserAuthorisationFailure Event. $this->triggerEvent('onUserAuthorisationFailure', array((array) $authorisation)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // Return the error. switch ($authorisation->status) { case JAuthentication::STATUS_EXPIRED: return JError::raiseWarning('102002', JText::_('JLIB_LOGIN_EXPIRED')); break; case JAuthentication::STATUS_DENIED: return JError::raiseWarning('102003', JText::_('JLIB_LOGIN_DENIED')); break; default: return JError::raiseWarning('102004', JText::_('JLIB_LOGIN_AUTHORISATION')); break; } } } // Import the user plugin group. JPluginHelper::importPlugin('user'); // OK, the credentials are authenticated and user is authorised. Lets fire the onLogin event. $results = $this->triggerEvent('onUserLogin', array((array) $response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ if (!in_array(false, $results, true)) { // Set the remember me cookie if enabled. if (isset($options['remember']) && $options['remember']) { // Create the encryption key, apply extra hardening using the user agent string. $privateKey = self::getHash(@$_SERVER['HTTP_USER_AGENT']); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); $rcookie = $crypt->encrypt(json_encode($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; // Use domain and path set in config for cookie if it exists. $cookie_domain = $this->getCfg('cookie_domain', ''); $cookie_path = $this->getCfg('cookie_path', '/'); // Check for SSL connection $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || getenv('SSL_PROTOCOL_VERSION'); setcookie(self::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain, $secure, true); } return true; } } // Trigger onUserLoginFailure Event. $this->triggerEvent('onUserLoginFailure', array((array) $response)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will have been raised by the user plugin if ($response->status !== JAuthentication::STATUS_SUCCESS) { JError::raiseWarning('102001', $response->error_message); } return false; }
function authenticateUser($username, $password) { // Get the global JAuthentication object jimport('joomla.user.authentication'); $auth =& JAuthentication::getInstance(); $credentials = array('username' => $username, 'password' => $password); $options = array(); $response = $auth->authenticate($credentials, $options); return $response->status === JAUTHENTICATE_STATUS_SUCCESS; }