PwnedPasswordsService   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 14
c 2
b 0
f 0
dl 0
loc 33
rs 10

1 Method

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