Passed
Push — master ( 088a14...696b0c )
by Torben
02:02
created

PwnedPasswordsService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 15
dl 0
loc 30
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A checkPassword() 0 19 4
1
<?php
2
namespace Derhansen\FeChangePwd\Service;
3
4
/*
5
 * This file is part of the Extension "fe_change_pwd" for TYPO3 CMS.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
/**
12
 * Class PwnedPasswordsService
13
 */
14
class PwnedPasswordsService
15
{
16
    const API_URL = 'https://api.pwnedpasswords.com/range/';
17
18
    /**
19
     * Checks the given password against data breaches using the haveibeenpwned.com API
20
     * Returns the amount of times the password is found in the haveibeenpwned.com database
21
     *
22
     * @param string $password
23
     * @return int
24
     */
25
    public function checkPassword(string $password)
26
    {
27
        $hash = sha1($password);
28
        $ch = curl_init();
29
        curl_setopt($ch, CURLOPT_URL, self::API_URL . substr($hash, 0, 5));
30
        curl_setopt($ch, CURLOPT_USERAGENT, 'TYPO3 Extension fe_change_pwd');
31
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
32
        $results = curl_exec($ch);
33
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
34
        curl_close($ch);
35
        if (($httpCode !== 200) || empty($results)) {
36
            // Something went wrong with the request, return 0 and ignore check
37
            return 0;
38
        }
39
40
        if (preg_match('/' . preg_quote(substr($hash, 5)) . ':([0-9]+)/ism', $results, $matches) === 1) {
41
            return $matches[1];
42
        }
43
        return 0;
44
    }
45
}
46