GergelyPolonkai GergelyPolonkai - 1 month ago 14
PHP Question

Symfony 2 - onSecurityAuthenticationSuccess handler gets called on every page load

I have created a

security.authentication.success
event listener, which should send a line to the logs upon login success. Now every time I load a page which is behind a firewall, I get a successful login message in my logs. If I tried to use

if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY'))
{
$logger->info('Successful login by ' . $username);
}


I get into a recursive madness (xdebug complaining after 10000 nested calls, or whatever high I set it to).

Is there a way to check if the user has just logged in, or if (s)he is using an active session?

Note: I'm using Symfony 2.2 (dev-master)

Answer

You have to use the security.interactive_login:

namespace Acme\UserBundle\Listener;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.1.x
// use Symfony\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.0.x

/**
 * Custom login listener.
 */
class LoginListener
{
    /** @var \Symfony\Component\Security\Core\SecurityContext */
    private $securityContext;

    /** @var \Doctrine\ORM\EntityManager */
    private $em;

    /**
     * Constructor
     * 
     * @param SecurityContext $securityContext
     * @param Doctrine        $doctrine
     */
    public function __construct(SecurityContext $securityContext, Doctrine $doctrine)
    {
        $this->securityContext = $securityContext;
        $this->em              = $doctrine->getEntityManager();
    }

    /**
     * Do the magic.
     * 
     * @param  Event $event
     */
    public function onSecurityInteractiveLogin(Event $event)
    {
        if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
            // user has just logged in
        }

        if ($this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            // user has logged in using remember_me cookie
        }

        // do some other magic here
        $user = $this->securityContext->getToken()->getUser();

        // ...
    }
}