I am new to CakePHP and trying to get my head round register / login, Im using cakephp 2.0
If i create a user using a register controller function and then login seperately the session ($this-Auth-user()) contains all the Model values i expect.
If i follow the cakephp 2.0 book example and manually login during the register then I do get logged in but $this->Auth->user() only contains the fields from the register form not the User Model. (ie. its missing my Model fields "created", "full name" etc but includes "password" and "passwordconfirm" both unencrypted)
Am i missing something here?
Login Action:
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid Username or Password.'), 'default', array(), 'auth');
}
}
}
Register Action (with auto login):
public function register(){
if($this->request->is('post')){
$this->User->create();
if($this->User->save($this->request->data)){
//Login automatically
if($this->Auth->login($this->data['User'])){
$this->Session->setFlash(__('Welcome to Test Site.'), 'default', array(), 'auth');
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Failed to login with new account.'), 'default', array(), 'auth');
$this->redirect(array('action' => 'login'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Register.ctp View
<?php
echo $this->Form->create('User', array('action' => 'register'));
echo $this->Form->input('username');
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->input('passwordconfirm', array('label' => 'Confirm Password', 'type' => 'password'));
echo $this->Form->input('email', array('label' => 'Email (optional)'));
echo $this->Form->end('Join');
?>
Cheers for any help guys apologies this is a bit long!
EDIT:
Found a workaround! Looks like $this->Auth->login($this->data['User']) was failing to AuthComponent::identify() my User so i changed it for the following 3 lines:
$LoggedInID = $this->User->field('id', array('username' => $this->Auth->user('username')));
$user = $this->User->read(null, $LoggedInID);
$this->Auth->login($user);
and this works a treat.
Edit: You can also just use the return value of save():
if($user = $this->User->save($this->request->data)){
//Login automatically
if($this->Auth->login($user)){