Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling default handler from a custom authentication handler [duplicate]

Tags:

symfony

Possible Duplicate:
Symfony2 AJAX Login

I have implemented a custom authentication handler service to handle AJAX login requests, as suggested here: https://stackoverflow.com/a/8312188/267705

But how can I handle normal login requests? It would be nice to call the default behavior, but I don't know and haven't found how to do it.

like image 883
David Morales Avatar asked Dec 28 '11 09:12

David Morales


1 Answers

This is one of the ways to achieve what you want:

namespace YourVendor\UserBundle\Handler;

// "use" statements here

class AuthenticationHandler
implements AuthenticationSuccessHandlerInterface,
           AuthenticationFailureHandlerInterface
{
    private $router;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            // Handle XHR here
        } else {
            // If the user tried to access a protected resource and was forces to login
            // redirect him back to that resource
            if ($targetPath = $request->getSession()->get('_security.target_path')) {
                $url = $targetPath;
            } else {
                // Otherwise, redirect him to wherever you want
                $url = $this->router->generate('user_view', array(
                    'nickname' => $token->getUser()->getNickname()
                ));
            }

            return new RedirectResponse($url);
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            // Handle XHR here
        } else {
            // Create a flash message with the authentication error message
            $request->getSession()->setFlash('error', $exception->getMessage());
            $url = $this->router->generate('user_login');

            return new RedirectResponse($url);
        }
    }
}

Enjoy. ;)

like image 110
Elnur Abdurrakhimov Avatar answered Sep 30 '22 02:09

Elnur Abdurrakhimov