src/Auth/Infrastructure/Symfony/EventListener/UserResolveListener.php line 25

  1. <?php declare(strict_types=1);
  2. namespace App\Auth\Infrastructure\Symfony\EventListener;
  3. use App\Auth\Domain\Exceptions\UsernameNotFoundException;
  4. use App\Auth\Domain\Exceptions\WrongPasswordException;
  5. use App\Auth\Domain\User;
  6. use App\Auth\Infrastructure\Repositories\MysqlAuthRepository;
  7. use League\Bundle\OAuth2ServerBundle\Event\UserResolveEvent;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. use Symfony\Component\PasswordHasher\PasswordHasherInterface;
  10. final class UserResolveListener
  11. {
  12.     private MysqlAuthRepository $mysqlAuthRepository;
  13.     private UserPasswordHasherInterface $passwordHasher;
  14.     public function __construct(MysqlAuthRepository $mysqlAuthRepositoryUserPasswordHasherInterface $passwordHasher)
  15.     {
  16.         $this->mysqlAuthRepository $mysqlAuthRepository;
  17.         $this->passwordHasher $passwordHasher;
  18.     }
  19.     public function onUserResolve(UserResolveEvent $event): void
  20.     {
  21.         $user $this->mysqlAuthRepository->findUserByUsername($event->getUsername());
  22.         if (is_null($user)) {
  23.             throw new UsernameNotFoundException();
  24.         }
  25.         $isPasswordValid $this->passwordHasher->isPasswordValid($user$event->getPassword());
  26.         if (!$isPasswordValid) {
  27.             throw new WrongPasswordException();
  28.         }
  29.         $user = new User(
  30.             'portail-' $user->getId(),
  31.             $user->getEmail(),
  32.             $user->getPassword(),
  33.             $user->getFirstName(),
  34.             $user->getLastName(),
  35.             $user->getRoles()
  36.         );
  37.         $event->setUser($user);
  38.     }
  39. }