PasswordManager::isValid()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2.0625
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 48
    public function __construct(Selectable $passwordRepository, LoggerInterface $logger)
27
    {
28 48
        $this->passwordRepository = $passwordRepository;
29 48
        $this->logger = $logger;
30 48
    }
31
32 14
    public function isValidForUser(string $password, User $user): bool
33
    {
34 14
        $results = $this->passwordRepository->matching(
35 14
            Criteria::create()
36 14
                ->where(Criteria::expr()->eq('owner', $user))
37 14
                ->andWhere(Criteria::expr()->eq('active', true))
38
        );
39 14
        if ($results->count()) {
40
            /** @var Password $pw */
41 14
            $pw = $results->first();
42 14
            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 14
    private function isExpired(Password $password)
53
    {
54 14
        return $password->getDue() < new \DateTime();
55
    }
56
57 4
    public function getHash(string $password): string
58
    {
59 4
        return password_hash($password, PASSWORD_DEFAULT);
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65 14
    public function isValid(string $password, Password $passwordObject): bool
66
    {
67 14
        if ($this->isExpired($passwordObject)) {
68
            throw new PasswordExpiredException('Password is expired.');
69
        }
70 14
        return password_verify($password, $passwordObject->getHash());
71
    }
72
}
73