Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Forget password in cakephp

    • 0
    • 0
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 434
    Comment on it

    Hello Reader's!,If you want to add forgot password field in your login page and send the forgot password link through mail Then I wrote this blog for you.

    // first create a forgot password link in your login page and allow forgot password page access before login

    <?php echo $this->Html->link('Forgot Password',array('controller'=>'Users','action'=>'forgetpwd'));?>

    // Gives the page access in controller before doing Anywork
     

    parent::beforeFilter();
    $this->Auth->allow('forgetpwd','reset');

    // create forgotpwd.ctp in /view/Users/forgotpwd.ctp

    <div class="forgetpwd form" style="margin:5px auto 5px auto;width:450px;">
    <?php echo $this->Form->create('User', array('action' => 'forgetpwd')); ?>
    <?php echo $this->Form->input('email',array('style'=>'float:left'));?>
    <input type="submit" class="button" style="float:left;margin-left:3px;" value="Recover" />
    <?php echo $this->Form->end();?>
    </div>
    //set the smtp setting for sending email  in config/email.php copy below code as default
    
    public $default = array(
    		'transport' => 'Smtp',
    		'from' => array('noreply@ishake.com' => 'Login Reset'),
    		'host' => 'ssl://smtp.gmail.com',
    		'port' => 465,
    		'timeout' => 30,
    		'username' => 'gmail_id',
    		'password' => 'Password',
    		'client' => null,
    		'log' => false,
    		'emailFormat' => 'html',
    		'charset' => 'utf-8',
    		'headerCharset' => 'utf-8',
    	);
    //App Controller Function for set the mail in appcontroller
    
     public function send_mail($email_data = null)
        {
            $email         = new CakeEmail('default');
            $email_to      = $email_data['to'];
            $email_msg     = $email_data['body'];
            $email_subject = $email_data['subject'];
            
            $email->to($email_to);
            $email->subject($email_subject);
            $mail_status = @$email->send($email_msg);
         
            if (!$mail_status) {
                return FALSE;
            }
            return TRUE;
        }
    

     

    //Add Tokenhash field in user table

     

    //create the function which create the token for user and save it in user table for varification user email id	
    public function forgetpwd()
    {
    		$this->User->recursive=-1;
    		if(!empty($this->data))
    		{
    			if(empty($this->data['User']['email']))
    			{
    				$this->Session->setFlash('Please Provide Your Email Adress that You used to Register with Us');
    			}
    			else
    			{
    				$email=$this->data['User']['email'];
    				$fu = $this->User->find('first', array('conditions' => array('User.email' => $email)));
    										
    				if($fu)
    				{
    					
    					if($fu['User']['user_status']=='1')
    					{
    						$key = Security::hash(CakeText::uuid(),'sha512',true);
    						$hash=sha1($fu['User']['username'].rand(0,100));
    						$url = Router::url( array('controller'=>'Users','action'=>'reset'), true ).'/'.$key.'#'.$hash;
    						$ms=$url;
    						
    						
    						
    						$ms=wordwrap($ms,1000);
    						
    						$fu['User']['tokenhash']=$key;
    						$this->User->id=$fu['User']['id'];
    				
    						
    						if($this->User->saveField('tokenhash',$fu['User']['tokenhash']))
    						{						
    						
    						$this->set('ms', $ms);	
    																		
    						$data = array();
    						
    						$data['to'] = $fu['User']['email'];
    						$data['subject'] = 'Reset Password';
    						$data['body'] =$ms;
    						$output =$this->send_mail($data); 
    //This is a function in appcontroller which send the mail to registerd user (see below this function)
    							if($output){
    								$this->Session->setFlash('Check Your Mail Id for Reset Your password');
    								$this->redirect(array('controller'=>'users','action'=>'login'));
    							}																								
    						}
    						else{
    							$this->Session->setFlash("Error Generating Reset link");
    						}
    					}
    					else
    					{
    						$this->Session->setFlash('This Account is not Active yet.Check Your mail to activate it');
    					}
    				}
    				else
    				{
    					$this->Session->setFlash('Email does Not Exist');
    				}
    			}
    		}	
    }
    

     

    //now create Reset Password Code which get user token and validate befor updation

    public function reset($token=null)
    {
    			
    		$this->User->recursive=-1;
    		if(!empty($token))
    		{
    			$u=$this->User->findBytokenhash($token);
    			if(!empty($u))
    			{
    				$this->User->id=$u['User']['id'];		
    				
    				if(!empty($this->data))
    				{	 
    					$this->User->data=$this->data;
    					$this->User->data['User']['username']=$u['User']['username'];
    					$new_hash=sha1($u['User']['username'].rand(0,100));//created token
    						
    					$this->User->data['User']['tokenhash']=$new_hash;
    					
    					if($this->User->validates(array('fieldList' => array('password', 'password_confirm'))))
    					{
    																						
    						if($this->User->save($this->User->data))
    						{
    							$this->Session->setFlash('Password Has been Updated');
    							$this->redirect(array('controller'=>'users','action'=>'login'));
    						}
    
    					}
    					else{
    
    						$this->set('errors',$this->User->invalidFields());
    						}
    				}
    			}
    			else
    			{
    				$this->Session->setFlash('Token Corrupted,,Please Retry.the reset link work only for once.');
    			}
    		}
    
    		else
    		{
    			$this->Session->setFlash('Invalid Token,Try Again');
    			$this->redirect(array('controller'=>'users','action'=>'login'));
    		}
    	
    }
    
    

     

     

    Hope this will be helpful for you!!! Contact me if there is any problem:)

     

 3 Comment(s)

  • Hi, i tried to use your code, but when i clicked the generated link i got this error message: Notice (1024): Element Not Found: Elements/Flash/auth_error.ctp [CORE/Cake/View/View.php, line 425]. Any ideas?

    I already solved it (i forgot to add the reset method in before_filter)! Thank you so much.

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: