src/EventSubscriber/Auth/UserSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber\Auth;
  4. use App\Entity\App\User;
  5. use App\Event\Auth\UserCreatedEvent;
  6. use App\Event\Auth\UserResetEvent;
  7. use App\Service\NotifierInterface;
  8. use DateTime;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. class UserSubscriber implements EventSubscriberInterface
  12. {
  13. protected UserPasswordHasherInterface $encoder;
  14. public function __construct(UserPasswordHasherInterface $passwordEncoder)
  15. {
  16. $this->encoder = $passwordEncoder;
  17. }
  18. public static function getSubscribedEvents(): array
  19. {
  20. return [
  21. UserCreatedEvent::class => ['onUserCreated', 100],
  22. UserResetEvent::class => ['onUserReset', 100],
  23. ];
  24. }
  25. public function onUserCreated(UserCreatedEvent $event): void
  26. {
  27. $this->updatePassword($event->getUser());
  28. $this->sendConfirmationEmail($event->getUser(), $event->getNotifier());
  29. }
  30. public function onUserReset(UserResetEvent $event): void
  31. {
  32. $this->sendResetEmail($event->getUser(), $event->getNotifier());
  33. }
  34. /**
  35. * Hash user password
  36. */
  37. protected function updatePassword(User $user): void
  38. {
  39. $plainPassword = $user->getPlainPassword();
  40. if (!$plainPassword) {
  41. return;
  42. }
  43. $user->setPassword(
  44. $this->encoder->hashPassword($user, $plainPassword)
  45. );
  46. }
  47. /**
  48. * Send email to user email address for account verification
  49. */
  50. protected function sendConfirmationEmail(User $user, NotifierInterface $notifier): void
  51. {
  52. $notifier->send(
  53. $user->setConfirmationToken(
  54. md5(
  55. microtime()
  56. )
  57. )
  58. );
  59. }
  60. /**
  61. * Send email to user email for password reset
  62. */
  63. protected function sendResetEmail(User $user, NotifierInterface $notifier): void
  64. {
  65. $notifier->send(
  66. $user->setConfirmationToken(md5(microtime()))
  67. ->setPasswordRequestedAt(new DateTime())
  68. );
  69. }
  70. }