PasswordPolicy
A tool for checking and creating password policies in PHP and JS., (*1)
Installation
Use composer to setup an autoloader, (*2)
php composer.phar install
Require the composer autoload file:, (*3)
require_once 'vendor/autoload.php';
Usage:
To use, first instantiate the core policy object:, (*4)
$policy = new \PasswordPolicy\Policy;
Then, add rules:, (*5)
$policy->contains('lowercase', $policy->atLeast(2));
Supported rule helper methods are:
-
contains($class, $constraint = null, $description = ''): Checks to see if a password contains a class of chars, (*6)
Supported Short-Cut classes:, (*7)
-
letter - a-zA-Z
-
lowercase - a-z
-
uppercase - A-Z
-
digit - 0-9
-
symbol - ^a-zA-Z0-9 (in other words, non-alpha-numeric)
-
null - \0
-
alnum - a-zA-Z0-9
The second param is a constraint (optional), (*8)
-
length($constraint): Checks the length of the password matches a constraint, (*9)
-
endsWith($class, $description = ''): Checks to see if the password ends with a character class., (*10)
-
startsWith($class, $description = ''): Checks to see if the password starts with a character class., (*11)
-
notMatch($regex, $description): Checks if the password does not match a regex., (*12)
-
match($regex, $description): Checks if the password matches the regex., (*13)
Supported Constraints:
The policy also has short-cut helpers for creating constraints:, (*14)
-
atLeast($n): At least the param matches, (*15)
Equivilant to between($n, PHP_INT_MAX), (*16)
-
atMost($n): At most the param matches, (*17)
Equivilant to between(0, $n), (*18)
-
between($min, $max): Between $min and $max number of matches, (*19)
-
never(): No matches, (*20)
Equivilant to between(0, 0), (*21)
Testing the policy
Once you setup the policy, you can then test it in PHP using the test($password) method., (*22)
$result = $policy->test($password);
The result return is a stdclass object with two members, result and messages., (*23)
-
$result->result - A boolean if the password is valid., (*24)
-
$result->messages - An array of messages, (*25)
Each message is an object of two members:, (*26)
-
$message->result - A boolean indicating if the rule passed, (*27)
-
$message->message - A textual description of the rule, (*28)
Using JavaScript
Once you've built the policy, you can call toJavaScript() to generate a JS anonymous function for injecting into JS code., (*29)
$js = $policy->toJavaScript();
echo "var policy = $js;";
Then, the policy object in JS is basically a wrapper for $policy->test($password), and behaves the same (same return values)., (*30)
var result = policy(password);
if (!result.result) {
/* Process Messages To Display Failure To User */
}
One note for the JavaScript, any regular expressions that you write need to be deliminated by / and be valid JS regexes (no PREG specific functionality is allowed)., (*31)