Laravel 4 conditional route filter

I have a group of routes that I want to allow the user to access only if they are in a certain department or the id in the route they are trying to access matches their logged in id.

I have:

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']);

});

But it is not working, previously ‘auth.department:6’ works as expected, but when I change it to ‘auth.department:6|auth.me’, the user is still denied access. The filters are defined as:

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(IlluminateRoutingRoute $route, $request){
if($route->getParameter('id') == Auth::id()) {
    return null;
} else {
    return BaseController::failed(['authorization' => ['Unauthorized']], 401);
}
});

I did this:

Route::filter('auth.dept-6-or-me', function(IlluminateRoutingRoute $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);
    }
}
});


Source: laravel

Leave a Reply