Route restrictions with laravel

0

Good afternoon.

How can I make a restriction of some specific routes with Laravel?

For example. If I have an e-commerce I will have the admin users who will be able to access the routes of the administrative panel and all the other routes of the site. But I will also have the users / clients say so. They will be able to access the routes of the site and their login in the client area, but they will not be able to access the routes of the administrative panel.

Another example:

Routes (/ admin / home) (/ admin / products) (/ admin / edit-products) - > These routes only administrators will be able to access.

(/ my-purchases) (/ my-cart) - > These routes clients and administrators can access.

But if I do the same authentication for users / clients and for administrators, I will not be able to do this restriction. If the guy is logged in he will be able to access any route on my system, regardless of whether he is an administrator or a client.

Understand? Can you help me?

    
asked by anonymous 02.05.2018 / 18:47

1 answer

2

You can use Laravel's Middlewares, you create a specific rule and create a grouping of routes for example:

Route::group(['middleware' => ['auth','check_permissions']], function () {
   // TODAS SUAS ROTAS QUE VÃO SER VALIDADAS POR ESSE MIDDLEWARE
})

In this grouping, I'm saying that it has to be authenticated and abide by the rules of% CheckPermissions

My CheckPermissions file:

class CheckPermissions {

     /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request $request
       * @param  \Closure $next
       * @return mixed
     */
    public function handle ($request, \Closure $next)
    {
        $isAdmin = Auth::user()->is_admin;

        if ($isAdmin) {
            return $next($request);
        }
        return redirect()->route('home');
    }

}

It will check if the user is admin, if it is not redirected to home, otherwise it goes to the route being requested.

You have to add your middleware to the Kernel.php file in the variable Middleware :

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'check_permissions' => CheckPermissions::class
    ];

If you have questions, follow the documentation link:

link

    
02.05.2018 / 19:26