1

im using fosuserbundle in symfony 3.4. i wanted to redirect after login the problem is can't rediret after login it stays always in login page even i'm alerdy log in here you can find my code (https://gist.github.com/Bakhshi-Faisal/b0eda6075af53130b2e6513059e07802)

i tried the code below

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $roles = $token->getRoles();

    $rolesTab = array_map(function ($role) {
        return $role->getRole();
    }, $roles);

    if (in_array('ROLE_COMPTABLE', $rolesTab, true)) {
        // c'est un aministrateur : on le redirige vers l'espace admin
        $redirection = new RedirectResponse($this->router->generate('comptable'));
    } else {
      
        $redirection = new RedirectResponse($this->router->generate('visiteur'));
    }

    return $redirection;
}
Astronaute
  • 219
  • 3
  • 19
  • Have you made sure that the given code is executed? How did you debug your problem further? – Nico Haase Apr 15 '19 at 14:48
  • well i think SecurityControler in the fosuserBundle prevent my function to be execute and i don't get any error so my function works but can't be executed because of SecurityController @NicoHaase – Astronaute Apr 15 '19 at 14:57
  • Well, the key point is: according to all that code, you have just defined some method `onAuthenticationSuccess` without any more context. How should Symfony guess that you want to execute it at some specific point in time? – Nico Haase Apr 15 '19 at 15:13
  • Have a look at https://stackoverflow.com/questions/41440417/symfony-redirect-after-login-with-condition-on-user, it shows two ways of solving your problem – Nico Haase Apr 15 '19 at 15:14
  • You messed up a bit when creating you LoginHandler (and not Controller) try to follow this answer, it's doing exactly what you're trying : https://stackoverflow.com/a/31167310/1259367 – Snroki Apr 15 '19 at 15:17
  • okay let me take a loot Thank you :D – Astronaute Apr 15 '19 at 15:32
  • still same problem even after i'm log in it stays in login page 0 redirects i did exactly like the link you said to me. – Astronaute Apr 15 '19 at 15:41

2 Answers2

0

Staying in the same page mean you don't actually access your code.

You should handle this in a listner, not in a controller.

Your class LoginController should be called LoginListener and be in some event folder.

A controller is only used to contain action. This could be your problem.

Here is an exemple for redirect user depending of the pages he try to access if he is connected or not:

<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Model\User;

/**
 * Class RedirectUserListener
 * @package AppBundle\EventListener
 */
class RedirectUserListener
{
private $tokenStorage;
private $router;

/**
 * RedirectUserListener constructor.
 * @param TokenStorageInterface $tokenStorage
 * @param RouterInterface $router
 */
public function __construct(TokenStorageInterface $tokenStorage, RouterInterface $router)
{
    $this->tokenStorage = $tokenStorage;
    $this->router = $router;
}

/**
 * @param GetResponseEvent $event
 */
public function onKernelRequest(GetResponseEvent $event)
{
    if ($this->isUserLogged() && $event->isMasterRequest()) {
        /** @var \AppBundle\Entity\User $user */
        $user = $this->tokenStorage->getToken()->getUser();
        if (empty($user->getModifiedBy())) {
            $user->setModifiedBy($user);
        }
        $currentRoute = $event->getRequest()->attributes->get('_route');
        if ($this->isAuthenticatedUserOnAnonymousPage($currentRoute)) {
            $response = new RedirectResponse($this->router->generate('app_default_index'));
            $event->setResponse($response);
        }
    }
}


/**
 * @return bool
 */
protected function isUserLogged()
{
    $token = $this->tokenStorage->getToken();
    if (is_null($token)) {
        return false;
    }
    $user = $token->getUser();
    return $user instanceof User;
}

/**
 * @param $currentRoute
 * @return bool
 */
protected function isAuthenticatedUserOnAnonymousPage($currentRoute)
{
    return in_array(
        $currentRoute,
        ['fos_user_security_login', 'fos_user_resetting_request', 

'app_user_registration']
        );
    }
}

And in services.yml:

app.tokens.action_listener:
    class: AppBundle\EventListener\RedirectUserListener
    arguments:
        - "@security.token_storage"
        - "@router"
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Florent Cardot
  • 1,400
  • 1
  • 10
  • 19
0

i found out another way to redirect after login according to user role

 /**
     * @Route("/accueil")
     */
    public function redirectAction()
    {
        $authChecker = $this->container->get('security.authorization_checker');

        if ($authChecker->isGranted('ROLE_COMPTABLE')) {
            return $this->render('comptes/comptable/comptable.html.twig', array());

        } elseif ($authChecker->isGranted('ROLE_VISITEUR')) {
            return $this->render('comptes/visiteur/visiteur.html.twig',array());

        } else {
            return $this->render('userLogin.html.twig', array());
        }
    }

and in security.yml in firewalls section and in main section i add this always_use_default_target_path: false and default_target_path: /accueil and it works perfectly. one thing i might forgot to tell i'm using fosuserbundle my function works well with it

Astronaute
  • 219
  • 3
  • 19