Skip to content

Instantly share code, notes, and snippets.

@yakubenko
Created April 2, 2018 06:48
Show Gist options
  • Save yakubenko/6b3a5a82e4b887c3a6525f78da6f1e05 to your computer and use it in GitHub Desktop.
Save yakubenko/6b3a5a82e4b887c3a6525f78da6f1e05 to your computer and use it in GitHub Desktop.
A password component for CakePHP 3. Allows generating a password which matches a given pattern.
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Auth\DefaultPasswordHasher;
class PasswordComponent extends Component {
public function generate() {
return $this->create_password('##CcC#C');
}
public function hash($password) {
return (new DefaultPasswordHasher())->hash($password);
}
// http://www.bestcodingpractices.com/php_create_strong_random_passwords-27.html
// Mask Rules
// # - digit
// C - Caps Character (A-Z)
// c - Small Character (a-z)
// X - Mixed Case Character (a-zA-Z)
// ! - Custom Extended Characters
private function create_password($mask) {
$extended_chars = "!@#$%^&*()";
$length = strlen($mask);
$pwd = '';
for ($c=0;$c<$length;$c++) {
$ch = $mask[$c];
switch ($ch) {
case '#':
$p_char = rand(0,9);
break;
case 'C':
$p_char = chr(rand(65,90));
break;
case 'c':
$p_char = chr(rand(97,122));
break;
case 'X':
do {
$p_char = rand(65,122);
} while ($p_char > 90 && $p_char < 97);
$p_char = chr($p_char);
break;
case '!':
$p_char = $extended_chars[rand(0,strlen($extended_chars)-1)];
break;
}
$pwd .= $p_char;
}
return $pwd;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment