Thursday, February 16, 2012

Create admin user by code

Here is a piece of code that will allow you to create admin users. It's really useful if you forget the admin password: Create a file called adminuser.php on the same level as index.php (in the root of the application) with the following content:
<?php
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);

umask(0);
Mage::app('default');//if you changed the code for the default store view change it here also
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$username = 'yourUsername';//desired username
$firstname = "Firstname";//desired firstname
$lastname = "Lastname";//desired lastname
$email = "email@example.com";//desired email
$pass = 'yourPaSSWordHere';//desired password
$user = Mage::getModel('admin/user')->load($username, 'username');
if ($user->getId()){
 echo "User {$username} already exists";
 exit;
}
$user->setUsername($username)
  ->setFirstname($firstname)
  ->setLastname($lastname)
  ->setEmail($email)
  ->setPassword($pass)
  ;
$result = $user->validate();
if (is_array($result)){
 foreach ($result as $res){
  echo $res."\n";
 }
 exit;
}
try{
 $user->setForceNewPassword(true);
 $user->save();
 $user->setRoleIds(array(1))->saveRelations();
 echo "User {$username} was created";
 exit;
}
catch (Exception $e){
 echo $e->getMessage();
}
Now call in you browser this url www.mysite.com/adminuser.php. You should see a message on the screen with the result of your action. Cheers, Marius.

5 comments:

  1. Cant belive we can retrive password in this way!

    ReplyDelete
    Replies
    1. You cannot retrieve a password this way. Passwords are hashed and cannot be retrieved (easily). you can create a new admin account like this. And if you modify a bit the script you can modify a password. but you cannot retrieve it.

      Delete
  2. Great its working perfectly

    ReplyDelete
  3. This is awesome, thank you, worked great!!!

    ReplyDelete