Skip to content
Advertisement

Symfony2/FosUserBundle – Get the previous route before Login

I’m creating an E-commerce app and I’m building a custom redirection with the Handler.

Let’s say my user is on his shopping’s cart and he is not logged. He validates his cart to continue the buying process. In this situation, My app redirect the user to the login page. But when He is finally logged I would like to redirect him to the previous route (ie the cart page). (Sorry for my poor english, I hope you will understand what I say)

This is my AuthentificationSuccessHandler :

class AuthentificationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
   protected $router;
   protected $security;

/**
 * AfterLoginRedirection constructor.
 * @param Router $router
 * @param AuthorizationChecker $security
 */
public function __construct(Router $router, AuthorizationChecker $security)
{
    $this->router = $router;
    $this->security = $security;
}


public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $session = $request->getSession();
    if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
        $response = new RedirectResponse($this->router->generate('_homepage_admin'));
    } else {
        $referer_url = $request->headers->get('referer');

        $response = new RedirectResponse($referer_url);
    }
    $session->getFlashBag()->add('success', 'Connexion réussi !');
    return $response;
}

As you can see, I use headers->get('referer'); like I saw in the documentation, but this is not working. The user is redirect to the login page (but the authentification works fine)

So i’m stuck right now..

Tell me if you need more code to help me for my issue.

Any clues or advices ?

Thanks.

Advertisement

Answer

Well, I found a solution, I don’t know if it’s the better way but at least it’s works.

So : into my listener I storage a attribute in the session’s object, This attribue is update if the user is on a path in my list.

My Listener :

class RedirectionListener
{

/**
 * RedirectionListener constructor.
 * @param ContainerInterface $container
 * @param Session $session
 */
public function __construct(ContainerInterface $container, Session $session)
{
    $this->session = $session ;
    $this->router = $container->get('router') ;
    $this->securityContext = $container->get('security.context') ;
}

/**
 * @param GetResponseEvent $event
 */
public function onKernelRequest(GetResponseEvent $event){
    $request        = $event->getRequest() ;
    $list_route     = array('_cart', '_category', '_delivery','_validate','_product','_homepage');
    $route          = $request->attributes->get('_route') ;
    $route_params   = $request->attributes->get('_route_params') ;

    if(in_array($route, $list_route)){
        $this->setRouteSession($request, $route, $route_params);
    }
    if($route == "_delivery" || $route =="_validate"){
        if ($this->session->has('cart')){
            if(count($this->session->get('cart')) == 0){
                $this->session->getFlashBag()->add('info', 'Votre panier étant vide, vous ne pouvez pas continuer le processus d'achat ');
                $event->setResponse(new RedirectResponse($this->router->generate('_cart')));
            }
        }
        if(!is_object($this->securityContext->getToken()->getUser())){
            $this->session->getFlashBag()->add('info', 'Vous devez vous identifier');
            $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
        }
    }
}

/**
 * @param $request
 * @param $route
 * @param null $param
 */
private function setRouteSession($request, $route, $param){
    $session = $request->getSession() ;
    $session->set('lastPath', array(
        'route' => $route,
        'params' => $param
    ));
  }
}

My Handler :

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $session = $request->getSession();
    if(!$session->has('lastPath')){
        $route = '_homepage';
    } else {
        $route = $session->get('lastPath') ;
    }

    if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
        $response = new RedirectResponse($this->router->generate('_homepage_admin'));
    } else {
        if($route['params'] != null){
            $response = new RedirectResponse($this->router->generate($route['route'],$route['params']));
        } else {
            $response = new RedirectResponse($this->router->generate($route['route']));
        }

    }
    $session->getFlashBag()->add('success', 'Connexion réussi !');
    return $response;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement