vendor/ezsystems/ezplatform-kernel/eZ/Publish/Core/Repository/User/PasswordHashService.php line 17

Open in your IDE?
  1. <?php
  2. /**
  3.  * @copyright Copyright (C) Ibexa AS. All rights reserved.
  4.  * @license For full copyright and license information view LICENSE file distributed with this source code.
  5.  */
  6. declare(strict_types=1);
  7. namespace eZ\Publish\Core\Repository\User;
  8. use eZ\Publish\API\Repository\Values\User\User;
  9. use eZ\Publish\Core\Repository\User\Exception\UnsupportedPasswordHashType;
  10. /**
  11.  * @internal
  12.  */
  13. final class PasswordHashService implements PasswordHashServiceInterface
  14. {
  15.     /** @var int */
  16.     private $defaultHashType;
  17.     public function __construct(int $hashType User::DEFAULT_PASSWORD_HASH)
  18.     {
  19.         $this->defaultHashType $hashType;
  20.     }
  21.     public function getSupportedHashTypes(): array
  22.     {
  23.         return User::SUPPORTED_PASSWORD_HASHES;
  24.     }
  25.     public function isHashTypeSupported(int $hashType): bool
  26.     {
  27.         return in_array($hashType$this->getSupportedHashTypes(), true);
  28.     }
  29.     public function getDefaultHashType(): int
  30.     {
  31.         return $this->defaultHashType;
  32.     }
  33.     /**
  34.      * @throws \eZ\Publish\Core\Repository\User\Exception\UnsupportedPasswordHashType
  35.      */
  36.     public function createPasswordHash(string $password, ?int $hashType null): string
  37.     {
  38.         $hashType $hashType ?? $this->defaultHashType;
  39.         switch ($hashType) {
  40.             case User::PASSWORD_HASH_BCRYPT:
  41.                 return password_hash($passwordPASSWORD_BCRYPT);
  42.             case User::PASSWORD_HASH_PHP_DEFAULT:
  43.                 return password_hash($passwordPASSWORD_DEFAULT);
  44.             default:
  45.                 throw new UnsupportedPasswordHashType($hashType);
  46.         }
  47.     }
  48.     public function isValidPassword(string $plainPasswordstring $passwordHash, ?int $hashType null): bool
  49.     {
  50.         if ($hashType === User::PASSWORD_HASH_BCRYPT || $hashType === User::PASSWORD_HASH_PHP_DEFAULT) {
  51.             // In case of bcrypt let php's password functionality do it's magic
  52.             return password_verify($plainPassword$passwordHash);
  53.         }
  54.         // Randomize login time to protect against timing attacks
  55.         usleep(random_int(030000));
  56.         return $passwordHash === $this->createPasswordHash($plainPassword$hashType);
  57.     }
  58. }