<?php
declare(strict_types=1);
namespace Harmonizely\EventSubscriber;
use Harmonizely\Model\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Harmonizely\Core\Exception\AccountDisabledException;
final class RequireProfileSettingsSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $router;
public function __construct(RouterInterface $router, TokenStorageInterface $tokenStorage)
{
$this->router = $router;
$this->tokenStorage = $tokenStorage;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['redirect'],
];
}
public function redirect(GetResponseEvent $event)
{
if (null !== ($token = $this->tokenStorage->getToken()) && ($user = $token->getUser()) instanceof UserInterface) {
$request = $event->getRequest();
$routeName = $request->get('_route');
if (null === $routeName) {
return;
}
if ('hrm_welcome_index' === $routeName || 0 === strpos($routeName, 'consent_') || 0 === strpos($routeName, 'api_')) {
return;
}
if ($user->isRequireConfirmEmail()) {
$confirmEmailRoutes = [
'resend_user_verification_code',
'fos_user_registration_check_email',
'validate_user_verification_code',
];
if (!in_array($routeName, $confirmEmailRoutes)) {
if ($request->headers->has('X-AUTH-TOKEN')) {
throw new AccountDisabledException('User email is not confirmed', [], 406);
} else {
$event->setResponse(new RedirectResponse($this->router->generate('fos_user_registration_check_email')));
}
}
}
if (null === $user->getConsent()) {
$event->setResponse(new RedirectResponse($this->router->generate('consent_index')));
}
if (null === $user->getTimezone() || null === $user->getLocale() || null === $user->getTimeFormat()) {
$event->setResponse(new RedirectResponse($this->router->generate('hrm_welcome_index'), 302));
}
}
}
}