简体   繁体   中英

protecting admin and user routes laravel 5

I have a common login for both admin and user. But I have created a roles in my table which looks like:

user_id      role_id
1              2
2              1
3              2

where role_id 1 refers to the admin and role_id 2 refers to the user. I can attach roles to the different user as well. Now what I want is, I want to protect all admin routes and user routes.

For example, I don't want user to get any access that is meant for admin. For now, I can check whether the user is admin or user like if (Auth::user()->hasRole('admin')) or if (Auth::user()->hasRole('user')) .

How should I separate my user routes from admin routes in this case? Should I make my own middleware and implement? If so, how to implement it correctly?

Create two middleware, for admin you can do:

<?php namespace App\Http\Middleware;

use Auth;
use Illuminate\Contracts\Routing\Middleware;

class CheckAdmin implements Middleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (Auth::user()->hasRole('admin'))
        {
            return $next($request);

        }

        throw new \Exception("Unauthorized");
    }

}

Then enable this middleware in App\\Http\\Kernel

protected $routeMiddleware = [
    'auth' = 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',

    'checkAdmin' => 'App\Http\Middleware\CheckAdmin',
];

You can use your CheckAdmin middlware in the routes.php file or in the constructor of your Controller

In routes.php you can do:

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

    Route::get('admin/profile', function () {
        // Uses CheckAdmin Middleware
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM