Search code examples
phpsymfonyfosuserbundle

Can't do redirect after login


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;
}

Solution

  • 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