2

I'm developing my website in cakephp 3.x. In that I want remember me functionality for login the user.

I have done lots of seraching(R&D) on google but I can't found anything helpful for me. I have tried to apply CakePHP remember me with Auth

But it doesnot helped me.

I have username as email & password as password field in my database.

If anyone has any idea then please share it with me.

My login function :

    $user = $this->Auth->identify();
    if ($user) {
        $this->Auth->setUser($user);


        if ($this->request->data['rememberMe'] == "on") {

            $cookie = array();
            $cookie['username'] = $this->request->data['email'];
            $cookie['password'] = $this->request->data['password'];
            $this->Cookie->write('rememberMe', $cookie, true, "1 week");
            unset($this->request->data['rememberMe']);
        }

        if (empty($this->data)) {
            $cookie = $this->Cookie->read('rememberMe');
            if (!is_null($cookie)) {
                $user = $this->Auth->identify();
                if ($user) {
                    $this->redirect($this->Auth->redirectUrl());
                } else {
                    $this->Cookie->destroy('rememberMe'); # delete invalid cookie

                    $this->Session->setFlash('Invalid cookie');
                    $this->redirect('login');
                }
            }
        }


        return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Flash->set('Invalid username or password, try again', ['element' => 'error']);
}
Community
  • 1
  • 1
Pratik Patel
  • 131
  • 1
  • 3
  • 12

2 Answers2

4

The easiest way of coding a remember-me cookie is using this Authenticate adapter from this plugin:

https://github.com/FriendsOfCake/authenticate/tree/cake3#cookieauthenticate

  • Storing a username and password for session cookies in insecure. See http://stackoverflow.com/questions/244882/what-is-the-best-way-to-implement-remember-me-for-a-website An alternative is https://github.com/Beskhue/CookieTokenAuth – Thomas Apr 13 '16 at 01:20
2

After

if (!is_null($cookie)) {

Add

$this->request->data = $cookie;

That should work.

The Auth component is using $this->request->data to do the authentication. Once you add the cookie data identify() should work. I'm using similar code on my site with no issues.

  • This worked but it also needs to add after `if ($user) {` add `$this->Auth->setUser($user);` again. – Zordon Jun 08 '15 at 14:07