Skip to content

Commit

Permalink
SimpleAuthenticator: passwords can be hashed
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 6, 2022
1 parent 46a04b4 commit 9a987d9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/Security/SimpleAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public function __construct(
private array $passwords,
private array $roles = [],
private array $data = [],
private ?Passwords $verifier = null,
) {
}

Expand Down Expand Up @@ -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;
}
}
20 changes: 15 additions & 5 deletions tests/Security/SimpleAuthenticator.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,20 @@
declare(strict_types=1);

use Nette\Security\SimpleAuthenticator;
use Nette\Security\Passwords;
use Tester\Assert;


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());
Expand All @@ -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.',
);

0 comments on commit 9a987d9

Please sign in to comment.