Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to implement 'Remember me' functionality in cakephp

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.24k
    Comment on it

    To implement 'Remember Me' functionality in cakephp, you need to follow following steps.

    Step1 :  Add the following code in app/Config/core.php

    Configure::write('Session', array(
    		'defaults' => 'php'
    		'defaults' => 'php',
    		'cookieTimeout' => 0
     	));

    Step2 : Add the following code in app/Controller/AppController.php

     public function beforeFilter() {
    
            $this->Auth->allow('login', 'logout','forgot','register','getCities','getStates','getData');
            $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'home');
            $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'logout', 'login');
            // $this->Auth->authorize = array('Controller');
            $this->Auth->redirectUrl(array('controller' => 'users', 'action' => 'home'));
            $this->Auth->authenticate = array(
                'Cookie' => array(
                    'fields' => array(
                         'username' => 'email',
                         'password' => 'password'
                    ),
                    'userModel' => 'User',
                ),
                'Form' =>array(
                        'passwordHasher' => 'Blowfish',
                        'fields' => array('username' => 'email')
                        ),
    
                
            );
            $this->Cookie->type('rijndael');
            $this->set('authUser', $this->Auth->user());
    
            @$cookieData = $this->Cookie->read('User');
             // echo debug($cookieData);
            if (!empty(@$cookieData))
            {   
    
    
                $this->request->data["User"]["email"] = $cookieData["User"]["email"];
                $this->request->data["User"]["password"] = $cookieData["User"]["password"];
            }
    
        }
    

     Step3 : Add the following code in app/Controller/Component/Auth/CookieAuthenticate.php

    <?php
    App::uses('BaseAuthenticate', 'Controller/Component/Auth');
    App::uses('AuthComponent', 'Controller/Component');
    App::uses('Router', 'Routing');
    
    /**
     * An authentication adapter for AuthComponent.  Provides the ability to authenticate using COOKIE
     *
     * {{{
     *  $this->Auth->authenticate = array(
     *      'Authenticate.Cookie' => array(
     *          'fields' => array(
     *              'username' => 'username',
     *              'password' => 'password'
     *          ),
     *          'userModel' => 'User',
     *          'scope' => array('User.active' => 1),
     *          'crypt' => 'rijndael', // Defaults to rijndael(safest), optionally set to 'cipher' if required
     *          'cookie' => array(
     *              'name' => 'RememberMe',
     *              'time' => '+2 weeks',
     *          )
     *      )
     *  )
     * }}}
     *
     */
    class CookieAuthenticate extends BaseAuthenticate {
    
        public function __construct(ComponentCollection $collection, $settings) {
            $this->settings['cookie'] = array(
                'name' => 'RememberMe',
                'time' => '+2 weeks',
                'base' => Router::getRequest()->base
            );
            $this->settings['crypt'] = 'rijndael';
            parent::__construct($collection, $settings);
        }
    
    /**
     * Authenticates the identity contained in the cookie.  Will use the `settings.userModel`, and `settings.fields`
     * to find COOKIE data that is used to find a matching record in the `settings.userModel`.  Will return false if
     * there is no cookie data, either username or password is missing, of if the scope conditions have not been met.
     *
     * @param CakeRequest $request The unused request object
     * @return mixed False on login failure. An array of User data on success.
     * @throws CakeException
     */
        public function getUser(CakeRequest $request) {
            if (!isset($this->_Collection->Cookie) || !$this->_Collection->Cookie instanceof CookieComponent) {
                throw new CakeException('CookieComponent is not loaded');
            }
    
            $this->_Collection->Cookie->type($this->settings['crypt']);
            list(, $model) = pluginSplit($this->settings['userModel']);
    
            $data = $this->_Collection->Cookie->read($model);
            if (empty($data)) {
                return false;
            }
    
            extract($this->settings['fields']);
            if (empty($data[$username]) || empty($data[$password])) {
                return false;
            }
    
            $user = $this->_findUser($data[$username], $data[$password]);
            if ($user) {
                $this->_Collection->Session->write(AuthComponent::$sessionKey, $user);
                return $user;
            }
            return false;
       }
    
        public function authenticate(CakeRequest $request, CakeResponse $response) {
            return $this->getUser($request);
        }
    
        public function logout($user) {
            $this->_Collection->Cookie->destroy();
        }
    
    } 

    Step4 : Add the following code in app/Controller/UsersController.php

    public function login()
    	{
    		if($this->Auth->user()){
    			$this->redirect(array('controller'=>'Users','action'=>'home'));
    		}
    		if ($this->request->is('post')) {
    			
    
    
    			if ($this->Auth->login()) {
    				$this->_setCookie($this->Auth->user('id'));
    				$this->redirect($this->Auth->redirect());
    			} else {
    				$this->Session->setFlash(' Invalid username or password ');
    			}
    		}
    		
    		if ($this->Auth->loggedIn() || $this->Auth->login()) {
    			return $this->redirect($this->Auth->redirectUrl());
    		}
    	}
    
    
       protected function _setCookie($id) {
    
    
    		if (!$this->request->data['remember_me']) {
    			return false;
    		}
    
    		$data = array(
    			'User' => array(
    				'email' => $this->request->data['User']['email'],
    				'password' => $this->request->data['User']['password']
    				));
    		
    		$this->Cookie->write('User', $data, true, '+2 week');
    		return true;
    	}

    Step5 : Add the following code in app/View/Users/login.ctp

    <?php echo $this->Form->create('User'); ?>
     	<fieldset>
     		<legend><?php echo __('Please enter your username and password'); ?></legend>
    		<?php echo $this->Form->input('username');
    		echo $this->Form->input('password');
    	?>
    		<?php
    			echo $this->Form->input('username');
    			echo $this->Form->input('password');
    			echo $this->Form->checkbox('remember_me');
    		?>
     	</fieldset>
     <?php echo $this->Form->end(__('Login')); ?>
     </div>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: