From 469d0baa3a91a78dd21855e07a15a7020f71ad8b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 21 Jun 2022 16:21:33 +0200 Subject: [PATCH] SimpleAuthenticator: passwords can be hashed --- src/Security/SimpleAuthenticator.php | 4 ++++ tests/Security/SimpleAuthenticator.phpt | 20 +++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/Security/SimpleAuthenticator.php b/src/Security/SimpleAuthenticator.php index 6a34a68a..2af590b0 100644 --- a/src/Security/SimpleAuthenticator.php +++ b/src/Security/SimpleAuthenticator.php @@ -28,6 +28,7 @@ public function __construct( private array $passwords, private array $roles = [], private array $data = [], + private ?Passwords $verifier = null, ) { } @@ -55,6 +56,9 @@ public function authenticate(string $username, string $password): IIdentity protected function verifyPassword(string $password, string $passOrHash): bool { + if (preg_match('~\$.{50,}~A', $passOrHash)) { + return $this->verifier->verify($password, $passOrHash); + } return $password === $passOrHash; } } diff --git a/tests/Security/SimpleAuthenticator.phpt b/tests/Security/SimpleAuthenticator.phpt index ed0ecfc4..a8ebded2 100644 --- a/tests/Security/SimpleAuthenticator.phpt +++ b/tests/Security/SimpleAuthenticator.phpt @@ -6,6 +6,7 @@ declare(strict_types=1); +use Nette\Security\Passwords; use Nette\Security\SimpleAuthenticator; use Tester\Assert; @@ -14,16 +15,12 @@ require __DIR__ . '/../bootstrap.php'; $users = [ - 'john' => 'password123!', + 'john' => '$2a$12$dliX6LynG/iChDUF7DhKzulN7d3nU.l3/RozE1MmEaxxBWdZXppm2', 'admin' => 'admin', ]; $authenticator = new SimpleAuthenticator($users); -$identity = $authenticator->authenticate('john', 'password123!'); -Assert::type(Nette\Security\IIdentity::class, $identity); -Assert::equal('john', $identity->getId()); - $identity = $authenticator->authenticate('admin', 'admin'); Assert::type(Nette\Security\IIdentity::class, $identity); Assert::equal('admin', $identity->getId()); @@ -39,3 +36,16 @@ Assert::exception( Nette\Security\AuthenticationException::class, "User 'nobody' not found.", ); + + +$authenticator = new SimpleAuthenticator($users, verifier: new Passwords); + +$identity = $authenticator->authenticate('john', 'password123!'); +Assert::type(Nette\Security\IIdentity::class, $identity); +Assert::equal('john', $identity->getId()); + +Assert::exception( + fn() => $authenticator->authenticate('john', $users['john']), + Nette\Security\AuthenticationException::class, + 'Invalid password.', +);