Laravel Redirect If Authenticated middleware

Gammer picture Gammer · Sep 13, 2017 · Viewed 10.2k times · Source

I have three type of users for the application, Each one have its own dashboard. I need a check that adminor any other user cannot see another user dashboard.

There is a middleware RedirectIfAuthenticated :

public function handle($request, Closure $next, $guard = null){

    if (Auth::guard($guard)->check() && auth()->user()->type == 'admin'){
        return redirect('/admin');
    }

    if (Auth::guard($guard)->check() && auth()->user()->type == 'author'){
        return redirect('/author');
    }

    if (Auth::guard($guard)->check() && auth()->user()->type == 'client'){
        return redirect('/client');
    }
}

Its under guest middleware.

The above code seems good to me but when i tests it, The browser says Too many redirects.

What am i doing wrong, What will be the best way to handle it.

Answer

apokryfos picture apokryfos · Sep 13, 2017

You may have misunderstood the purpose of that middleware. The purpose of RedirectIfAuthenticated is to redirect a user to their default authenticated page. It is not meant to block unauthenticated/unauthorised users from accessing specific areas.

What you need to do is redirect if not authorised. Since this is a simple case you can just have a middleware:

class RequireRole {
     public function handle($request, Closure $next, $role) {
          abort_unless(auth()->check() && auth()->user()->type == $role, 403, "You don't have permissions to access this area");
           return $next($request);
     }
}

Then register this middleware in your Kernel.php

protected $routeMiddleware = [
        //Other middleware
        "requirerole" => RequireRole::class
];

Then you can use it in your routes e.g.

Route::get('/admin', function () { /* action */ })->middleware("requirerole:admin");

However if you find yourself in need of more complex rules then take a look at Authorization