Skip to content

Instantly share code, notes, and snippets.

@smottt
Last active December 17, 2015 06:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smottt/1075753 to your computer and use it in GitHub Desktop.
Save smottt/1075753 to your computer and use it in GitHub Desktop.
Symfony2 Custom Login Even Listener
<?php
namespace Acme\UserBundle\Listener;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.1.0+
// 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 InteractiveLoginEvent $event
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $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 = $event->getAuthenticationToken()->getUser();
// ...
}
}
@phamngoctan
Copy link

Really useful post. But I don't known how to redirect to the specific page? Can you help me in this problem? Thank you very much.

@iuli-dercaci
Copy link

@phamngoctan as they tell in a documentation you need to setup successful login redirects in your security.yml
firewalls:
firewall_name:
...
default_target_path: your_path_or_pathname_here
...

hope this helps

@TeLiXj
Copy link

TeLiXj commented Dec 17, 2015

To redirect you must use the event dispatcher and the router service

$this->getDispatcher()->addListener(KernelEvents::RESPONSE, function(FilterResponseEvent $event) {
    $event->setResponse(new RedirectResponse($this->router->generate("your_path")));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment