Magento1Password.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Support;
  3. use Illuminate\Contracts\Auth\Authenticatable;
  4. use Illuminate\Support\Facades\Hash;
  5. /**
  6. * Magento 1.x password hashes: md5(password) or md5(salt + password).':'.salt
  7. */
  8. class Magento1Password
  9. {
  10. public static function verify(string $plain, string $hash): bool
  11. {
  12. if ($plain === '' || $hash === '') {
  13. return false;
  14. }
  15. $parts = explode(':', $hash);
  16. $computed = match (count($parts)) {
  17. 1 => md5($plain),
  18. 2 => md5($parts[1].$plain),
  19. default => null,
  20. };
  21. if ($computed === null) {
  22. return false;
  23. }
  24. return hash_equals($parts[0], $computed);
  25. }
  26. public static function upgradeToBcrypt(Authenticatable $customer, string $plain): void
  27. {
  28. $customer->password = Hash::make($plain);
  29. $customer->legacy_password = null;
  30. $customer->save();
  31. }
  32. public static function attempt(Authenticatable $customer, string $plain): bool
  33. {
  34. $stored = (string) $customer->getAuthPassword();
  35. try {
  36. if ($stored !== '' && Hash::check($plain, $stored)) {
  37. return true;
  38. }
  39. } catch (\Throwable) {
  40. // Magento hashes are not bcrypt; continue with the legacy verifier.
  41. }
  42. $legacy = (string) ($customer->legacy_password ?? '');
  43. if ($legacy !== '' && self::verify($plain, $legacy)) {
  44. self::upgradeToBcrypt($customer, $plain);
  45. return true;
  46. }
  47. return false;
  48. }
  49. }