CakePHP: Creating a Custom Shell for Adding Users for Use With AuthComponent

Posted on 31 July 2008 by Johannes Fahrenkrug. Tags: Programming Tutorials php
I'm cursed with having to use PHP for a current small project. I hate PHP, but with CakePHP it's not too bad. I did a little write-up on creating a custom CakePHP shell for adding users with AuthComponent (it's not published yet, so you might not be able to view it). Here it is: AuthComponent is great and there are tutorials for letting users register an account. But what if you just want a convenient way to add a few admin users? This custom shell will help you! The AuthComponent guide at is very useful. Read it. I have a simple admin tool that uses AuthComponent. I also want a convenient way to create admin users, though and I surely don't want to allow everyone to register their own admin account. So I wrote a custom shell. This shell assumes that you have a User model like this: Model Class:
class User extends AppModel { 
    var $name = 'User'; 
It should be backed by a database table named 'users' with this layout:
CREATE TABLE users (    
  id integer auto_increment,     
  username char(50),     
  password char(50),     
To create users, put this custom shell code into the file app/vendors/shells/create_user.php:
class CreateUserShell extends Shell { 
    var $uses = array('User'); 

    function main() { 
        $this->Auth = new AuthComponent(null); 
        $this->out('Create Admin User:'); 
        while (empty($username)) { 
          $username = $this->in('Username:'); 
          if (empty($username)) $this->out('Username must not be empty!'); 
        while (empty($pwd1)) { 
          $pwd1 = $this->in('Password:'); 
          if (empty($pwd1)) $this->out('Password must not be empty!'); 
        while (empty($pwd2)) { 
          $pwd2 = $this->in('Password Confirmation:'); 
          if ($pwd1 !== $pwd2) { 
            $this->out('Passwort and confirmation do not match!'); 
            $pwd2 = NULL; 
        // we got all the data, let's create the user         
              if ($this->User->save(array('username' => $username, 'password' => $this->Auth->password($pwd1)))) { 
                  $this->out('Admin User created successfully!'); 
              } else { 
                  $this->out('ERROR while creating the Admin User!!!'); 
That's it, now you can run your spiffy new shell script like so:
cake/console/cake create_user


Johannes Fahrenkrug said...

Hey Tom,

Thank you for your kind feedback! I'm glad it was helpful for you :)

January 27, 2009 06:45 AM

Tom said...

You probably just saved me a good deal of time learning CakePhp shells so that I could accomplish just this -- and provided an excellent simple example of a cake shell script in the bargain. Thanks!

January 27, 2009 03:38 AM


Please keep it clean, everybody. Comments with profanity will be deleted.

blog comments powered by Disqus