简体   繁体   中英

Protecting Routes with Role Permissions using middleware Laravel

I have a multilevel members website and need to protect my routes in the web.php file in Laravel 5.5.

I have a column on my users table called role_id .

In role_id is the following values

  • NULL (For New Users)
  • 1 (For Owner)
  • 2 (For Admin)
  • 3 (For Moderators)
  • 4 (For Banned Users)

I was trying to do it with a simple IF statement

if (Auth::user()->role_id != '2'):
    return view('home');
    else:
//ADMIN ROUTES
    Route::get('/admin','AdminController@index')->name('admin');
endif;

if (Auth::user()->role_id != '1'):
    return view('home');
    else:
//OWNER ROUTES
    Route::get('/admin','OwnerController@index')->name('owner');
endif;
ETC....

But get Error Trying to get property of non-object. Also probably not the best way to do that.

So I read about doing it with MIDDLEWARE like this: (Looks much better)

Route::group(['middleware' => ['auth', 'admin']], function() {
    // put all your admin routes here
});

Route::group(['middleware' => ['auth', 'owner']], function() {
    // put all your owner user routes here
});

But it didn't explain how to add the Middleware. Would I have to create 5 different Middleware files for each group similar to file I found:

use Illuminate\Contracts\Auth\Guard;

class Admin
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        if($this->auth->user()->role_id != '2') {
            return redirect()->view('home');
        }
        return $next($request);        
    }
}

Could someone lend a helping hand and explain how to write the correct middleware to achieve this?

Error Trying to get property of non-object. Can be found if user not logged in yet.

Before u check

if (Auth::user()->role_id != '2'):

u should make sure that user is logged in with

Auth::check()

first...

Like this example:

 Route::get('/cart/payment', 'CartController@getcartpayment')->middleware('checkAuth');


 $user = Sentinel::findById($user_id);
        $role= $user->role();

web.php

Route::group(['middleware' => ['auth', 'admin']], function() {
    Route::get('/admin/dashboard', function(){
        return view('admin.dashboard');
    });
});

into protected $routeMiddleware of Kernel.php

'admin'      => \App\Http\Middleware\AdminMiddleware::class,

AdminMiddleware.php

$user = Auth::user();
if($user->role == 'admin'){
    return $next($request);
} else
    // abort(403, 'Wrong Accept Header');
    return new Response(view('notauthorized')->with('role', 'admin'));

}

admin, moderators, owner, banned_user will be value of user_type/role column of user table. or you can use user_type_id or role_id instead of user_type_name or role_type

Don't forget to add

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;

just under the

use Closure; 

of your Middleware

You can also do it with other ways like Gate, let me know if you need it. :)

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