Authentication.php 1.3 KB

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