<?php
namespace Eckinox\SecurityBundle\EventSubscriber;
use Eckinox\SecurityBundle\Event\AppUserEvent;
use Eckinox\SecurityBundle\Notifier\CreatePasswordLoginLinkNotification;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Notifier\NotifierInterface;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\LoginLink\LoginLinkDetails;
use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class AppUserSubscriber implements EventSubscriberInterface
{
public function __construct(
private RequestStack $requestStack,
private LoginLinkHandlerInterface $loginLinkHandler,
private Environment $twig,
private UrlGeneratorInterface $router,
private NotifierInterface $notifier,
private TranslatorInterface $translator
) {
}
public static function getSubscribedEvents(): array
{
return [
AppUserEvent::CREATED_SUCCESS => [['onUserCreate', 0]],
];
}
public function onUserCreate(AppUserEvent $event): void
{
$user = $event->getUser();
$recipient = new Recipient($user->getEmail());
$loginLinkDetails = $this->loginLinkHandler->createLoginLink($user);
// Remake the login URL for the frontend firewall
$url = str_replace($this->router->generate('eckinox_security_login_check'), $this->router->generate('eckinox_security_app_login_check'), $loginLinkDetails->getUrl());
$loginLinkDetails = new LoginLinkDetails($url, $loginLinkDetails->getExpiresAt());
$template = $this->twig->getLoader()->exists('@EckinoxSecurity/email/app_create_password_login_email.html.twig') ? '@EckinoxSecurity/email/app_create_password_login_email.html.twig' : null;
$subject = $this->translator->trans('eckinox_security.messages.app_welcome') == 'eckinox_security.messages.app_welcome' ? $this->translator->trans('eckinox_security.messages.welcome') : $this->translator->trans('eckinox_security.messages.app_welcome');
$notification = new CreatePasswordLoginLinkNotification(
$this->translator,
$loginLinkDetails,
$subject,
$template
);
$this->notifier->send($notification, $recipient);
}
}