CakePHP记得我跟Auth
发布时间:2020-05-25 09:35:27 所属栏目:PHP 来源:互联网
导读:我已经成功地使用了Auth,但不幸的是,它似乎只能在Session中工作.我想要,如果用户检查“记住我”复选框,我将使用Cookie,他将被登录2周.我在官方的书籍中找不到任何东西,而在Google中我发现只是几个而不是很好的博客文章.有没有办法实现这个而不重写核心? 在您
|
我已经成功地使用了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
}
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
