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 http://manual.cakephp.org/view/172/authentication 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:
<?php
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), PRIMARY KEY (id) );
To create users, put this custom shell code into the file app/vendors/shells/create_user.php:
<?php
class CreateUserShell extends Shell {
var $uses = array('User');
function main() {
App::import('Component','Auth');
$this->Auth = new AuthComponent(null);
$this->out('Create Admin User:');
$this->hr();
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
$this->User->create();
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
Enjoy!
Comments
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
Johannes Fahrenkrug said...
Hey Tom,
January 27, 2009 06:45 AMThank you for your kind feedback! I'm glad it was helpful for you :)