Authentication.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * @package Grav\Common\User
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\User;
  9. abstract class Authentication
  10. {
  11. /**
  12. * Create password hash from plaintext password.
  13. *
  14. * @param string $password Plaintext password.
  15. *
  16. * @throws \RuntimeException
  17. * @return string
  18. */
  19. public static function create($password): string
  20. {
  21. if (!$password) {
  22. throw new \RuntimeException('Password hashing failed: no password provided.');
  23. }
  24. $hash = password_hash($password, PASSWORD_DEFAULT);
  25. if (!$hash) {
  26. throw new \RuntimeException('Password hashing failed: internal error.');
  27. }
  28. return $hash;
  29. }
  30. /**
  31. * Verifies that a password matches a hash.
  32. *
  33. * @param string $password Plaintext password.
  34. * @param string $hash Hash to verify against.
  35. *
  36. * @return int Returns 0 if the check fails, 1 if password matches, 2 if hash needs to be updated.
  37. */
  38. public static function verify($password, $hash): int
  39. {
  40. // Fail if hash doesn't match
  41. if (!$password || !$hash || !password_verify($password, $hash)) {
  42. return 0;
  43. }
  44. // Otherwise check if hash needs an update.
  45. return password_needs_rehash($hash, PASSWORD_DEFAULT) ? 2 : 1;
  46. }
  47. }