2

Using code from simular questions here I am trying to login users from a game into Joomla. My problem is that i'm not getting a positive pasword verification.

Since I was having great difficult converting my original script what worked prior joomla 3.2 with the solutions given to simular questions, I made this test script.

I created user named 'test' with a pasword 'test' and copied the encrypted pw from phpMyAmdin to the script. According to all information I can find on Joomla and this website my pasword verification should be succesfull, but its failing. Am I missing something or what is going on here?

<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', "../public_html" );
define( 'DS', DIRECTORY_SEPARATOR );

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

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

// created a test username with test as password in joomla
$username   = "test";
$password   = "test";
$dbPW       = "$P$DxdrgIwlYqFE23mQjYvgvTNO3zoVN40";  // copied from phpMyAdmin
$id         = JUserHelper::getUserId($username);
echo "$id"; //<-- matches value shown in phpMyAdmin

if(JUserHelper::verifyPassword($password, $dbPW, $id))
{
    echo "succesfull Login!";
}
else
{
    echo "failed Login!";
} 
?>
jrtc27
  • 8,496
  • 3
  • 36
  • 68
Bluestrike
  • 37
  • 1
  • 5

5 Answers5

4

Some general PHP knowledge about strings variables and quotes and having your development system properly configured certainly can help you get over this kind of issues.

I hope now you have spotted your mistake.

Below is a solution that should work for you:

<?php
/**
 * Joomla! External authentication script
 *
 * @author vdespa
 * Version 1.0
 *
 * Code adapted from /index.php
 *
 * @package    Joomla.Site
 *
 * @copyright  Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */

if (version_compare(PHP_VERSION, '5.3.1', '<'))
{
    die('Your host needs to use PHP 5.3.1 or higher to run this version of Joomla!');
}

/**
 * Constant that is checked in included files to prevent direct access.
 * define() is used in the installation folder rather than "const" to not error for PHP 5.2 and lower
 */
define('_JEXEC', 1);

if (file_exists(__DIR__ . '/defines.php'))
{
    include_once __DIR__ . '/defines.php';
}

