How to auto redirect user having Auto-Login cookie, using Auto-Login component in CakePHP 2x?
-
30-06-2021 - |
Frage
I am using CakePHP 2x with Auto-Login component. The problem is, I can write the stuff but, I am not sure how to implement it to read and authorize. When user arrives at the page, he still has the cookie in his browser but, how do I authorize it?
My Login script:
public function login() {
if ($this->Auth->user('id')) {
$this->redirect(array('action' => 'dashboard'));
}
if($this->request->data['User']['auto_login']):
$this->AutoLogin->write($this->request->data['User']['username'],
$this->request->data['User']['password']);
endif;
if ($this->request->is('post')) {
if ($this->Auth->login( )) {
//$this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
return $this->redirect($this->Auth->redirect( ));
}
else
{
$this->Session->setFlash(__('Username or Password is incorrect'), 'default', array( ), 'auth');
}
}
Lösung
This should be something like:
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
if ($this->request->data['User']['persist'] == '1')
{
$cookie = array();
$cookie['username'] = $this->data['User']['USER_LOGINNAME'];
$cookie['password'] = $this->data['User']['USER_PASSWORD'];
$this->Cookie->write('Auth.User', $cookie, true, '+4 weeks');
}
$this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash('Your username or password was incorrect.', 'default/flash-error');
}
}
else
{
$user = $this->Auth->user();
if (empty($user))
{
$cookie = $this->Cookie->read('Auth.User');
if (!is_null($cookie))
{
$user = $this->User->find('first', array('conditions' => array('USER_LOGINNAME' => $cookie['username'], 'USER_PASSWORD' => AuthComponent::password($cookie['password']))));
if ($this->Auth->login($user['User']))
{
$this->Session->delete('Message.auth');
$this->redirect($this->Auth->redirect());
}
else
{
$this->Cookie->delete('Auth.User');
}
}
}
else
{
$this->redirect($this->Auth->redirect());
}
}
}
This gives you the idea of how to achieve the same task, however, I used form fields according to my DB Structure.
Kindly change the form fields according to your DB Structure.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow