Search code examples
phpemailzend-framework2tokenverification

Zend Framework 2 email token verification


I am trying to make a system (in Zend Framework 2) to validate a user registration's email by sending an email with a link with a token (for example: http://example.com/user/autenticate/verify/abG12Fdss67j3kgfdds4jdpa74FiP9) so if the token is found in the database the pre-registered account moves to VERIFIED status.

I am using a route in module.config.php like this:

'verify' => array(
            'type'    => 'Segment',
            'options' => array(
                'route'    => '/user/autenticate/verify/:token',
                'defaults' => array(
                    '__NAMESPACE__' => 'User\Controller',
                    'controller'    => 'Autenticate',
                    'action'        => 'verify',
                ),
                    'constraints' => array(
                    'token' => '[a-zA-Z0-9]{30}'
                ),
            ),
        ),

then in AutenticateController.php, the following action method:

public function verifyAction()
{
    sleep(3); // Delay against brute attack (is it useful?)
    $token = $this->params()->fromRoute('token');
    $registerverification = new RegisterVerification();

    try {
        $registerverification = $this->getRegisterVerificationTable()->getRegisterVerification($token);

        // If arrives here (no exception) means that the token was in the database
        $aux = $this->getRegisterVerificationTable()->deleteRegisterVerification($token);
        $user = new User();
        $user = $this->getUserTable()->getUser((int)$registerverification->id);
        $user->verified = date("Y-m-d H:i:s");
        $this->getUserTable()->saveUser($user);

        $this->flashMessenger()->addMessage("Now your account is active");
    } catch (\Exception $e) { // Could not find row: $token

        $this->flashMessenger()->addMessage($e->getMessage()); 
    }
    return array();
}

And a verify.phtml like this:

<?php
echo $this->flashMessenger()->render();
?>

This is working, but not on the first attempt, but only after refreshing the URL (http://example.com/user/autenticate/verify/abG12Fdss67j3kgfdds4jdpa74FiP9).

Can anyone help me on what do I have to do to make the method verifyAction() of AutenticateController.php being executed the first time the URL is called?


Solution

  • The flash messenger is designed to show messages on the next request, so you probably want to redirect to another URL after adding your success message. That may be the only issue (otherwise please let us know what happens on the first request).