src/EventSubscriber/Auth/UserSubscriber.php line 29

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. public function __construct(protected UserPasswordHasherInterface $encoder)
  14. {
  15. }
  16. public static function getSubscribedEvents(): array
  17. {
  18. return [
  19. UserCreatedEvent::class => ['onUserCreated', 100],
  20. UserResetEvent::class => ['onUserReset', 100],
  21. ];
  22. }
  23. public function onUserCreated(UserCreatedEvent $event): void
  24. {
  25. $this->updatePassword($event->getUser());
  26. $this->sendConfirmationEmail($event->getUser(), $event->getNotifier());
  27. }
  28. public function onUserReset(UserResetEvent $event): void
  29. {
  30. $this->sendResetEmail($event->getUser(), $event->getNotifier());
  31. }
  32. /**
  33. * Hash user password
  34. */
  35. protected function updatePassword(User $user): void
  36. {
  37. $plainPassword = $user->getPlainPassword();
  38. if (!$plainPassword) {
  39. return;
  40. }
  41. $user->setPassword(
  42. $this->encoder->hashPassword($user, $plainPassword)
  43. );
  44. }
  45. /**
  46. * Send email to user email address for account verification
  47. */
  48. protected function sendConfirmationEmail(User $user, NotifierInterface $notifier): void
  49. {
  50. $notifier->send(
  51. $user->setConfirmationToken(
  52. md5(
  53. microtime()
  54. )
  55. )
  56. );
  57. }
  58. /**
  59. * Send email to user email for password reset
  60. */
  61. protected function sendResetEmail(User $user, NotifierInterface $notifier): void
  62. {
  63. $notifier->send(
  64. $user->setConfirmationToken(md5(microtime()))
  65. ->setPasswordRequestedAt(new DateTime())
  66. );
  67. }
  68. }