CakePHP记得我跟Auth

前端之家收集整理的这篇文章主要介绍了CakePHP记得我跟Auth前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经成功地使用了Auth,但不幸的是,它似乎只能在Session中工作.我想要,如果用户检查“记住我”复选框,我将使用Cookie,他将被登录2周.我在官方的书籍中找不到任何东西,而在Google中我发现只是几个而不是很好的博客文章.有没有办法实现这个而不重写核心?
在您的用户控制器中:
  1. public function beforeFilter() {
  2. $this->Auth->allow(array('login','register'));
  3. parent::beforeFilter();
  4. }
  5.  
  6. public function login() {
  7. if ($this->request->is('post')) {
  8.  
  9. if ($this->Auth->login()) {
  10.  
  11. // did they select the remember me checkBox?
  12. if ($this->request->data['User']['remember_me'] == 1) {
  13. // remove "remember me checkBox"
  14. unset($this->request->data['User']['remember_me']);
  15.  
  16. // hash the user's password
  17. $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
  18.  
  19. // write the cookie
  20. $this->Cookie->write('remember_me_cookie',$this->request->data['User'],true,'2 weeks');
  21. }
  22.  
  23. return $this->redirect($this->Auth->redirect());
  24.  
  25. } else {
  26. $this->Session->setFlash(__('Username or password is incorrect.'));
  27. }
  28. }
  29.  
  30. $this->set(array(
  31. 'title_for_layout' => 'Login'
  32. ));
  33. }
  34.  
  35. public function logout() {
  36. // clear the cookie (if it exists) when logging out
  37. $this->Cookie->delete('remember_me_cookie');
  38.  
  39. return $this->redirect($this->Auth->logout());
  40. }

登录视图中:

  1. <h1>Login</h1>
  2.  
  3. <?PHP echo $this->Form->create('User'); ?>
  4. <?PHP echo $this->Form->input('username'); ?>
  5. <?PHP echo $this->Form->input('password'); ?>
  6. <?PHP echo $this->Form->checkBox('remember_me'); ?> Remember Me
  7. <?PHP echo $this->Form->end('Login'); ?>

在您的AppController中:

  1. public $components = array(
  2. 'Session','Auth','Cookie'
  3. );
  4.  
  5. public $uses = array('User');
  6.  
  7. public function beforeFilter() {
  8. // set cookie options
  9. $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
  10. $this->Cookie->httpOnly = true;
  11.  
  12. if (!$this->Auth->loggedIn() && $this->Cookie->read('remember_me_cookie')) {
  13. $cookie = $this->Cookie->read('remember_me_cookie');
  14.  
  15. $user = $this->User->find('first',array(
  16. 'conditions' => array(
  17. 'User.username' => $cookie['username'],'User.password' => $cookie['password']
  18. )
  19. ));
  20.  
  21. if ($user && !$this->Auth->login($user['User'])) {
  22. $this->redirect('/users/logout'); // destroy session & cookie
  23. }
  24. }
  25. }

猜你在找的PHP相关文章