Authentication.php 1.5 KB

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