CakePHP remember me with Auth

In your user controller:

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());
}

In the login view:

<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'); ?>

In your 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
        }
    }
}

Leave a Comment