phpsymfonysymfony5

Not redirecting to User/Admin page after logging in


public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
    if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
        return new RedirectResponse($targetPath);
    }

    $user = $token->getUser();
    
    if (!$user instanceof User) {
        return new RedirectResponse($this->urlGenerator->generate('app_error'));
    }

    
    if (in_array('ROLE_ADMIN', $user->getRoles())) {
        return new RedirectResponse($this->urlGenerator->generate('app_admin'));
    } else {
        return new RedirectResponse($this->urlGenerator->generate('app_user'));
    }
}

I was expecting that after logging in I would be rediretcted to the admin or user page depending on the role. But it keeps bringing me to the homepage and give errors.

What am I doing wrong?


Solution

  • This code is not checking if $user is an instance of the expected User class. This can cause an error if $token->getUser() returns something other than a User instance that doesn't have the getRoles() method, and results in a fatal error.

    Here is how you can fix this mistake:

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
        {
            if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
                return new RedirectResponse($targetPath);
            }
    
            // Get the authenticated user
            $user = $token->getUser();
    
            // Check the user's role
            if (in_array('ROLE_ADMIN', $user->getRoles())) {
                // Redirect to the app_admin page
                return new RedirectResponse($this->urlGenerator->generate('app_admin'));
            } else {
                // Redirect to the app_user page
                return new RedirectResponse($this->urlGenerator->generate('app_user'));
            }
        }