Free Android CakePHP GMaps Articles by Bali Web Design

May 31, 2012

Remember me with manual Login are not work cakephp 2

Filed under: cakephp — admin @ 9:15 pm

I have been code a day to fix problem on manual login cakephp 2. I try to redesign my cms using the latest cakephp 2 version, which in my opinion are great improve especially for the performance of framework. However there are many thing are make me confusing and a bit frustating.

I have use the magic of login Auth function, which is fast to build a login form. However on certain condition we still need manual login using user parameter on the function. For example when coding for auto login using remember me function. The user data are save on cookie when remember me selected.

This function are nice when we want the user to have option to save their login data for certain period. In this scenario, as long the cookie data available on their browser cache, they will automatically login when opening the site. It is convenient for user because they don’t need to login everytime they open the site.

My remember me function work like this. Here are the code on login function user controllers.


function login() {
if ($this->Auth->user('id')) {
$this->Session->setFlash('You are logged in!');
$this->redirect($this->Auth->redirect());
} else {
$cookie = $this->Cookie->read('User');
$user = $this->User->login($cookie['username'], $cookie['password']); // my function to retrieve user data record
if($user) {
$this->Auth->login($user['User']); // this is important, we cannot user $user, but must mention $user['User']
$this->redirect($this->Auth->redirect());
}
}

if ($this->request->isPost()) {
$user = $this->User->login($this->request->data['User']['username'], $this->request->data['User']['password']);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
if ($this->Auth->login()) {
if (empty($this->request->data['User']['remember'])) {
$this->Cookie->delete($var_name .'User');
} else {
$cookie = array();
$cookie['username'] = $this->request->data['User']['username'];
$cookie['password'] = $this->request->data['User']['password'];
$this->Cookie->write('User', $cookie, true, '+2 weeks');
}
$this->redirect($this->Auth->redirect());
}
}
}

The important thing of this code are when we executing manual login with user parameter $this->Auth->login($user[‘User’]); we must pass $user[‘User’] not only $user. I don’t know why but it is solved my manual login problem with remember me function. It was so frustated. I hope this work for you too


No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment