2014-09-02 46 views
0

如何保護路由,以便用戶只能訪問他所屬的部門? 我目前的過濾器:使用過濾器保護laravel中的路由

 

    Route::filter('department', function ($route, $request) { 
     // Check to see if the current user belongs to the department: 
     if (!Request::isMethod('post')) 
     { 
     if($request->segment(2) != "create") 
     { 
      if (!Auth::user()->canAccessDepartment($request->segment(2))) { 
       // The user shouldn't be allowed to access the department! Redirect them 
       return Redirect::to('/')->with('notice', 'Error!');; 
      } 
     } 
    } 
    }); 

這是我的用戶模型

public function canAccessDepartment($department_id) { 
     $user = Confide::user(); 

     if ($user->departments()->where('department_id', $department_id)->count() < 1) 
     { 
      return false; 
     } 
     else{ return true; } 
    } 

回答

0

我認爲,這應該在數據庫/模型級進行的方法。由於您需要比較的數據位於數據庫中,因此如果您在數據庫級別執行此事務,則會更好。

1

在代碼中,過濾器應用於所有路由,然後檢查是否有匹配的方法/操作。我希望只在需要時才應用過濾器。所以

[警告 - 未經測試的代碼如下]

Route::resource('department', 'DepartmentController', 
       array('except' => array('create','store', 'update', 'destroy'))); 

Route::resource('department','DepartmentController',array('only'=>array('create','store', 'update', 'destroy'),'before'=>'departmentFilter')); 


Route::filter('department', function ($route, $request) { 
    // should this be Confide::user() ? 
    if (!Auth::user()->canAccessDepartment($request->segment(2))) { 
     // The user shouldn't be allowed to access the department! Redirect them 
     return Redirect::to('/')->with('notice', 'Error!'); 
    } 
}); 
+0

當我訪問它工作的具體部門域/部門/ 2,但如果我嘗試訪問域/部門(這將列出所有部門)我得到「error」重定向到「/」 – SuperManSL 2014-09-02 21:41:12

+0

當您訪問域/部門時,它將調用控制器上的index()函數。那裏的代碼是什麼樣的? – 2014-09-02 22:28:26

+0

只有這個 \t \t return View:make('department.index'); – SuperManSL 2014-09-03 15:22:29