2014-04-01 54 views
0

我使用laravel 4開發一個網站,並試圖實現使用哨兵2.我需要如何構建以下幫助我的ACL:Laravel 4和哨兵2 ACL結構和訪問控制水平

我有對於角色HR以下權限:

Staffs|View staff details 
Staffs|Register new staff 
Staffs|Edit staff details 
Staffs|Delete staff details 

對應於下列路線:

//get route to staffs landing page 
Route::get('staffs/view-staffs', '[email protected]'); 

//post routes 
Route::post('staffs/add-staff', '[email protected]'); 
Route::post('staffs/update-staff', '[email protected]'); 
Route::post('staffs/delete-staff', '[email protected]'); 

我需要訪問控制以下:

  1. 鏈接在我的菜單上查看員工:如果全部員工權限被禁用,請禁用鏈接。這就是我如何做它:

    if($user->hasAnyAccess(array('Staffs|View staff details', 'Staffs|Register new staff', 'Staffs|Edit staff details', 'Staffs|Delete staff details'))) 
    { 
        //display menu link 
    } 
    
  2. 我的路線:如果所有工作人員的權限被禁用,禁用「員工/」

    //For this, i have no idea how to restrict routes based on my permissions 
    //But i don't want to do it like i did in (1) within my controllers 
    
  3. 禁止的行動,corresbond到按鈕下下跌的所有路由禁用許可

    //same as no (1) 
    

回答

1

你可以這樣做以下:

在app/filters.php中,按如下所示創建過濾器。

Route::filter('permissions', function() 
{ 
    $name = Route::current()->getName(); 
    $name = 'system' . (! empty($name) ? '.' : '') . $name; 

    if (!UserHelper::hasPermission($name)) { 
     App::abort(401, 'You are not authorized to access route '.$name); 
    } 
}); 

您可以通過在路線上放置一個before過濾器來應用過濾器,例如,

Route::group(array('before' => 'permissions'), function() 
{ 
    // routes 
} 

有了這個系統,你可以創建權限組這樣的:

Sentry::getGroupProvider()->create(array(
    'id' => 1, 
    'name'  => 'Super Administrators', 
    'permissions' => array(
     'system' => 1, 
    ), 
)); 

Sentry::getGroupProvider()->create(array(
    'id' => 2, 
    'name'  => 'Administrators', 
    'permissions' => array(
     'system.users' => 1, 
     'system.products' => 1, 
     'system.store' => 1, 
     'system.profile' => 1, 
    ), 
)); 
Sentry::getGroupProvider()->create(array(
    'id' => $id++, 
    'name'  => 'Managers', 
    'permissions' => array(
     'system.products' => 1, 
     'system.store' => 1, 
     'system.profile' => 1, 
    ), 
)); 

因此,如果用戶有權限system.products,他就能夠使用所有的產品路線。現在

,因爲你希望顯示鏈接到某些羣體的一部分,你可以做到這一點像這樣的幫手:

public static function has($permission) 
{ 
    $all = []; 
    $parts = explode('.',$permission); 
    $permission = ''; 

    foreach($parts as $part) { 
     $permission .= (!empty($permission) ? '.' : '') . $part; 
     $all[] = $permission; 
    } 

    return Sentry::check() and Sentry::getUser()->hasAnyAccess($all); 
} 

你會簡單地傳遞路線的名稱(例如system.products)到該函數,它會返回用戶是否有權訪問它。 來源:https://laracasts.com/forum/conversation/post/2819

+0

哎,流量看起來很酷..讓我嘗試實現..回來.. – aiiwa