if (!defined('_JDEFINES'))
{
    define('JPATH_BASE', __DIR__);
    require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_BASE . '/includes/framework.php';

// Instantiate the application.
$app = JFactory::getApplication('site');

// JFactory
require_once (JPATH_BASE .'/libraries/joomla/factory.php');


// Hardcoded for now
$credentials['username'] = 'admin';
$credentials['password'] = 'admin';

/**
 * Code adapted from plugins/authentication/joomla/joomla.php
 *
 * @package     Joomla.Plugin
 * @subpackage  Authentication.joomla
 *
 * @copyright   Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// Get a database object
$db    = JFactory::getDbo();
$query = $db->getQuery(true)
    ->select('id, password')
    ->from('#__users')
    ->where('username=' . $db->quote($credentials['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);
        var_dump($user);
        echo 'Joomla! Authentication was successful!';
    }
    else
    {
        // Invalid password
        // Prmitive error handling
        die('Invalid password');
    }
} else {
    // Invalid user
    // Prmitive error handling
    die('Cound not find user in the database');
}
Community
  • 1
  • 1
Valentin Despa
  • 40,712
  • 18
  • 80
  • 106
  • 1
    Thanks got it to work, looks like I miss some basic knowledge of php like what the different quotes do and better get that sorted now :) – Bluestrike Feb 08 '14 at 13:31
  • wow, I must comment! this still work with joomla 3.x.x versions, thanks a lot – Jorius Jan 27 '17 at 13:42
1

If this helps you, I think Joomla has an encryption algorithm which works like this:

  1. You create an user $user

  2. You assign it a password $password

  3. Joomla! creates a pseudo random array of 32 chars from A to Z a to z and 0 to 9 and call this array $salt

  4. Joomla! creates another variable called $hash concatenating your variable user with the salt and get the md5 from all of it, like this... $hash = md5($user.$salt)

  5. Joomla! saves a password which is again a concatenation of your hash then 2 points and then the salt, in this format.... $hash.":".$salt

  6. That's why when you check out your database your password looks like this: 3977807f631949e190966ae148a073ee:8z2Geal1qzizkhSTN6hP4fMrnnRxXbrj

I try to connect my Joomla site with my php site so i try to enter into the Joomla! db, but splitting the variables to make it work, I will post the code for anyone who wants it...

login.php

Note: the login.php file only does the comparison between the already existing password in joomla's db, and does not crypt it, I'll try to edit this comment with the additional file tomorrow because I have to go, also i will translate the Spanish parts, sorry I'm from Mexico xD

conectar();
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);     
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($contrasena);
if (isset($_POST['username']))
    {
    $pass="SELECT * FROM users WHERE username='$myusername'"; 
    $result=mysql_query($pass);
    $count=mysql_num_rows($result);
    $row=mysql_fetch_array($result);
    $pass=$row["password"];
    list($hash,$salt) = explode(":",$pass); //split the bd password
    $cripto = md5($mypassword.$salt); //md5 into pass+salt
    if (($hash==$cripto) && ($count==1))
        {
        echo "true";
        session_start();
        $_SESSION['idUsuario'] = $row['idUser'];
        $_SESSION['username'] = $myusername;
        $_SESSION['password'] = $pass;
        $_SESSION['rolUser'] = $row['rol'];
        //header("location:login_success.php");
        }
    else 
    {
        echo "false";
    }
}
else 
    {
    echo "false";
    }
desconectar();
?>

conexion.php

And also I show you my conectar() code, which only performs the connections to the db

<?php
function conectar(){

    $db_host="localhost";
    $db_usuario="root";
    $db_password="";
    $db_nombre="joomla";
    $conexion = @mysql_connect($db_host, $db_usuario, $db_password) or die(mysql_error());
    if (!$conexion) {
        die('Error in connection: ' . mysql_error());
    }
    else{
        //echo "<div class='success'> Conectado satisfactoriamente </div>";     
        $db = @mysql_select_db($db_nombre, $conexion) or die(mysql_error());
    }
}
function desconectar()
{
    @mysql_close($conexion);
}
?>

finally, the crypter, it will be something like this:

crypter.php

<?php
function pseudoRandom($values)
{
$values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$chainNumber=$values;
$originalPassword = ""; 
for($i=0;$i<$chainNumber;$i++)
    {
    $originalPassword .= substr($values,rand(0,strlen($values)),1); 
    }
return $originalPassword;
}
$originalPassword = ’caca’;
$salt=pseudoRandom(32);
$hash=md5($cadena.$salt);
$finalPassword=$hash.”:”.$salt;
?>
0

Use this JCryptPasswordSimple->verify($postpassword,$dbpasswordhash) in libraries/joomla/crypt/password/simple.php

Sam Adamsh
  • 3,331
  • 8
  • 32
  • 53
0

for a more recent version of joomla (3.x) you can use below snippet

jimport( 'joomla.user.helper' );

// Hardcoded for now
$credentials['username'] = 'admin';
$credentials['password'] = 'admin';

//create a new password or load it from the database using the user, you might need to change the encryption method
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($credentials['password'] , $salt, 'md5-hex');
$password = $crypt.':'.$salt;


$match = JUserHelper::verifyPassword($credentials['password'], $password);

if ($match === true){
    echo 'Joomla! Authentication was successful!';
}else{
    // Invalid password
    // Prmitive error handling
    die('Invalid password');
}
Alex
  • 624
  • 1
  • 9
  • 12
0

I did a login page which from outside of Joomla, ( I used Joomla 2.5, if you are using higher version, you can take it as a reference)

<?php

//this xxx.php is outside of Joomla root
//and Joomla root is in ./login folder

define( '_JEXEC', 1 );
define( 'JPATH_BASE', './login' );

// Required Files
require_once (JPATH_BASE . '/includes/defines.php');
require_once (JPATH_BASE . '/includes/framework.php');

// To use Joomla's Database Class
require_once (JPATH_BASE .'/libraries/joomla/factory.php');

/********* POST login data from some where *********/   
if(isset($_POST['uname']) && isset($_POST['psw'])) {

    $credentials['username'] = trim($_POST['uname']);
    $credentials['password'] = trim($_POST['psw']);

    if(class_exists(JFactory)) {

        $app = JFactory::getApplication('site');    

        // Get a database object
        $db     = JFactory::getDbo();
        $query  = $db->getQuery(true);

        $query->select('id, password');
        $query->from('#__users');
        $query->where('username=' . $db->quote($credentials['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
                $app->login($credentials);

                echo ("This user is logged in and Joomla also logged in! ");
            }
            else
            {
                echo ("User name and password not match! ");
            }
        }
        else
        {
            echo ("THE USER IS NOT REGISTERED! ");
        }
    }
} 

?>
Ray Lei
  • 1
  • 1