0

I built a component where a user fills in a form, and on submit it creates an account for them and tries to log them in immediately. The account creation works, but when it tries to log users in, I get the error Invalid password.

Here is the core the function:

$app = JFactory::getApplication();

$user = new JUser;
$user->bind($data);
if (!$user->save()) {
    $this->setError($user->getError());
    return false;
}

$credentials = array(
    'username' => $user->username,
    'password' => $user->password_clear,
);
$app->login($credentials);

I'm not entirely sure what I'm missing. When I do a print_r of all of the data I have, it's all correct. If I log in manually after getting the wrong password error, I log in correctly. I tried passing $user->password instead, but that didn't work either. If I modified index.php to do the exact same $app->login, it would log me in properly.

Clearly there's something I'm missing, but I just can't find it.

1

I wrote a wee module based on your code above and it worked ok. Here's my code for comparison. (I set URL params like ?newusr=fredc&newpwd=fredc)

use Joomla\CMS\Factory;

$app = Factory::getApplication();   // equivalent of $app = JFactory::getApplication();
$input = $app->input;

if ($input->exists('newusr') && $input->exists('newpwd'))
{
    $usr = $input->get('newusr', 0, "STRING");  
    $pwd = $input->get('newpwd', 0, "STRING");

    $logged_on_user = JFactory::getUser();
    echo "Logged on user is " . $logged_on_user->username; 

    $user = new JUser();
    $data = array("name" => $usr, "username" => $usr, "email" => $usr . "@example.com", "password" => $pwd, "password_clear" => $pwd, "groups" => array("2"));
    $user->bind($data);
    if (!$user->save()) {
        $this->setError($user->getError());
        return false;
    }

    $credentials = array(
        'username' => $user->username,
        'password' => $user->password_clear,
    );
    $app->login($credentials);

    $logged_on_user = JFactory::getUser();
    echo "Logged on user is " . $logged_on_user->username; 
}

The second call to getUser() got the new user ok, and then the username was output ok.

  • My original code only had password being bound to user, because the bind event properly encrypted it for me. But, for whatever reason when I have both password and password_clear bound like your example, it just works. I don't understand why, but if it works I guess I'll just let it go for now. – Chaosxmk Dec 11 '19 at 18:44
  • I removed the password_clear element from the $data array and it still worked ok. So I think it's actually not needed. – Robbie Jackson Dec 11 '19 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.