10

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"?

tereško
  • 58,060
  • 25
  • 98
  • 150
user1424508
  • 3,231
  • 13
  • 40
  • 66

3 Answers3

14

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');


});
lozadaOmr
  • 2,565
  • 5
  • 44
  • 58
Anam
  • 11,999
  • 9
  • 49
  • 63
  • 1
    Exactly...It should works.... But if you need do it for multiple roles we need to change filter route like `Route::filter('role', function() { $roles = ['2','3','4']; if (!in_array(Auth::user()->role, $roles)) { return Redirect:to('/'); } }); ` – user2943773 Dec 27 '13 at 04:23
5

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

petkostas
  • 7,250
  • 3
  • 26
  • 29
0

From laravel 5.1.11 you can use the AuthServiceProvider: https://laravel.com/docs/5.1/authorization

Luca C.
  • 11,714
  • 1
  • 86
  • 77