SuperManSL
SuperManSL

Reputation: 1306

Protecting routes in laravel with filters

how can I secure routes so that user can access only those departments that he belongs to? my current filter:


    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!' );;
            }
        }
    }
    });

And this is my method in user model

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

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

Upvotes: 0

Views: 202

Answers (2)

J.T. Grimes
J.T. Grimes

Reputation: 4272

In the code you have, the filter is applied to all the routes, and then checks to see if we have a matching method/action. My preference would be to only apply the filter when it's needed. So

[Warning - untested code follows]

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!' );
    }
});

Upvotes: 1

Ninz
Ninz

Reputation: 241

I think that this should be done in the database/model level. Since the data that you need to compare is in a database, its better if you do this transaction in a database level.

Upvotes: 0

Related Questions