Pregunta

My first question is: How can I programmatically register user for Joomla 3.2.1 In previous versions of Joomla MD5 encryption is used:

$username="John";
$password="pass";
$password=md5($password);
$ukaz="INSERT INTO joomla_users (username,password,email) VALUES ('".$username."','".$password."','".$email."')";
mysqli_query($con,$ukaz);

But in joomla 3.2.1 bcrypt encryption is used, which also uses "salt", which changes each time. That is the thing I don't understand.

For checking user credentials in previous versions of joomla I would use:

$username="John";
$password="pass";
$password=md5($password);
$result = mysqli_query($con,"SELECT * FROM joomla_users WHERE username LIKE '".$username."' AND password LIKE '".$password."'");


$output;
$suma = $result->num_rows; 

if($suma==0)
{
$result2 = mysqli_query($con,"SELECT * FROM joomla_users WHERE username LIKE '".$username."'");
$suma2 = $result2->num_rows; 

  if($suma2==1)
  {
   $output="WRONG_PASSWORD";
  }
  else
  {
  $output="USER_DOES_NOT_EXISTS";
  }
}
 else
{
$output="OK";
}

Please help me solve this problem.

¿Fue útil?

Solución 2

I managed to solve this problem, thanks to answers from all of you.

But I have 1 more question: How can i send an activation email to user?

This is the registration code:

<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', "/home/gddregop/public_html" );//this is when we are in the root
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();   
ini_set('default_charset', 'utf-8');
include('database_settings.php');

$username=$_POST["username"];
$password=$_POST["password"];
$email=$_POST["email"];    

$salt = JUserHelper::genRandomPassword(32);
$crypt = md5($password.$salt);
$password = $crypt.':'.$salt;
$con=mysqli_connect("localhost",$username_baza_joomla,$password_baza_joomla,$database_baza_joomla);
mysqli_set_charset($con,"utf8");

$SQL1 = "SELECT * FROM joomla_users WHERE username LIKE ?";

if ($stmt = $con->prepare($SQL1)) {

$stmt->bind_param("s", $username);
$stmt->execute();    
$stmt->store_result();     
$vsota = $stmt->num_rows;
}  

 $vrnjeno;


if($vsota==0)
{
$SQL2 = "SELECT * FROM joomla_users WHERE email LIKE ?";
   if ($stmt2 = $con->prepare($SQL2)) {

$stmt2->bind_param("s", $email);
$stmt2->execute();    
$stmt2->store_result();     
$vsota2 = $stmt2->num_rows;
}            

  if($vsota2==0)
  {
   $vrnjeno="OK";
  }
  else
  {
  $vrnjeno="EMAIL_EXISTS";
  }
 }
else
{
$vrnjeno="USERNAME_EXISTS";
}
echo $vrnjeno;
if($vrnjeno=="OK")
{
$data = array(
'name'=>'name',
'username'=>$username,
'password'=>$password,
'email'=>$email,
'sendEmail'=>1,  
"groups"=>array("2"),
'block'=>1,);

 $user = new JUser;

try{
$user->bind($data);
$user->save();
}catch(Exception $e){
var_dump($e->getMessage());
}

}
mysqli_close($con);    

?>

This is the login code(check for user credentials):

<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', "/home/grdddegap/public_html" );//this is when we are not in the root
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();        

$username=$_POST["username"];
$password=$_POST["password"];
ini_set('default_charset', 'utf-8');
include('nastavitve.php');
if (!empty($username))
{
 $con=mysqli_connect("localhost",$username_baza_joomla,$password_baza_joomla,$database_baza_joomla);
mysqli_set_charset($con,"utf8");

$SQL = "SELECT name,email,password,block FROM joomla_users WHERE username LIKE ?";

if ($stmt = $con->prepare($SQL)) {

$stmt->bind_param("s", $username);
$stmt->execute();    
$stmt->store_result();     
$vsota = $stmt->num_rows;

  if($vsota==1)
  {

    $stmt->bind_result($name, $email, $password_baza,$block); 
   $stmt->fetch();

    if((JUserHelper::verifyPassword($password, $password_baza, $user_id = 0)==1))
     {

        if($block==1)
        {
        $vrnjeno="EMAIL_VALIDATION";          
        }
        else
        {
        $vrnjeno="OK";
        }
     }
     else
     {
     $vrnjeno="WRONG_PASSWORD";
     }  


     }

  else
  {
  $vrnjeno="USER_DOES_NOT_EXISTS";
  }


echo $vrnjeno;
}
else
{
echo "SQL INJECTION";
}
}
else
{
echo "STOP THIS YOU HECKER";
}
$mainframe->close();   
mysqli_close($con); 

?>

Otros consejos

Try this:

$password = 'password';
$salt   = JUserHelper::genRandomPassword(32);
$crypted  = JUserHelper::getCryptedPassword($password, $salt);
$cpassword = $crypted.':'.$salt;

