Question

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)

Was it helpful?

Solution

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();

        // ...
    }
}

OTHER TIPS

From the documentation:

The security.interactive_login event is triggered after a user has actively logged into your website. It is important to distinguish this action from non-interactive authentication methods, such as:

  • authentication based on a "remember me" cookie.
  • authentication based on your session.
  • authentication using a HTTP basic or HTTP digest header.

You could listen on the security.interactive_login event, for example, in order to give your user a welcome flash message every time they log in.

The security.switch_user event is triggered every time you activate the switch_user firewall listener.

http://symfony.com/doc/current/components/security/authentication.html#security-events

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top