1

I am trying to create a new SuperAdmin via JUser:

    $user = new \JUser(0);
    $user->set('password',\JUserHelper::hashPassword($password));
    $user->set('username','administrator');
    $user->set('groups',array(8));
    $user->groups = array(8);
    $user->save();

Is this the right way? Or should i try another way?

  • What ever you do, please be very careful creating a super user programatically. You make 1 single mistake in the rest of your code and you can say good bye to your site. Personally I'd suggest creating a registered user and performing some two factor authentication to change the user's group to super user – Lodder Sep 23 '17 at 11:03
2

You forgot the email but apart from that it'd probably work. You shouldn't set the groups property directly, the setter right above it is fine. Also I would suggest using the getInstance method of juser rather than newing up manually. Also you should catch errors in case there's a duplicate email or something. There is also a chance that the usergroups have been messed with, eg if this was for a distributed component, but if you know the superuser is still id 8 then it's fine.

$user = \JUser::getInstance();
$user->set('id',0);
$user->set('password',\JUserHelper::hashPassword($password));
$user->set('username',$username);
$user->set('email', $email);
$user->set('usertype', 'deprecated');
$user->set('groups',array(8));
if (!$user->save()) {
    $error = $user->getError();
}

Here is the API reference for anyone reading this: https://api.joomla.org/cms-3/classes/JUser.html

| improve this answer | |

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.