Last active
December 17, 2015 06:56
-
-
Save smottt/1075753 to your computer and use it in GitHub Desktop.
Symfony2 Custom Login Even Listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 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
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
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.