UserAuth.php 1.6 KB

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