Laravel 4.1 - Sentry 2用户组访问/权限

时间:2014-01-27 14:53:32

标签: laravel-4 cartalyst-sentry

我正在使用带有Sentry 2的Laravel 4.1作为授权和身份验证包来构建我的项目 我已设法登录用户,注册他们并分配适当的用户组 我有3个用户组:

  • 管理员
  • 演示
  • 注册

我想实现两件事:

  1. 管理员演示者可以访问管理面板。 用户不要。
  2. 限制演示者的“管理面板”中的视图。我希望他们只能看到少量观点(链接),例如只有计划
  3. 我之前从未使用过角色,这是我第一次使用Sentry 2.这就是为什么我想请求一些帮助。有些观点,如何开始。我怎样才能实现这两个目标?

3 个答案:

答案 0 :(得分:4)

对于更一般的权限检查,我会查看inGroup()帮助:

// Find the user using the user id
$user = Sentry::findUserByID(1);

// Find the Administrator group
$admin = Sentry::findGroupByName('Administrator');

// Check if the user is in the administrator group
if ($user->inGroup($admin)) {
    // User is in Administrator group
} else {
    // User is not in Administrator group
}

答案 1 :(得分:1)

定义所有群组的权限。

查看本教程https://cartalyst.com/manual/sentry/users/helpers

并专注于hasAccess($permission)hasAnyAccess($permissions)

答案 2 :(得分:0)

在filter.php中

/**
* hasAcces filter (permissions)
*
* Check if the user has permission (group/user)
*/
Route::filter('hasAccess', function($route, $request, $value)
{
    try {
        $user = Sentry::getUser();
        if( ! $user->hasAccess($value)) {
            if(Sentry::check())
                return Redirect::to('portal')->with('message', 'No Access.');
            else
                return Redirect::to('registration#login')->with('message', 'No Access.');
        }
    } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
        if(Sentry::check())
            return Redirect::to('portal')->with('message', 'User not found.');
        else
            return Redirect::to('registration#login')->with('message', 'User not found.');
    }
});

/**
* InGroup filter
*
* Check if the user belongs to a group
*/
Route::filter('inGroup', function($route, $request, $value) {
    try {
        $user = Sentry::getUser();
        $group = Sentry::findGroupByName($value);
        if( ! $user->inGroup($group)) {
            if(Sentry::check())
                return Redirect::to('portal')->with('message', 'No Access.');
            else
                return Redirect::to('registration#login')->with('message', 'No Access.');
        }
    } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
        if(Sentry::check())
            return Redirect::to('portal')->with('message', 'User not found.');
        else
            return Redirect::to('registration#login')->with('message', 'User not found.');
    } catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
        if(Sentry::check())
            return Redirect::to('portal')->with('message', 'Group not found.');
        else
            return Redirect::to('registration#login')->with('message', 'Group not found.');
    }
});

路线 - >

Route::group(array( 'before' => 'Sentry|inGroup:Administrators'), function() {
    Route::get('manageusers', array('as' => 'manageusers', 'uses' => 'UserController@viewUsersList'));
});