Redirect if the user is logged in
symfony
Solution
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 ]
Problem
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 achieve now is to have the user redirected to their account from any page they may be at if they are logged in. This includes: - if they get back to the login page - if they get back to the registration page - if they go to the homepage of the website - once they confirm their email - once they reset their password Basically the code would be something like this: ``` $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) { return $this->redirect($this->generateUrl($accountRouteName)); } } ``` The problem is I don't know where that code should go. It should be executed for any request. In Symfony 1 I would have used a filter.