I have the below in my users_controller because there is further logic needed to perform the login, however when done in CakePHP the default validation stops and therefore i am trying to force it to validate the username and password fields before doing the account check. Everything works fine but this. I have tried adding two if statements (below) to check if username/password is empty, however as soon as the page loads they are empty and the validation box shows.
I am stumped as to how to achieve this. Any help would be greatly appreciated.
function login() {
if($this->Auth->user()) {
$this->redirect(array('controller'=>'shows'));
}
if(empty($this->data['User']['username'])) {
$this->User->validationErrors['username'] = "Please enter a username";
}
if(empty($this->data['User']['password'])) {
$this->User->validationErrors['password'] = "Please enter a password";
}
if(!empty($this->data['User']['username'])) {
// unset unrequired validation rules
unset($this->User->validate['username']['unique']);
// validate form
$this->User->set($this->data);
if($this->User->validates()) {
// update Last Login date
$this->User->id = $this->User->_user['User']['id'];
$this->User->saveField('last_login',date("Y-m-d H:i:s"));
// save User to Session and redirect
$this->Session->write('User', $this->User->_user);
$this->Session->setFlash('You have successfully logged in.','default',array('class'=>'flash_green'));
//$this->redirect(array('controller'=>'shows', 'admin'=>FALSE));
} else {
$this->Session->setFlash('Incorrect username/password combination.','default',array('class'=>'flash_red'));
$this->redirect(array('controller'=>'users', 'action'=>'login', 'admin'=>FALSE));
}
}
}
users_controller beforeFilter()
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('register');
}
app_controller beforeFilter and components
var $components = array('Session', 'Auth' => array(
'loginAction' => array('controller'=>'users','action'=>'login', 'admin'=>false),
//'logoutRedirect' => array('controller'=>'users','action'=>'logout'),
'loginRedirect' => array('controller'=>'shows', 'action'=>'index'),
'autoRedirect' => false,
'authorize' => 'controller')
);
function beforeFilter() {
$this->Auth->allow('home');
$this->set('admin', $this->_isAdmin());
$this->set('logged_in', $this->_loggedIn());
$this->set('users_username', $this->_usersUsername());
}
Remove the below code from the user_controller.php file.
This is looping the page back to the login action with no data and therefore no validation.