5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Drupal\Core\Password\PasswordInterface;
9 * Validates user authentication credentials.
11 class UserAuth implements UserAuthInterface {
16 * @var \Drupal\Core\Entity\EntityManagerInterface
18 protected $entityManager;
21 * The password hashing service.
23 * @var \Drupal\Core\Password\PasswordInterface
25 protected $passwordChecker;
28 * Constructs a UserAuth object.
30 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
32 * @param \Drupal\Core\Password\PasswordInterface $password_checker
33 * The password service.
35 public function __construct(EntityManagerInterface $entity_manager, PasswordInterface $password_checker) {
36 $this->entityManager = $entity_manager;
37 $this->passwordChecker = $password_checker;
43 public function authenticate($username, $password) {
46 if (!empty($username) && strlen($password) > 0) {
47 $account_search = $this->entityManager->getStorage('user')->loadByProperties(['name' => $username]);
49 if ($account = reset($account_search)) {
50 if ($this->passwordChecker->check($password, $account->getPassword())) {
51 // Successful authentication.
52 $uid = $account->id();
54 // Update user to new password scheme if needed.
55 if ($this->passwordChecker->needsRehash($account->getPassword())) {
56 $account->setPassword($password);