Created
June 8, 2011 19:20
-
-
Save xanf/1015146 to your computer and use it in GitHub Desktop.
AJAX auth errors listener for Symfony2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\ProdrepHelperBundle\Component\Event; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\Security\Core\Exception\AuthenticationException; | |
use Symfony\Component\Security\Core\Exception\AccessDeniedException; | |
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; | |
/** | |
*/ | |
class AjaxAuthenticationListener | |
{ | |
/** | |
* Handles security related exceptions. | |
* | |
* @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance | |
*/ | |
public function onCoreException(GetResponseForExceptionEvent $event) | |
{ | |
$exception = $event->getException(); | |
$request = $event->getRequest(); | |
if ($request->isXmlHttpRequest()) { | |
if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException) { | |
$event->setResponse(new Response('', 403)); | |
} | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function() { | |
$(document).ajaxError(function (event, jqXHR) { | |
if (403 === jqXHR.status) { | |
window.location.reload(); | |
} | |
}); | |
}); | |
Thank you! If anyone would just have an easy solution for global error handling (of just authentication/authorization errors) for superagent...
I am implementing the same solution, I am using jquery Datatables in my application. When I return 403 error, before logging out, it gives a jquery error in alert, and when user clicks OK, session logs out.
Is there a way to do it without that alert coming??
Note that returning it should return an http code 401 instead to be conform with the http standard
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a really helpful Gist! One question though - would it not be pertinent to implement a distinction between the user not being logged in VS being logged in and not having permission to access the URL requested?
Currently, if the user performs an Ajax request to a URL for which they are not authorised then they would experience a page reload which would not be ideal.