UserAuth.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Drupal\user;
  3. use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
  4. use Drupal\Core\Entity\EntityTypeManagerInterface;
  5. use Drupal\Core\Password\PasswordInterface;
  6. /**
  7. * Validates user authentication credentials.
  8. */
  9. class UserAuth implements UserAuthInterface {
  10. use DeprecatedServicePropertyTrait;
  11. /**
  12. * {@inheritdoc}
  13. */
  14. protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
  15. /**
  16. * The entity type manager.
  17. *
  18. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  19. */
  20. protected $entityTypeManager;
  21. /**
  22. * The password hashing service.
  23. *
  24. * @var \Drupal\Core\Password\PasswordInterface
  25. */
  26. protected $passwordChecker;
  27. /**
  28. * Constructs a UserAuth object.
  29. *
  30. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  31. * The entity type manager.
  32. * @param \Drupal\Core\Password\PasswordInterface $password_checker
  33. * The password service.
  34. */
  35. public function __construct(EntityTypeManagerInterface $entity_type_manager, PasswordInterface $password_checker) {
  36. $this->entityTypeManager = $entity_type_manager;
  37. $this->passwordChecker = $password_checker;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function authenticate($username, $password) {
  43. $uid = FALSE;
  44. if (!empty($username) && strlen($password) > 0) {
  45. $account_search = $this->entityTypeManager->getStorage('user')->loadByProperties(['name' => $username]);
  46. if ($account = reset($account_search)) {
  47. if ($this->passwordChecker->check($password, $account->getPassword())) {
  48. // Successful authentication.
  49. $uid = $account->id();
  50. // Update user to new password scheme if needed.
  51. if ($this->passwordChecker->needsRehash($account->getPassword())) {
  52. $account->setPassword($password);
  53. $account->save();
  54. }
  55. }
  56. }
  57. }
  58. return $uid;
  59. }
  60. }