Laravel 4条件路由过滤器

时间:2015-06-15 08:01:01

标签: php laravel laravel-4 laravel-routing

我有一组路由,我想让用户只有在某个部门才能访问,或者他们尝试访问的路由中的ID与他们登录的ID匹配。

我有:

Route::group(array('before' => 'auth.department:6|auth.me'), function () {

    Route::get('users/{id}/outofoffice', ['as' => 'users.outofoffice.form', 'uses' => 'RackspaceController@outOfOfficeForm']);
    Route::post('users/{id}/outofoffice', ['as' => 'users.outofoffice.save', 'uses' => 'RackspaceController@outOfOfficeSave']);

    Route::get('users', ['as' => 'users.list', 'uses' => 'UserController@index']);
    Route::get('users/{id}/edit', ['as' => 'users.edit', 'uses' => 'UserController@edit']);
    Route::post('users/{id}', ['as' => 'users.update', 'uses' => 'UserController@update']);

});

但它不起作用,以前' auth.department:6'按预期工作,但当我将其更改为' auth.department:6 | auth.me'时,仍然拒绝用户访问。过滤器定义为:

Route::filter('auth.department', function($route, $request)
{
if(Auth::level() > 5) return null;

$departmentIds = array_slice(func_get_args(), 2);

if(!in_array(Auth::dept(), $departmentIds)) {
    if (Request::ajax())
    {
        return Response::make('Unauthorized', 401);
    }
    else
    {
        return Response::make('Unauthorized', 401);
    }
}

});

Route::filter('auth.me', function(\Illuminate\Routing\Route $route, $request){
if($route->getParameter('id') == Auth::id()) {
    return null;
} else {
    return BaseController::failed(['authorization' => ['Unauthorized']], 401);
}
});

我这样做了:

Route::filter('auth.dept-6-or-me', function(\Illuminate\Routing\Route $route, $request){
if(Auth::level() > 5) return null;
$departmentIds = array_slice(func_get_args(), 2);
if($route->getParameter('id') == Auth::id()) {
    return null;
}
elseif(!in_array(Auth::dept(), $departmentIds)) {
    if (Request::ajax())
    {
        return Response::make('Unauthorized', 401);
    }
    else
    {
        return Response::make('Unauthorized', 401);
    }
} else {
    if (Request::ajax())
    {
        return Response::make('Unauthorized', 401);
    }
    else
    {
        return Response::make('Unauthorized', 401);
    }
}
});

1 个答案:

答案 0 :(得分:0)

不是解决方案,但也许这会对某人有所帮助。

同样的事情,这里提到了解决方法How to apply multiple filters on Laravel 4 route group?

此外,我现在也对此进行了测试,因为我遇到了同样的问题。所以,| sign只表示AND,它的工作原理是这个,我在Sentry插件中使用它。

Route::post('/insert', array('as' => 'insertKom', 'uses' => 'KommunikationController@insertKom', 'before' => 'hasAccess:admin|hasAccess:contact.insert'));

例如我的2个权限是:

hasAccess:admin: 1
hasAccess:contact.insert: 1

此解决方案通过后,用户可以访问该路径。

更改权限:

hasAccess:admin: 0
hasAccess:contact.insert: 1

不过,这个解决方案仍然以某种方式通过。用户访问了该路线。不太清楚为什么。

更改权限:

hasAccess:admin: 1
hasAccess:contact.insert: 0

这个没有通过。用户无权访问该路线。有趣的事情,就像它只检查最后的许可一样。