Search code examples
phplaravelauthenticationlaravel-4cartalyst-sentry

How to Use Permissions in Sentry for Laravel application


I need to use Sentry 2.1 in a Laravel application, I read this document https://cartalyst.com/manual/sentry/2.1 what I really need to have is some groups and assign some permissions to each group and then assign those groups to the users.

take this as an example (which I took from the same link): I register a user with following detaiks

 Sentry::register(array(
   'email'    => '[email protected]',
   'password' => 'foobar', 
   'activated' => true,    
));

Then I register a group with the following details:

 $group = Sentry::createGroup(array(
    'name'        => 'Moderator',
    'permissions' => array(
        'admin' => 1,
        'writers' => 1,
    ),
));

And then I assigned the group to the user

The Question: Can someone provide me with a piece of code that helped me through how I should modify routes.php and add filters to it, so that the filters will apply on permissions and not the groups.

Route::group(array('before' => 'admin'), function()
{
    Route::controller('admin','adminController');

});

Route::group(array('before' => 'mod'), function()
{
     Route::controller('cruds','crudController');
 });

For example users with admin permissions can only see the adminController links


Solution

  • Checking permissions is done via the Sentry hasAccess() method. You can either create multiple filters to take specific actions for different permission checks, or you can use a generic filter which takes the permission as a parameter and check on that. Below is a generic "hasAccess" filter, to which you pass the permission for which to check.

    Filter:

    Route::filter('hasAccess', function ($route, $request, $value) {
        try {
            // get the logged in user
            $user = Sentry::getUser();
    
            // check the user against the requested permission
            if (!$user->hasAccess($value)) {
                // action to take if the user doesn't have permission
                return Redirect::home();
            }
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            // action to take if the user is not logged in
            return Redirect::guest(route('login'));
        }
    });
    

    Routes:

    Route::group(array('before' => 'hasAccess:admin'), function() {
        Route::controller('admin','adminController');
    });
    
    Route::group(array('before' => 'hasAccess:mod'), function() {
        Route::controller('cruds','crudController');
    });