Performing authentication in custom validator in ZF

Although, this is not a good approach to use more than one value in Zend_Validate, but it may be useful sometimes if you want to write your custom validator and add it to let’s say password field and use it as other validators in Zend_Form. So

        $password->setRequired(true)
                 ->setLabel('Password')
                 ->addFilter(new Zend_Filter_StringTrim())
                 ->addValidator(new My_Custom_Password_Validator());

we added it to password field. Now let’s have a look at its implementation:

class My_Custom_Password_Validator extends Zend_Validate_Abstract
{
    const WRONG_PASSWORD = 'wrong_password';
 
    protected $_messageTemplates = array(
        self::WRONG_PASSWORD => "Login failed"
    );
 
    public function isValid($value, $context = null)
    {
        return $this->_validate($context['username'],$value);
    }
 
    protected function _validate($username,$password)
    {
        $authAdapter = new Zend_Auth_Adapter_DbTable(
            Zend_Registry::get('db'),
            'users',
            'username',
            'password',
            'MD5(?) AND active = 1'
        );
 
        $authAdapter->setIdentity($username)->setCredential($password);
 
        if(Zend_Auth::getInstance()->authenticate($authAdapter)->isValid())
        {
            return true;
        } else {
            $this->_error(self::WRONG_PASSWORD);
            return false;
        }
    }
}

We assume that username and password columns are in users table (see https://framework.zend.com/manual/en/zend.auth.adapter.dbtable.html) Pay attention to this

$context['username']

and

public function isValid($value, $context = null)

context = null second parameter. It holds all form values. So there we get username field.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.