微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/php/140193.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