regexpasswordskohanakohana-3.3kohana-auth

Enforcing strong passwords in Kohana Auth


I am trying to enforce strong(er) passwords in my Kohana application using Auth, by using the following regex to require at least one upper case letter, one lower case, one number, one non-alphanum (special character), and a minimum of 8 characters.

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$

The regex is working, as can be seen on Rubular. Here's the code I'm using in Kohana's Model_Auth_User, which extends ORM.

public function rules() {
    return array(
        'password' => array(
            array('not_empty'),
            array('min_length', array(':value', 8)),
            array('regex', array(':value', '/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$/'))
        )
    );
}

However, when creating a new user account, or changing the password of an existing one, this regex seems to be completely ignored. The min_length from the line above is working fine though!

It will stop me from using test as a password because it's less than 8 characters, but testing123 doesn't give any sort of error message.

Any ideas why this is happening and a way around it?


Solution

  • Figured it out - you have to add the regex to the get_password_validation function (in the same Model) or it doesn't output any error message.

    public static function get_password_validation($values) {
        return Validation::factory($values)
            ->rule('password', 'min_length', array(':value', 8))
            ->rule('password', 'regex', array(':value', '/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$/'))
            ->rule('password_confirm', 'matches', array(':validation', ':field', 'password'));
    }
    

    If added, the regex in the rules() function needs to be removed or it's not possible to login as it runs the regex check on the hashed string, which doesn't contain any special characters.

    Hope this helps someone.