Added minimum password requirements
This commit is contained in:
@ -13,6 +13,7 @@ namespace Da\User\Helper;
|
||||
|
||||
use yii\base\Exception;
|
||||
use yii\base\Security;
|
||||
use yii\base\InvalidConfigException;
|
||||
|
||||
class SecurityHelper
|
||||
{
|
||||
@ -60,25 +61,36 @@ class SecurityHelper
|
||||
return $this->security->validatePassword($password, $hash);
|
||||
}
|
||||
|
||||
public function generatePassword($length)
|
||||
public function generatePassword($length, $minPasswordRequirements)
|
||||
{
|
||||
$sets = [
|
||||
'abcdefghjkmnpqrstuvwxyz',
|
||||
'ABCDEFGHJKMNPQRSTUVWXYZ',
|
||||
'23456789',
|
||||
'lower' => 'abcdefghjkmnpqrstuvwxyz',
|
||||
'upper' => 'ABCDEFGHJKMNPQRSTUVWXYZ',
|
||||
'digit' => '123456789',
|
||||
'special' => '!#$%&()*+,-./:;<=>?@[\]^_{|}~'
|
||||
];
|
||||
$all = '';
|
||||
$password = '';
|
||||
foreach ($sets as $set) {
|
||||
$password .= $set[array_rand(str_split($set))];
|
||||
|
||||
if (isset($minPasswordRequirements['min']) && $length < $minPasswordRequirements['min']) {
|
||||
$length = $minPasswordRequirements['min'];
|
||||
}
|
||||
foreach ($sets as $setKey => $set) {
|
||||
if (isset($minPasswordRequirements[$setKey])) {
|
||||
for ($i = 0; $i < $minPasswordRequirements[$setKey]; $i++) {
|
||||
$password .= $set[array_rand(str_split($set))];
|
||||
}
|
||||
}
|
||||
$all .= $set;
|
||||
}
|
||||
|
||||
$passwordLength = strlen($password);
|
||||
if ($passwordLength > $length) {
|
||||
throw new InvalidConfigException('The minimum length is incompatible with other minimum requirements.');
|
||||
}
|
||||
$all = str_split($all);
|
||||
for ($i = 0; $i < $length - count($sets); ++$i) {
|
||||
for ($i = 0; $i < $length - $passwordLength; ++$i) {
|
||||
$password .= $all[array_rand($all)];
|
||||
}
|
||||
|
||||
$password = str_shuffle($password);
|
||||
|
||||
return $password;
|
||||
|
||||
Reference in New Issue
Block a user