如何使用CakePHP 2x中的自动登录组件自动重定向具有自动登录cookie的用户?

时间:2012-09-06 10:09:01

标签: php cakephp cakephp-2.1 remember-me autologin

我正在使用CakePHP 2x和自动登录组件。问题是,我可以编写这些东西但是,我不知道如何实现它来阅读和授权。当用户到达页面时,他仍然在浏览器中有cookie但是,我该如何授权呢?

我的登录脚本:

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');
            }
        }

1 个答案:

答案 0 :(得分:1)

这应该是这样的:

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());
        }
    }
}

这让您了解如何实现相同的任务,但是,我根据我的数据库结构使用了表单字段。

请根据您的数据库结构更改表单字段。