【问题标题】:How to Use Permissions in Sentry for Laravel application如何在 Sentry 中为 Laravel 应用程序使用权限
【发布时间】:2015-03-24 02:22:10
【问题描述】:

我需要在 Laravel 应用程序中使用 Sentry 2.1,我阅读了这个文档 https://cartalyst.com/manual/sentry/2.1 我真正需要的是一些组并为每个组分配一些权限,然后将这些组分配给用户。

以此为例(我取自同一个链接): 我用以下详细信息注册了一个用户

 Sentry::register(array(
   'email'    => 'john.doe@example.com',
   'password' => 'foobar', 
   'activated' => true,    
));

然后我使用以下详细信息注册一个组:

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

然后我将组分配给用户

问题: 有人可以为我提供一段代码,帮助我了解如何修改routes.php 并向其添加过滤器,以便过滤器将应用于权限而不是组。

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

});

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

例如拥有admin权限的用户只能看到adminController链接

【问题讨论】:

    标签: php laravel authentication laravel-4 cartalyst-sentry


    【解决方案1】:

    通过 Sentry hasAccess() 方法检查权限。您可以创建多个过滤器以针对不同的权限检查采取特定操作,也可以使用通用过滤器将权限作为参数并对其进行检查。下面是一个通用的“hasAccess”过滤器,您将检查的权限传递给该过滤器。

    过滤器:

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

    路线:

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

    【讨论】:

      猜你喜欢
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2018-10-12
      • 1970-01-01
      • 2014-03-06
      • 2022-01-04
      • 2020-06-11
      相关资源
      最近更新 更多