Skip to content

Instantly share code, notes, and snippets.

@flackend
Last active October 20, 2018 12:44
Show Gist options
  • Save flackend/9517696 to your computer and use it in GitHub Desktop.
Save flackend/9517696 to your computer and use it in GitHub Desktop.
Example solution to handling re-authentication after session expires for AJAX requests.

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.

demo

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.

@incomestore
Copy link

Thanks, I was looking for something like this. Helped a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment