Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Redirect to login after session has expired on ajax request

If I log in to my web app, wait for the session to expire, then make an ajax request with a form in my web app I get the following error show up in the console:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Ideally what would happen is a redirect to the login page or an error message shows up under the form that fired the ajax request (i.e. something meaningful to the user). It may be worth noting I already have the client side code to throw up errors to show an error message to the user if they make a validation error on the form.

I believe I have an idea how to check if the session is expired and return something useful to the user telling them to login but I'm unsure how I'd implement this globally. So I'm wondering is it possible to handle this issue globally from the back end in Laravel and (or) do I need to write some logic for each ajax request to catch the issue to show an error message client side?

I'm using Laravel and Javascript/JQuery. Thanks for any help!

like image 943
haakym Avatar asked Mar 16 '23 17:03

haakym


2 Answers

Here's the quick solution for your case:

Controller (e.g. AuthController.php):

/**
 * Check user session.
 *
 * @return Response
 */
public function checkSession()
{
    return Response::json(['guest' => Auth::guest()]);
}

Also, probably it will be needed to add this method name to ignore by guest middleware:

$this->middleware('guest', ['except' => ['logout', 'checkSession']]);

Route:

Route::get('check-session', 'Auth\AuthController@checkSession');

Layout (JS part), only for signed in users:

@if (Auth::user())
  <script>
    $(function() {
      setInterval(function checkSession() {
        $.get('/check-session', function(data) {
          // if session was expired
          if (data.guest) {
            // redirect to login page
            // location.assign('/auth/login');

            // or, may be better, just reload page
            location.reload();
          }
        });
      }, 60000); // every minute
    });
  </script>
@endif
like image 71
Limon Monte Avatar answered Mar 26 '23 03:03

Limon Monte


use Middleware

Middleware:

<?php namespace App\Http\Middleware;

class OldMiddleware {

    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       if(!**condition to check login**)
       {
         // if session is expired
          return response()->json(['message' => 'Forbidden!'],403);
       }

        return $next($request);
    }

}

Route:

Route::group(['middleware' => '\App\Http\Middleware\OldMiddleware'], function(){
    //put the routes which needs authentication to complete
});

View:

$.ajax({

     type: 'post',
     url: {{route('someroute')}}
    //etc etc

}).done(function(data){
    //do if request succeeds
}).fail(function(x,y,z){
    //show error message or redirect since it is failed.
});
like image 28
itachi Avatar answered Mar 26 '23 01:03

itachi