如何保护路由,以便用户只能访问他所属的部门? 我当前的过滤器:
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!' );
}
});
答案 1 :(得分:0)
我认为这应该在数据库/模型级别完成。由于您需要比较的数据位于数据库中,因此如果您在数据库级别执行此事务,则会更好。