ILoveBaymax
ILoveBaymax

Reputation: 267

Laravel 5.0:: Middleware Issue (ERR_TOO_MANY_REDIRECTS error)

I am an absolute beginner of Laravel framework. I am dealing with a middleware issue.

With the authenticate.php and __construct function in AdminController.php combined below, I cannot log in and have to deal with ERR_TOO_MANY_REDIRECTS error.

Has anyone ever encountered this kind of problem? If you have, could me give any advice to solve this issue?

English is not my first language so if this post does not make sense or you need more information, please leave your comments! Any advice would be appreciated! Thanks in advance!

Authenticate.php

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

   if ($this->whoIsLoggedIn() == 'instructor'){
        return redirect('/instructor/home');
    } elseif ($this->whoIsLoggedIn() == 'admin') {
        return redirect('/admin/home');
    } elseif ($this->whoIsLoggedIn() == 'student') {
        return redirect('/student/home');
    } elseif($this->whoIsLoggedIn() == 'unknown'){
        return redirect('/auth/login');
    }

     return $next($request);
}

public function whoIsLoggedIn(){

    $identity = '';

    foreach (\Auth::user()->roles as $role) {
        if ($role->name == 'admin') {
            return $identity = 'admin';
        } else if ($role->name == 'instructor')  {
            return $identity = 'instructor';
        } else if ($role->name == 'student'){
            return $identity = 'student';
        } else {
            return $identity = 'unknown';
        }
    }
}

AdminController.php

public function __construct(){
    $this->middleware('auth');
}

Upvotes: 0

Views: 1301

Answers (1)

Denis Mysenko
Denis Mysenko

Reputation: 6534

If you look carefully, your code actually implements an infinite redirect loop - once user is logged in, your middleware class will always redirect the user further. Since the next page probably has the same middleware applied - user will be redirected again and again and again.

At some point, your middleware is supposed to just call the next middleware in the chain:

return $next($request);

That will finish the middleware chain, and, if everything is fine, finally give the control to your page.

What you are trying to implement (default starting page for authenticated users) should probably be in your AuthController instead of this middleware. This middleware doesn't know whether the user is just logging in or has been authenticated for a while now.

I suggest you move your redirect conditions to postLogin() method of AuthController so that it will happen only once – when the user actually logs in. You can pretty much copy paste most of the code.

Upvotes: 1

Related Questions