I am building a web application with Symfony 2, using the FOSUserBundle bundle.
Users create an account, login and start using the application.
What I want to
I found the solution myself:
<?php
namespace Danyuki\UserBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LoggedInUserListener
{
private $router;
private $container;
public function __construct($router, $container)
{
$this->router = $router;
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
$container = $this->container;
$accountRouteName = "DanyukiWebappBundle_account";
if( $container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
// authenticated (NON anonymous)
$routeName = $container->get('request')->get('_route');
if ($routeName != $accountRouteName) {
$url = $this->router->generate($accountRouteName);
$event->setResponse(new RedirectResponse($url));
}
}
}
}
And then, in the services.yml file of my bundle:
services:
kernel.listener.logged_in_user_listener:
class: Danyuki\UserBundle\Listener\LoggedInUserListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
arguments: [ @router, @service_container ]
You can also do this solution if you want to just check once:
There is an event triggered each time there's a successful login being done. The event is named:
security.interactive_login
In order to subscribe to this event, you have to create a service container with your created class let's say "LoginListener.php" and inject the tag "kernel.even_listener" with the event "security.interactive_login":
<service id="mylogin.success.listener" class="path\to\class\LoginListener">
<tag name="kernel.event_listener" event="security.interactive_login" method="onLoginSuccess" />
</service>
in LoginListener:
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
public function onLoginSuccess(InteractiveLoginEvent $event) {
if ($this->_security->isGranted('IS_AUTHENTICATED_FULLY')) {
//your code here...
}
}
you can also add other dependencies and inject it to the constructor, in my case I had to inject security, session and container:
public function __construct(SecurityContext $security, Session $session, ContainerInterface $container) {
}