Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel route filter to check user roles

I am building a restful api in laravel 4 where there are users with different types of permission. I want to restrict access to different routes depending on the user role (which is saved in the user table in db)

How would I do that? Here is what I have so far (it's not working so far).

filters.php

//allows backend api access depending on the user's role once they are logged in
Route::filter('role', function()
{ 
return Auth::user()->role;
}); 

routes.php

 Route::group(array('before' => 'role'), function($role) {
 if($role==1){
        Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
        Route::post('customer/create', 'CustomerController@create');
        Route::put('customer/update/{id}', 'CustomerController@update');
 }

    });

Is it possible that I'm writing the syntax wrong for a "group filter"?

like image 780
user1424508 Avatar asked Dec 27 '13 03:12

user1424508


2 Answers

Try the following:

filters.php

Route::filter('role', function()
{ 
  if ( Auth::user()->role !==1) {
     // do something
     return Redirect::to('/'); 
   }
}); 

routes.php

 Route::group(array('before' => 'role'), function() {
        Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
        Route::post('customer/create', 'CustomerController@create');
        Route::put('customer/update/{id}', 'CustomerController@update');


});
like image 173
Anam Avatar answered Oct 15 '22 06:10

Anam


There are different ways you could implement this, for starts Route filters accept arguments:

Route::filter('role', function($route, $request, $value)
{
  //
});

Route::get('someurl', array('before' => 'role:admin', function()
{
  //
}));

The above will inject admin in your Route::filter, accessible through the $value parameter. If you need more complicated filtering you can always use a custom route filter class (check Filter Classes): http://laravel.com/docs/routing#route-filters

You can also filter within your controller, which provides a better approach when you need to filter based on specific controllers and methods: http://laravel.com/docs/controllers#controller-filters

Finally you can use something like Sentry2, which provides a complete RBAC solution to use within your project: https://cartalyst.com/manual/sentry

like image 31
petkostas Avatar answered Oct 15 '22 04:10

petkostas