|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Authentication\Service; |
|
5
|
|
|
|
|
6
|
|
|
use Doctrine\Common\Collections\Criteria; |
|
7
|
|
|
use Doctrine\Common\Collections\Selectable; |
|
8
|
|
|
use Psr\Log\LoggerInterface; |
|
9
|
|
|
use SlayerBirden\DataFlowServer\Authentication\Entities\Password; |
|
10
|
|
|
use SlayerBirden\DataFlowServer\Authentication\Exception\InvalidCredentialsException; |
|
11
|
|
|
use SlayerBirden\DataFlowServer\Authentication\Exception\PasswordExpiredException; |
|
12
|
|
|
use SlayerBirden\DataFlowServer\Authentication\PasswordManagerInterface; |
|
13
|
|
|
use SlayerBirden\DataFlowServer\Domain\Entities\User; |
|
14
|
|
|
|
|
15
|
|
|
final class PasswordManager implements PasswordManagerInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var LoggerInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
private $logger; |
|
21
|
|
|
/** |
|
22
|
|
|
* @var Selectable |
|
23
|
|
|
*/ |
|
24
|
|
|
private $passwordRepository; |
|
25
|
|
|
|
|
26
|
17 |
|
public function __construct(Selectable $passwordRepository, LoggerInterface $logger) |
|
27
|
|
|
{ |
|
28
|
17 |
|
$this->passwordRepository = $passwordRepository; |
|
29
|
17 |
|
$this->logger = $logger; |
|
30
|
17 |
|
} |
|
31
|
|
|
|
|
32
|
7 |
|
public function isValidForUser(string $password, User $user): bool |
|
33
|
|
|
{ |
|
34
|
7 |
|
$results = $this->passwordRepository->matching( |
|
35
|
7 |
|
Criteria::create() |
|
36
|
7 |
|
->where(Criteria::expr()->eq('owner', $user)) |
|
37
|
7 |
|
->andWhere(Criteria::expr()->eq('active', true)) |
|
38
|
|
|
); |
|
39
|
7 |
|
if ($results->count()) { |
|
40
|
|
|
/** @var Password $pw */ |
|
41
|
7 |
|
$pw = $results->first(); |
|
42
|
7 |
|
return $this->isValid($password, $pw); |
|
43
|
|
|
} else { |
|
44
|
|
|
throw new InvalidCredentialsException('Invalid login/password combination.'); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param Password $password |
|
50
|
|
|
* @return bool |
|
51
|
|
|
*/ |
|
52
|
7 |
|
private function isExpired(Password $password) |
|
53
|
|
|
{ |
|
54
|
7 |
|
return $password->getDue() < new \DateTime(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
public function getHash(string $password): string |
|
58
|
|
|
{ |
|
59
|
2 |
|
return password_hash($password, PASSWORD_DEFAULT); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* @inheritdoc |
|
64
|
|
|
*/ |
|
65
|
7 |
|
public function isValid(string $password, Password $passwordObject): bool |
|
66
|
|
|
{ |
|
67
|
7 |
|
if ($this->isExpired($passwordObject)) { |
|
68
|
|
|
throw new PasswordExpiredException('Password is expired.'); |
|
69
|
|
|
} |
|
70
|
7 |
|
return password_verify($password, $passwordObject->getHash()); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|