|
1 | | -<?php |
| 1 | +<?php declare(strict_types = 1); |
2 | 2 |
|
3 | 3 | namespace Contributte\Http\Auth; |
4 | 4 |
|
5 | 5 | use Nette\Http\IRequest; |
6 | 6 | use Nette\Http\IResponse; |
| 7 | +use Tracy\Debugger; |
7 | 8 |
|
8 | 9 | class BasicAuthenticator |
9 | 10 | { |
10 | 11 |
|
11 | 12 | /** @var string */ |
12 | 13 | private $title; |
13 | 14 |
|
14 | | - /** @var array */ |
| 15 | + /** @var mixed[] */ |
15 | 16 | private $users = []; |
16 | 17 |
|
17 | | - /** |
18 | | - * @param string $title |
19 | | - */ |
20 | | - public function __construct($title) |
| 18 | + public function __construct(string $title) |
21 | 19 | { |
22 | 20 | $this->title = $title; |
23 | 21 | } |
24 | 22 |
|
25 | | - /** |
26 | | - * @param string $user |
27 | | - * @param string $password |
28 | | - * @return static |
29 | | - */ |
30 | | - public function addUser($user, $password) |
| 23 | + public function addUser(string $user, string $password, bool $unsecured): self |
31 | 24 | { |
32 | | - $this->users[$user] = $password; |
33 | | - |
| 25 | + $this->users[$user] = [ |
| 26 | + 'password' => $password, |
| 27 | + 'unsecured' => $unsecured, |
| 28 | + ]; |
34 | 29 | return $this; |
35 | 30 | } |
36 | 31 |
|
37 | | - /** |
38 | | - * @param IRequest $request |
39 | | - * @param IResponse $response |
40 | | - * @return void |
41 | | - */ |
42 | | - public function authenticate(IRequest $request, IResponse $response) |
| 32 | + public function authenticate(IRequest $request, IResponse $response): void |
43 | 33 | { |
44 | 34 | $user = $request->getUrl()->getUser(); |
45 | 35 | $password = $request->getUrl()->getPassword(); |
46 | 36 |
|
47 | 37 | if (!$this->auth($user, $password)) { |
| 38 | + if (class_exists(Debugger::class)) { |
| 39 | + Debugger::$productionMode = true; |
| 40 | + } |
| 41 | + |
48 | 42 | $response->setHeader('WWW-Authenticate', sprintf('Basic realm="%s"', $this->title)); |
49 | 43 | $response->setCode(IResponse::S401_UNAUTHORIZED); |
| 44 | + |
50 | 45 | echo '<h1>Authentication failed.</h1>'; |
51 | | - die(); |
| 46 | + die; |
52 | 47 | } |
53 | 48 | } |
54 | 49 |
|
55 | | - /** |
56 | | - * @param string $user |
57 | | - * @param string $password |
58 | | - * @return bool |
59 | | - */ |
60 | | - protected function auth($user, $password) |
| 50 | + protected function auth(string $user, string $password): bool |
61 | 51 | { |
62 | | - if (!isset($this->users[$user])) return FALSE; |
| 52 | + if (!isset($this->users[$user])) return false; |
| 53 | + |
| 54 | + if ( |
| 55 | + ($this->users[$user]['unsecured'] === true && !hash_equals($password, $this->users[$user]['password'])) || |
| 56 | + ($this->users[$user]['unsecured'] === false && !password_verify($password, $this->users[$user]['password'])) |
| 57 | + ) { |
| 58 | + return false; |
| 59 | + } |
63 | 60 |
|
64 | | - return $this->users[$user] === $password; |
| 61 | + return true; |
65 | 62 | } |
66 | 63 |
|
67 | 64 | } |
0 commit comments