Question

I have a bunch of grouped resource controllers in my Laravel 4 app like this:

Route::group(array('before'=>'auth'), function() {
    Route::resource('groups', 'GroupController');
    Route::resource('users', 'UserController');
});

The two mentioned above are controllers for managing users and groups implemented with help of Cartalysts Sentry 2 package.

Now I want a filter which checks the current Sentry user for permission to invoke a controller action. Since filters are wrapped around the group of routes, I cannot know what controller or action the enclosed route is leading to. As far as I know it makes no difference whether the filters are set in filters.php or in the BaseController beforeFilter() method since the problem is that I do not know anyway how to determine where the route is finally leading to.

Is it possible to determine the controller action which is going to be invoked in the (base)controllers beforeFilter() method?

Was it helpful?

Solution

I found the method getActionName() in the Route class of Laravel which returns the action to be executed (in the form of UserController@create, just like a controller route). So I put it to use in a filter where it is checked against the Sentry user permissions. If the user does not have access to, it will render an error view.

routes.php (added the perm filter to the grouped rotes):

Route::group(array('before'=>'auth|perm'), function() {

filters.php:

Route::filter('perm', function($route, $request) {
    $user = Sentry::getUser();

    if ($user)
    {
        if ($user->hasAccess($route->getActionName()) == false)
        {
            return Response::view('errors.forbidden', array(), 403);
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top