When a user's session expires and they're on a page that uses ajax requests, you need to set up something to gracefully handle reauthenticating. In this example, we prompt the user and redirect them to the login page.
For Laravel, in your auth filter:
<?php
Route::filter('auth', function()
{
if (Auth::guest()) {
if (Request::ajax()) {
return Response::json(false, 401);
} else {
return Redirect::guest('login');
}
}
});
In your app/global javascript:
/**
* This monitors all AJAX calls that have an error response. If a user's
* session has expired, then the system will return a 401 status,
* "Unauthorized", which will trigger this listener and so prompt the user if
* they'd like to be redirected to the login page.
*/
$(document).ajaxError(function(event, jqxhr, settings, exception) {
if (exception == 'Unauthorized') {
// Prompt user if they'd like to be redirected to the login page
var redirect = confirm("You're session has expired. Would you like to be redirected to the login page?");
// If the answer is yes
if (redirect) {
// Redirect
window.location = '/login';
}
}
});
A better solution would be to throw up a modal with the login page and reauthenticate without redirecting.
Thanks, I was looking for something like this. Helped a lot.