PHP code example of choks / password-policy-bundle
1. Go to this page and download the library: Download choks/password-policy-bundle library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Choks\PasswordPolicy\Contract\PolicyInterface;
use Choks\PasswordPolicy\Contract\PolicyProviderInterface;
use Choks\PasswordPolicy\Model\ExpirationPolicy;
use Choks\PasswordPolicy\Model\CharacterPolicy;
use Choks\PasswordPolicy\Model\HistoryPolicy;
use Choks\PasswordPolicy\Model\Policy;
final class MyCustomPolicyProvider implements PolicyProviderInterface
{
public function getPolicy(UserInterface $user): PolicyInterface
{
// Assuming that you have your own way of storing Policy configuration, for example db.
$policyData = $this->entityManager->getRepository()->yourOwnWayOfFetchingData();
return new Policy(
new ExpirationPolicy(/* Use your stored data to construct */),
new CharacterPolicy(/* Use your stored data to construct */),
new HistoryPolicy(/* Use your stored data to construct */),
);
}
}
$checker = $this->getContainer()->get('password_policy.checker')
$violations = $checker->validate($user);
if ($violations->hasErrors()) {
// Do own stuff, you have violations to check error messages.
}
$history = $this->getContainer()->get('password_policy.history')
$history->add($user); // This will write password into password history.
# ...
# also:
$history->clear(); // This will clear all passwords in history, for all users.
$history->remove($user); // This will clear all passwords in history, for specific User.
use Choks\PasswordPolicy\Contract\PasswordPolicySubjectInterface;
use Doctrine\ORM\Mapping as ORM;
use Choks\PasswordPolicy\Atrribute\PasswordPolicy;
#[PasswordPolicy]
#[ORM\Entity]
class User implements PasswordPolicySubjectInterface
{
#[ORM\Id]
#[ORM\Column]
public int $id;
public ?string $plainPassword = null;
public function __construct(int $id, string $plainPassword = null)
{
$this->id = $id;
$this->plainPassword = $plainPassword;
}
public function getIdentifier(): string
{
return (string)$this->id;
}
public function setPlainPassword(#[\SensitiveParameter] ?string $plainPassword): User
{
$this->plainPassword = $plainPassword;
return $this;
}
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
}