|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace midorikocak\nanoauth; |
|
6
|
|
|
|
|
7
|
|
|
use Exception; |
|
8
|
|
|
use midorikocak\nanodb\RepositoryInterface; |
|
9
|
|
|
use midorikocak\querymaker\QueryMaker; |
|
10
|
|
|
|
|
11
|
|
|
use function password_hash; |
|
12
|
|
|
use function password_verify; |
|
13
|
|
|
use function reset; |
|
14
|
|
|
|
|
15
|
|
|
class Authentication implements AuthenticationInterface, RegisterableInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private ?UserInterface $loggedUser = null; |
|
18
|
|
|
private RepositoryInterface $userRepository; |
|
19
|
|
|
|
|
20
|
6 |
|
public function __construct(RepositoryInterface $userRepository) |
|
21
|
|
|
{ |
|
22
|
6 |
|
$this->userRepository = $userRepository; |
|
23
|
6 |
|
} |
|
24
|
|
|
|
|
25
|
4 |
|
public function login(string $username, string $password): bool |
|
26
|
|
|
{ |
|
27
|
4 |
|
$queryMaker = new QueryMaker(); |
|
28
|
4 |
|
$query = $queryMaker->select('users')->where('username', $username); |
|
29
|
4 |
|
$foundUsers = $this->userRepository->readAll($query); |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var UserInterface $user |
|
33
|
|
|
*/ |
|
34
|
4 |
|
$user = reset($foundUsers); |
|
35
|
|
|
|
|
36
|
4 |
|
if ($user !== null && password_verify($password, $user->getPassword())) { |
|
37
|
4 |
|
$this->loggedUser = $user; |
|
38
|
4 |
|
return true; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return false; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
2 |
|
public function logout(): void |
|
45
|
|
|
{ |
|
46
|
2 |
|
if ($this->loggedUser !== null) { |
|
47
|
|
|
unset($this->loggedUser); |
|
48
|
|
|
} |
|
49
|
2 |
|
} |
|
50
|
|
|
|
|
51
|
5 |
|
public function isLogged(): bool |
|
52
|
|
|
{ |
|
53
|
5 |
|
return $this->loggedUser !== null; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @return mixed |
|
58
|
|
|
*/ |
|
59
|
2 |
|
public function getLoggedUser() |
|
60
|
|
|
{ |
|
61
|
2 |
|
return $this->loggedUser; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
1 |
|
public function register(string $username, string $email, string $password): bool |
|
65
|
|
|
{ |
|
66
|
|
|
try { |
|
67
|
1 |
|
$user = new User(null, $username, $email, password_hash($password, PASSWORD_DEFAULT)); |
|
68
|
|
|
|
|
69
|
1 |
|
$this->userRepository->save($user); |
|
70
|
1 |
|
return true; |
|
71
|
|
|
} catch (Exception $e) { |
|
72
|
|
|
return false; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|