Вход в Symfony2 AJAX

У меня есть пример, в котором я пытаюсь создать логин AJAX с помощью Symfony2 и FOSUserBundle. Я устанавливаю свои собственные success_handler и failure_handler в разделе form_login в моем файле security.yml .

Вот класс:

class AjaxAuthenticationListener implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{  
    /**
     * This is called when an interactive authentication attempt succeeds. This
     * is called by authentication listeners inheriting from
     * AbstractAuthenticationListener.
     *
     * @see \Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener
     * @param Request        $request
     * @param TokenInterface $token
     * @return Response the response to return
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => true);
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
    }

    /**
     * This is called when an interactive authentication attempt fails. This is
     * called by authentication listeners inheriting from
     * AbstractAuthenticationListener.
     *
     * @param Request                 $request
     * @param AuthenticationException $exception    
     * @return Response the response to return
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => false, 'message' => $exception->getMessage());
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
    }
}

Он отлично подходит для обработки как успешных, так и неудачных попыток входа в систему AJAX. Однако при включении я не могу войти в систему с помощью стандартного метода POST (не AJAX).Я получаю следующую ошибку:

Catchable Fatal Error: Аргумент 1, переданный в Symfony \ Component \ HttpKernel \ Event \ GetResponseEvent :: setResponse (), должен быть экземпляром Symfony \ Component \ HttpFoundation \ Response, задано значение null

I я бы хотел, чтобы мои переопределения onAuthenticationSuccess и onAuthenticationFailure выполнялись только для XmlHttpRequests (запросы AJAX) и просто возвращали выполнение исходному обработчику, если нет.

Есть ли способ сделать это?

TL; DR Я хочу, чтобы AJAX запрашивал попытки входа в систему, чтобы вернуть ответ JSON в случае успеха или неудачи, но я хочу, чтобы это не влияло на стандартный вход через форму POST.

43
задан j0k 20 September 2012 в 11:33
поделиться