password_policy_pwned-8.x-1.0-beta2/src/PwnedPasswordsClient.php

src/PwnedPasswordsClient.php
<?php

namespace Drupal\password_policy_pwned;

use Drupal\Component\Utility\DeprecationHelper;
use Drupal\Core\Utility\Error;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;

/**
 * The Pwned Passwords client.
 */
class PwnedPasswordsClient implements PwnedPasswordsClientInterface {

  /**
   * The http client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * PwnedPasswordsClient constructor.
   *
   * @param \GuzzleHttp\ClientInterface $http_client
   *   The HTTP client.
   */
  public function __construct(ClientInterface $http_client) {
    $this->httpClient = $http_client;
  }

  /**
   * {@inheritdoc}
   */
  public function getOccurrences($password) {
    $hash = strtoupper(sha1($password));
    $hashPrefix = substr($hash, 0, 5);
    $hashSuffix = substr($hash, 5);

    $url = "https://api.pwnedpasswords.com/range/$hashPrefix";

    try {
      $response = $this->httpClient->request('GET', $url, [
        'timeout' => 10.0,
      ]);

      if ($response->getStatusCode() == 200) {
        $body = (string) $response->getBody();
        $lines = explode("\n", $body);
        foreach ($lines as $line) {
          [$exposedHashSuffix, $occurrences] = explode(':', $line);
          if ($hashSuffix === $exposedHashSuffix) {
            return $occurrences;
          }
        }
      }
    }
    catch (GuzzleException $e) {
      DeprecationHelper::backwardsCompatibleCall(
        \Drupal::VERSION,
        '10.1.0',
        fn() => Error::logException(\Drupal::logger('password_policy_pwned'), $e),
        fn() => watchdog_exception('password_policy_pwned', $e)
      );
    }

    // If we get an error, just ignore and return 0.
    return 0;

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc