<?php

namespace App\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class PreventDisabledUserAutoLoginListener implements EventSubscriberInterface
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::RESETTING_RESET_COMPLETED => ['onResettingCompleted', 999], // high priority
        ];
    }

    public function onResettingCompleted(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();

        if (!$user->isEnabled()) {
            // Delete authentication token so disabled user isn't automaticaly connected after resetting password
            $this->tokenStorage->setToken(null);
        }
    }
}