Search code examples
laravelauthenticationadmin

Laravel isolate admin login


I've made a CMS without user front-end. Only admin panel is active, and I would like to restrict anyone who is not admin from logging in.

I have made an isAdmin() method in User model:

public function isAdmin()
    {
        if ($this->roles->first()->name == 'Administrator') {
            return true;
        }else return false;
    }

Which works fine (I have tested the feedback).

Everything outside the Route::auth(); is protected with middleware:

Route::group(['middleware' => ['auth', 'admin']], function () {
   ...
});

I have registered 'admin' middleware in Kernel, and it's handle method is:

public function handle($request, Closure $next)
    {
        if(Auth::user()->isAdmin()){
            return redirect('user');
        }else return redirect('login');
    }

But the problem I have is that I get ERR_TOO_MANY_REDIRECTS, and something doesn't work as it should? Does anyone know why?

EDIT:

Logic suggests that when middleware is triggered that each request will be redirected to user, so i changed it to:

public function handle($request, Closure $next)
    {
        if(Auth::user()->isAdmin()){
            return $next($request);
        }else return redirect('login');
    }

Which works for admin users, but for other users, they don't get redirected, but I get the ERR_TOO_MANY_REDIRECTS again


Solution

  • I've figured out that RedirectIfAuthenticated is giving me problems because it is redirecting to home (which is protected with middleware also), and then the middleware is redirecting it to login, and it never gets out of the route, so my solution was to logout user in order to break the started session:

    public function handle($request, Closure $next)
        {
            if(Auth::user()->isAdmin()){
                return $next($request);
            }else{
                Auth::logout();
                return redirect('login');
            }
        }