neemo
neemo

Reputation: 1

Redirect Loop Laravel 5.1 in Fortrabbit

I have deployed a laravel app to fortrabbit. The deployed app is a simple app just to test authentication and middleware ('auth' and 'guest'). I have tried the app in localhost, the authentication and middleware worked fine. When I tried my app in fortrabbit, the authentication worked properly but there was an issue with the middleware. I get

This webpage has a redirect loop, ERR_TOO_MANY_REDIRECTS

every time I log into the home page.

routes.php:

Route::get('/','UserController@getIndex');

Route::group(['middleware' => 'guest'], function() {

   Route::get('login','UserController@getLogin');
   Route::post('login','UserController@postLogin');

   Route::get('register','UserController@getRegister');
   Route::post('register','UserController@postRegister');

});

Route::group(['middleware' => 'auth'], function() {

   Route::get('home','MainController@getHome');
   Route::get('logout','MainController@logout');

});

Authenticate.php for 'auth' middleware:

public function handle($request, Closure $next)
{

    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else{
            return redirect()->guest('/login');
    }

    return $next($request);
}

RedirectIfAuthenticated.php for 'guest' middleware:

public function handle($request, Closure $next)
{
    if ($this->auth->check()) {
        return redirect('home');
    }

    return $next($request);
}

Is there any file/setting in fortrabbit that I have to configure to run this app properly?

Upvotes: 0

Views: 191

Answers (2)

neemo
neemo

Reputation: 1

After modifying config/cache.php with Fortrabbit memcache configuration (link), we should change not only the value of CACHE_DRIVER but also the SESSION_DRIVER to memcached in .env file

Upvotes: 0

Swimburger
Swimburger

Reputation: 7184

Your auth middleware looks off to me.
If guest() do this, if not guest redirect to login. Shouldn't you be redirected to login if you are a guest on a page where guests are not allowed?
You're in an endless loop because once you login, you are no longer a guest, so you get redirected to 'home', which triggers the 'auth' that's off and redirects you to login, which triggers 'guest' which redirects you ...

I think you're auth middleware should look like this, source from Laravel on Github

public function handle($request, Closure $next)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('auth/login');
        }
    }
    return $next($request);
}

Upvotes: 0

Related Questions