Snippets - Little bits of code to make you happy
Using a Password ValidatorTweet
18 October 2010 | |
The Password Validator allows you to set particular criteria for your members passwords. For example if you wanted to have a minimum length of 8 characters and contain lowercase and uppercase characters, well that's a simple case of adding a couple of lines to your _config.php file!
So before we get into the reference let's jump in with an example. The following code, when added to the mysite/_config.php will set a minimum length of 6 characters and force the user to use 2 of either uppercase, lowercase, punctuation and digits:
$Validator = new PasswordValidator(); $Validator->minLength(6); Member::set_password_validator($Validator);
So let's go through this. The first line creates a new PasswordValidator Object, then we set the minimum length to 6 characters. Finally we tell SilverStripe that we want to use this validator for our member object, for which we use the handy function set_password_validator(), passing in our validator as the argument.
We can also ensure that the user is using a certain number of different character types by using the charachterStrength() function. This takes 2 arguments, the first is the acceptable scrore and the second is the values to test. Here's how you might use it:
$Validator->characterStrength(2, array('lowercase', 'uppercase', 'digits', 'punctuation'));
So in this example we are saying make sure the user has at least 2 of the following items; lower case letters, upper case letters, numerical digits and punctuation characters. If we wanted the user to have all of these in their password, then we would set the first argument to 4.
The last thing we can do to make our members even more secure (and perhaps a little frustrated!) is ensure that when they change their password they don't set it to one of their previous passwords. We do this using checkHistoricalPasswords() which takes the number of prevous passwords to check as it's only argument. This would be used like so:
So to bring all this together here's a full example:
//Min 8 Chars, not last 2 passwords, 2 of Lowercase, Uppercase or Digits $Validator = new PasswordValidator(); $Validator->minLength(8); $Validator->checkHistoricalPasswords(2); $Validator->characterStrength(3,array('lowercase','uppercase','digits')); Member::set_password_validator($Validator);
There you have it, a great way to force your will onto others!