CakePHP记得我跟Auth

前端之家收集整理的这篇文章主要介绍了CakePHP记得我跟Auth前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经成功地使用了Auth,但不幸的是,它似乎只能在Session中工作.我想要,如果用户检查“记住我”复选框,我将使用Cookie,他将被登录2周.我在官方的书籍中找不到任何东西,而在Google中我发现只是几个而不是很好的博客文章.有没有办法实现这个而不重写核心?
在您的用户控制器中:
public function beforeFilter() {
    $this->Auth->allow(array('login','register'));
    parent::beforeFilter();
}

public function login() {
    if ($this->request->is('post')) {

        if ($this->Auth->login()) {

            // did they select the remember me checkBox?
            if ($this->request->data['User']['remember_me'] == 1) {
                // remove "remember me checkBox"
                unset($this->request->data['User']['remember_me']);

                // hash the user's password
                $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);

                // write the cookie
                $this->Cookie->write('remember_me_cookie',$this->request->data['User'],true,'2 weeks');
            }

            return $this->redirect($this->Auth->redirect());

        } else {
            $this->Session->setFlash(__('Username or password is incorrect.'));
        }
    }

    $this->set(array(
        'title_for_layout' => 'Login'
    ));
}

public function logout() {
    // clear the cookie (if it exists) when logging out
    $this->Cookie->delete('remember_me_cookie');

    return $this->redirect($this->Auth->logout());
}

登录视图中:

<h1>Login</h1>

<?PHP echo $this->Form->create('User'); ?>
    <?PHP echo $this->Form->input('username'); ?>
    <?PHP echo $this->Form->input('password'); ?>
    <?PHP echo $this->Form->checkBox('remember_me'); ?> Remember Me
<?PHP echo $this->Form->end('Login'); ?>

在您的AppController中:

public $components = array(
    'Session','Auth','Cookie'
);

public $uses = array('User');

public function beforeFilter() {
    // set cookie options
    $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
    $this->Cookie->httpOnly = true;

    if (!$this->Auth->loggedIn() && $this->Cookie->read('remember_me_cookie')) {
        $cookie = $this->Cookie->read('remember_me_cookie');

        $user = $this->User->find('first',array(
            'conditions' => array(
                'User.username' => $cookie['username'],'User.password' => $cookie['password']
            )
        ));

        if ($user && !$this->Auth->login($user['User'])) {
            $this->redirect('/users/logout'); // destroy session & cookie
        }
    }
}
原文链接:https://www.f2er.com/php/140193.html

猜你在找的PHP相关文章