$data = array(
'name'=>'name',
'username'=>'username',
'password'=>$cpassword,
'email'=>'email@email.com',
'block'=>0,);

$user = new JUser;

try{
  $user->bind($data);
  $user->save();
}catch(Exception $e){
    var_dump($e->getMessage());
}

Now that I read your code again I think your script is not connected with joomla framework. If that is the case you could try this:

<?php
include 'libraries/phpass/PasswordHash.php';
$phpass = new PasswordHash(10, true);
$passwordHash = $phpass->HashPassword($password);

That should give you a hashed password, but you need access to joomla phpass lib.

Also what you are doing there leaves you open to SQL INJECTIONS. Please try taking time to read about mysqli and prepared statements. Also if you need to verify user login you need to query the user with that username, if row exists fetch it and use this:

<?php 
<?php
include 'libraries/phpass/PasswordHash.php';
$phpass = new PasswordHash(10, true);
if($phpass->VerifyPassword($userInputPassword, $hashFromDb)){
    // Password ok
}else{
    // Wrong password
}

When you say programaticly do you you mean using an external source of users or do you mean you want to do it in the cms with users registering themselves? The problem is that JUser has a lot of dependencies if you are not in a current session. You can try this CLI app that I wrote for bulk importing, YMMV. It's not as polished as it could be but it works.

https://github.com/elinw/AddUsersFromTable

I really wouldn't recommend messing around with the encryption directly. The only problem with what I'm doing here is that you need to feed it plaintext passwords or else you need to have everyone do reset password or else you need to run a script to do that automatically and send out the reset emails.

At my work we develop and sometimes we use the same user (joomla one) for access to our system. After the upgrade the old verification system didn't work, so we solved this issue using the checkpassword function shown below:

<?php
/*  ==============================================================================
    ====     Fichero: mtote.php                         ==
    ====     Descripción: Ejemplo de como validar usuarios en instalaciones     ==
    ====        de joomla 2.5.x (nuevo encriptado usando hash+md5               ==
    ====     Programado por: Ing. Marvin JOsué Aguilar Romero y                 ==
    ====        José Luis Rodríguez García                                      ==
    ====     Fecha: Jueves 18 de Junio de 2014, 11:00 (GMT -6)                  ==
    ====     Contacto: drkmarvin@gmail.com, tote.ote@gmail.com                  ==
    ====     Informacíón adicional: fué necesario el presente código debido a   ==
    ====       que en nuestro trabajo hay sistemas que usan las credenciales    ==
    ====       de joomla para su acceso.                                        ==
    ==============================================================================
*/ 
//Obtaining configuration info for database conection using config.php 
//Obtenemos los datos de configfuración de php para la conexipón a la base de datos

require_once('./configuration.php');

//Pedimos el uso de la librería para encriptación
//ASk for use of crypt library
require_once('./libraries/phpass/PasswordHash.php');

$user1 = "usuario_a_verificar"; //The user who password wanna check
$jconf = new JConfig;  //Instanciamos un objeto jconf / Initialize a jconf object

$conexion = @mysql_connect($jconf->host,$jconf->user,$jconf->password,false,0); 
    @mysql_select_db($jconf->db);   //elegir base de datos /choose database

$sql = sprintf("SELECT * FROM %susers  WHERE  %susers.username='%s' LIMIT 1;",$jconf->dbprefix,$jconf->dbprefix, $user1); //Seleccionamos todos los usuarios de la tabla usuario
//selecting user from database

$request = @mysql_query($sql); //Ejecutamos las consultas previas /Execute the previous sql statments

//Si hemos encontrado coincidencia ingresamos al ciclo
//If we find a match we enter in this cycle

if (mysql_num_rows($request) == 1) 
{
    //obtenemos un arreglo con el usuario y sus datos
    //Store the user info on an array
    $user = array('User' => mysql_fetch_assoc($request));

    //Obtenemos en una variable el password en la base de datos
    //We store on a variable the hash password from database 
    $par = $user['User']['password']; 

    //ALmacenamos el password que queremos verificar si de verdad existe para el usuario 
    //NOw store on a variable the password that we wanna check for the user
    $userInputPassword = 'password_que_Creemos_pertenece_al_usuario';

    //Instanciar el objeto phpass       
    //Initialice an ohoass object
    $phpass = new PasswordHash(32, true);

    //LLamamos a la función checkpassword que recibe por parametros la ocntarseña que queremos verificar seguida de la real (en la bd)
    //Now we call the checkpassword function with two parameters 1. The password who we get and wanna verify and the hash password atcually stored on the database

    if($phpass->CheckPassword($userInputPassword, $par)){echo "El usuario existe y es esa su contraseña// The user exists and that´s his password";}
    else{ echo "El usuario existe pero la contraseña no es válida//the user exist but that isn´t his password"; }
}
?>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top