簡體   English   中英

cakephp 2記住我自動登錄

[英]cakephp 2 remember me auto-login

我正在嘗試進行設置,以便當用戶登錄時有一個“記住我”復選框,如果選中該復選框,則會寫入一個cookie以記住該用戶的電子郵件和密碼。 在我的用戶控制器登錄功能中是這樣的:

public function login() {
    if (!empty($this->data)) {
        if ($this->Auth->login()) {
            $userId = $this->Auth->user('id');
            if(!empty($this->data['User']['remember'])) {
                $user = $this->User->find('first', array('conditions'=>array('id'=>$userId), 'recursive'=>-1, 'fields'=>array('email', 'password')));
                $this->Cookie->write('User', $user['User']);
            }
... etc etc ...

在cakephp 1.x中,我已經完成了這項工作,因此在AppController的beforefilter中,我只是尋找cookie並嘗試這樣登錄:

//try to auto login a users
    if($this->Auth->user() == null) {
        $user = $this->Cookie->read('User');
        if(!empty($user)) {
            $this->Auth->login($user);
        }
    }

但這似乎現在不起作用。 我認為是因為從我閱讀的內容來看,如果您將任何內容傳遞給登錄功能,它將返回true。 而不是正確登錄,我需要發布該cookie的內容才能登錄功能...

那正確嗎? 是否有比嘗試在某處創建表單更簡單的方法,並通過大量重定向使其發布信息?

我也嘗試將cookie信息添加到$ this-> request-> data數組中,並嘗試登錄,但這既不起作用:(

//try to auto login a users
if($this->Auth->user() == null) {
    $user = $this->Cookie->read('User');
        if(!empty($user)) {
            $this->request->data['User']['email'] = $user['email'];
            $this->request->data['User']['password'] = $user['password'];
            $this->Auth->login();
        }
    }

誰能幫我嗎? 必須有一個更簡單的方法來做到這一點!

嘗試這個..

將此復選框保留在登錄ctp文件中

 <php echo $this->Form->checkbox('remember_me',array("id" => "id_remember_me",'name'=>'remember_me','label' => false)); ?>
 <span onclick="$('#id_remember_me').attr('checked',true);"><?php echo __('Remember my details')?></span>

然后保持這個

code in the controller where the $this->Auth->login() is..
     //Setting up the expiry time
     $year = time() + 31536000;
     if($this->request->data['remember_me']) {
     // Creating a cookie in the name of remember_me with the username for the time which was set
          setcookie('remember_me', $this->request->data['User']['username'], $year);
     }
     else if(!$this->request->data['remember_me']) {
         if(isset($_COOKIE['remember_me'])) {
              $past = time() - 100;
              setcookie('remember_me', 'gone', $past);
         }
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM