0
votes

I'm using an internal API to authenticate in Laravel, and I created a middleware to test if the user is logged in using session. The middleware work in the point of redirecting to the login route, but it keeps trying to redirect until I see ERR_TOO_MANY_REDIRECTS. It's the first time that I use a different way to authenticate, I removed de guest and auth middleware that a I used before.

This are my routes:

Route::get('/login', 'ApiController@index')->name('login')->middleware('psa');
Route::post('/logout', 'ApiController@destroy')->name('logout');
Route::post('/auth', 'ApiController@login')->name('psaAuth');

The middleware:

public function handle($request, Closure $next)
    {
        if(! $request->session()->exists('login')){
            return redirect('/login');
        }else{
            return redirect('/');
        }

        return $next($request);
    }

Any ideas why this is happening?

1
You can check you log file located inside storage/logs/laravel*.log to see if there are any errors. Also provide controller method bodies to get helpNoob Coder
Your middleware is for the route /login and if login session doesnt exist, you are redirecting it to again which is obviously a loop.Cerlin

1 Answers

1
votes

Since you are applying psa middleware only for /login, your code should be something like below

public function handle($request, Closure $next)
{
    if($request->session()->exists('login')){
        return redirect('/');
        // If session exist, take him to home page
    }

    // Else let him stay in the login page for login.
    return $next($request);
}