Added minimum password requirements

This commit is contained in:
MatteoF96
2022-01-10 12:34:57 +01:00
parent 504e18c855
commit 43fd2fdc34
5 changed files with 52 additions and 11 deletions

View File

@ -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;