Search code examples
phpzend-frameworkzend-formzend-db

PHP login user automatically after email verification


I'm using PHP Zend framework for my web application. When users register, I send them an email to verify their email address and when they click on that link - the account is activated.

My problem - when users click on the activate link - I also want to automatically log them in - rather than asking them to login in again. I'm not sure how to do that.

This is my login action in Zend which requires email address and password. So what should I send as part of the activation link so that when the user clicks on it, they are automatically logged in.

    $db = Zend_Db_Table::getDefaultAdapter();
    //create the auth adapter
    $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'user','email', 'password');
    //set the username and password
    $authAdapter->setIdentity($this->_getParam('email'));
    $authAdapter->setCredential(md5($this->_getParam('password')));


    //authenticate
    $result = $authAdapter->authenticate();

    if ($result->isValid()) {           
        $auth = Zend_Auth::getInstance();
        $storage = $auth->getStorage();

        $row = $authAdapter->getResultRowObject(array('user_id'));
        $userModel = new Model_User();
        $user = $userModel->loadUserProfile($row->user_id);
        $storage->write($user);
    }

Thanks for your help


Solution

  • You have an if statement to authenticate a username and password. In the case of someone validating their email you are mimicking this process and enabling a user to authenticate their account via an email and verification key.

    All you need to do is verify the email and verification are correct and place this conditional underneath:

       .
       .
       .
       $verified = $emailVerification->isValid( $email, $key );
    
        if ( $verified ) 
        {           
                $auth = Zend_Auth::getInstance();
                $storage = $auth->getStorage();
    
                $row = $authAdapter->getResultRowObject(array('user_id'));
                $userModel = new Model_User();
                $user = $userModel->loadUserProfile($row->user_id);
                $storage->write($user);
        }
    

    The user will then be logged in as you have saved their User details to the Zend_Auth storage engine.

    I'd advise after using this method remove the verification key from the user record to ensure they cannot login via this process again, unless they forget their password, in whcih case you assign a new verification key.

    Hope this helps!