Completed
Push — master ( 8e03fe...2e168d )
by Anthony
02:04
created

PasswordPwnedListValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 55
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 16 4
A getBlacklistPasswords() 0 10 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Porthou\Password\Validators;
5
6
use Generator;
7
use Porthou\Password\PasswordException;
8
9
class PasswordPwnedListValidator
10
{
11
    /** @var string $file */
12
    private $file;
13
14
    /** @var int $minimumThreshold */
15
    private $minimumThreshold;
16
17
    /**
18
     * PasswordPwnedListValidator constructor.
19
     *
20
     * @param string $file the path to the blacklist file
21
     * @param int $minimumThreshold How many times a password must appear before we consider it invalid
22
     * @see https://haveibeenpwned.com/Passwords for access to the list of passwords to be used with this validator.
23
     */
24
    public function __construct(string $file, $minimumThreshold = 50)
25
    {
26
        $this->file = $file;
27
        $this->minimumThreshold = $minimumThreshold;
28
    }
29
30
    /** {@inheritdoc} */
31
    public function validate(string $password): bool
32
    {
33
        $passwordHash = sha1($password);
34
35
        foreach ($this->getBlacklistPasswords() as $badPassword) {
36
            [$badHash, $count] = $badPassword;
0 ignored issues
show
Bug introduced by
The variable $badHash does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $count does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
37
            if (
38
                $passwordHash === $badHash
39
                && $count >= $this->minimumThreshold
40
            ) {
41
                throw new PasswordException('Password has been pwned.');
42
            }
43
        }
44
45
        return true;
46
    }
47
48
    /**
49
     * Iterates over and yields each blacklisted password
50
     *
51
     * @return Generator
52
     */
53
    private function getBlacklistPasswords(): Generator
54
    {
55
        $fh = fopen($this->file, 'rb');
56
57
        while (($password = fgets($fh)) !== false) {
58
            yield explode(':', trim($password));
59
        }
60
61
        fclose($fh);
62
    }
63
}
64