Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Forgot Password And Reset Password In CakePHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.92k
    Comment on it

    Forgot password functionality we usually on the login page of many website.

    It is used when we we forgot our password and want to recover it.

    In this blog we are going to recover it by sending an email to the registered email with user account.

    we need two function for it one is forgetpwd() and the other to reset the password reset().

    other thing we use is obviously the two ctp files for the same.

    And a field in the database tokenhash to store the token that we are going to attach in the url we will be sending to the user.

    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'];
    //Check if the Email exist				$fu=$this->User->find('first',array('conditions'=>array('User.email'=>$email)));
    
    				if(!empty($fu))
    				{
    				//create a unique key and hashing it only for on time use.
    					$key = uniqid();
    					$hash = md5($key);
                                    //create the url with the reset function
    					$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'])){
    
    							//============Email================//
    						
    						$Email = new CakeEmail();
    						$Email->config('smtp')
    							
    						->template ('resetpw')
    						->from     ('ishan.bhatnagar@evontech.com')
    						->to       ($fu['User']['email'])
    						->subject  ('Reset Your Example.com Password')
    						->emailFormat  ('html')
    						->viewVars  (array('ms' => $value));
    						
    						if ($Email->send()) {
    						
    						
    						$this->Session->setFlash(__('Check Your Email To Reset your password', true));
    
    							//============EndEmail=============//
    					}
    					else{
    						$this->Session->setFlash("Error Generating Reset link");
    					}
    
    
    				}
    				
    			}
    			else
    				{
    					$this->Session->setFlash('Email does Not Exist');
    				}
    		}
    	}
    }

    In this function we first check the email that is entered is registered with us or not by checking it in the database.

    If it exist than we create a unique if and than hash it using md5 function and add it to the url that contain the reset function.

    this url is send using the CakeEmail().

    You can also send using directly php email.

    For sending the email we have to create the html file in the View/Email/html and View/Email/text

    This is the code foe the same

    <html>
    <p>Click on the link below to Reset Your Password </p><br/>
    
    <a href="<?php echo $ms; ?>">Click here to Reset Your Password</a><br/>
    
    <pre>or Visit this Link</pre><br/>
    
    <p><a href="<?php echo $ms; ?>"><?php echo $ms; ?></a></p>
    </html>

    This is the one time url that will expire after you click on it.

    Now we go to the reset password.

    function reset($token=null)
    	{
    		
    		$this->User->recursive=-1;
    		if(!empty($token)){
    			$u=$this->User->findBytokenhash($token);
    			if($u){
    				$this->User->id=$u['User']['id'];
    				if(!empty($this->data)){
    					$this->User->data=$this->data;
    					$this->User->data['User']['email']=$u['User']['email'];
    					$new_hash=sha1($u['User']['email'].rand(0,100));//created token
    					$this->User->data['User']['tokenhash']=$new_hash;
    					$this->User->data['User']['password'] = AuthComponent::password($this->request->data["User"]["password"]);
    
    					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->redirect('/');
    		}
    	}

    In this the tokenhash field in the table is updated.

    and the password is reset after validating the confirm password.

    There you go you have reset the new password and can login with that.

    Everytime you generate tokenhash it will be updated for the security purpose.

 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: