Search code examples
phpcakephpuser-registration

Unique username and email with CakePHP Auth component


I'm new to Cake and building an application to learn it. I'm having a few troubles with my user registration system. So far this is my registration code in my Users controller:

public function register() {
    $this->set('title_for_layout', 'Register');
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash('The user has been saved');
            $this->redirect(array('action' => 'register'));
        } else {
            $this->Session->setFlash('The user could not be saved. Please, try again.');
        }
    }
}

And within my User model I have this method where I hash the passwords:

public function beforeSave() {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

This works, the user is added to my users table in my database with their username, email and hashed password. However, there are no checks done to make sure the username and email are unique.

From my limited understanding, I would need to add some validation rules to my User model to make sure the username and email fields are unique before they're entered into the table? At the moment I just have these validation rules:

public $validate = array(
    'username' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A username is required'
        )
    ),
    'email' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'An email is required'
        )
    ),
    'password' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A password is required'
        )
    )
);

Also, my registration form has a Password (confirm) field called passwordConf. I would like to check if the user entered his passwords correctly before they're entered into the users table, but I'm not sure how to do that. I'm guessing that somewhere in my register method I need to check if the two passwords are the same.

Thanks for any help.


Solution

  • CakePHP actually has a validation rule called isUnique, which you can use to check the username and e-mail. A list of built in rules can be found here. You can use this and the Data Validation Tutorial to check the user name and e-mail. As to checking if the passwords are the same, you MAY be able to use the EqualTo rule shown in the rules list, assuming you can make your validation rules on the fly every request.