Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom PHP function to verify correct password in Joomla

I created a script outside of Joomla that can successfully generate a Joomla password:

// I copied the JUserHelper class from Joomla here
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($password, $salt);
$psw = $crypt.':'.$salt;

My question is, how can I compare this new crypt:salt I generate above to a password of an existing user in the Joomla database, and know if the password supplied to the script above is the correct password for that user in the database?

like image 796
lioman Avatar asked Feb 22 '23 12:02

lioman


2 Answers

In joomla 3.4.5:

if (!class_exists("JFactory")) {
    define('_JEXEC', 1);
    define('JPATH_BASE', dirname(__FILE__)); // specify path to joomla base directory here
    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();
}

$user = JFactory::getUser(); // or: getUser($id) to get the user with ID $id
$passwordMatch = JUserHelper::verifyPassword($entered_password, $user->password, $user->id);
like image 133
spreus Avatar answered Feb 25 '23 02:02

spreus


EDIT: I posted this before the previous reply showed.

You could always break apart the stored password from the salt as they're just separated by a ':' ?


If the page is outside of the Joomla framework you will need to include the framework which should be able to be accomplished with this (reference - codeblock below). If you are inside of the Joomla framework, skip past this block. However, I didn't test the referenced codeblock:

define( '_JEXEC', 1 );

define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE', dirname(__FILE__).DS."..".DS.".." );

require_once ( JPATH_BASE.DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE.DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

In the framework you will need to look up the user by ID or username:

$user  =& JFactory::getUser(username or id goes here);

Then if you have a match for $user you can simply do this access that user's password:

$user->password;

Then you can just compare with what your $psw


I believe that should help you on your way.

Are you looking to use this to log a user in with Joomla credentials to an external site or are you looking to log them in to a Joomla site?

like image 24
aupdo Avatar answered Feb 25 '23 01:02

aupdo