AuthenticationFailureHandler.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Muzich\CoreBundle\Security\Http\Authentication;
  3. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\Routing\RouterInterface;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Bundle\FrameworkBundle\Translation\Translator;
  10. use Doctrine\ORM\EntityManager;
  11. use Muzich\CoreBundle\Entity\User;
  12. /**
  13. * Custom authentication success handler
  14. */
  15. class AuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
  16. {
  17. private $router;
  18. private $em;
  19. private $translator;
  20. /**
  21. * Constructor
  22. * @param RouterInterface $router
  23. * @param EntityManager $em
  24. */
  25. public function __construct(RouterInterface $router, EntityManager $em, Translator $translator)
  26. {
  27. $this->translator = $translator;
  28. $this->router = $router;
  29. $this->em = $em;
  30. }
  31. function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  32. {
  33. if ($request->isXmlHttpRequest())
  34. {
  35. $response = new Response(json_encode($this->getResponseParameters($request)));
  36. $response->headers->set('Content-Type', 'application/json; charset=utf-8');
  37. return $response;
  38. }
  39. return new RedirectResponse($this->router->generate('home'));
  40. }
  41. protected function getResponseParameters(Request $request)
  42. {
  43. $session = $request->getSession();
  44. return array(
  45. 'status' => 'error',
  46. 'data' => array(
  47. 'error' => $this->translator->trans('login.fail', array(), 'users')
  48. )
  49. );
  50. }
  51. }