Skip to content

Commit 469d0ba

Browse files
committed
SimpleAuthenticator: passwords can be hashed
1 parent 6a5fa97 commit 469d0ba

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

Diff for: src/Security/SimpleAuthenticator.php

+4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ public function __construct(
2828
private array $passwords,
2929
private array $roles = [],
3030
private array $data = [],
31+
private ?Passwords $verifier = null,
3132
) {
3233
}
3334

@@ -55,6 +56,9 @@ public function authenticate(string $username, string $password): IIdentity
5556

5657
protected function verifyPassword(string $password, string $passOrHash): bool
5758
{
59+
if (preg_match('~\$.{50,}~A', $passOrHash)) {
60+
return $this->verifier->verify($password, $passOrHash);
61+
}
5862
return $password === $passOrHash;
5963
}
6064
}

Diff for: tests/Security/SimpleAuthenticator.phpt

+15-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
declare(strict_types=1);
88

9+
use Nette\Security\Passwords;
910
use Nette\Security\SimpleAuthenticator;
1011
use Tester\Assert;
1112

@@ -14,16 +15,12 @@ require __DIR__ . '/../bootstrap.php';
1415

1516

1617
$users = [
17-
'john' => 'password123!',
18+
'john' => '$2a$12$dliX6LynG/iChDUF7DhKzulN7d3nU.l3/RozE1MmEaxxBWdZXppm2',
1819
'admin' => 'admin',
1920
];
2021

2122
$authenticator = new SimpleAuthenticator($users);
2223

23-
$identity = $authenticator->authenticate('john', 'password123!');
24-
Assert::type(Nette\Security\IIdentity::class, $identity);
25-
Assert::equal('john', $identity->getId());
26-
2724
$identity = $authenticator->authenticate('admin', 'admin');
2825
Assert::type(Nette\Security\IIdentity::class, $identity);
2926
Assert::equal('admin', $identity->getId());
@@ -39,3 +36,16 @@ Assert::exception(
3936
Nette\Security\AuthenticationException::class,
4037
"User 'nobody' not found.",
4138
);
39+
40+
41+
$authenticator = new SimpleAuthenticator($users, verifier: new Passwords);
42+
43+
$identity = $authenticator->authenticate('john', 'password123!');
44+
Assert::type(Nette\Security\IIdentity::class, $identity);
45+
Assert::equal('john', $identity->getId());
46+
47+
Assert::exception(
48+
fn() => $authenticator->authenticate('john', $users['john']),
49+
Nette\Security\AuthenticationException::class,
50+
'Invalid password.',
51+
);

0 commit comments

Comments
 (0)