enriqg9 enriqg9 - 25 days ago 6
PHP Question

In Laravel, should I check for permission in controller if already checking on middleware?

I created a middleware that checks if the user is authorized to perform an action and added this middleware to the routes that I want to protect like this:

// VerifyPermission middleware

class VerifyPermission {

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param $permission
* @return mixed
*/
public function handle($request, Closure $next, $permission)
{
$user = auth()->user();

if (auth()->check() && $user->hasPermission($permission))
{
return $next($request);
}

return redirect('/');
}
}

// Routes

Route::patch('company/{id}', ['as' => 'updateCompany',
'uses' => 'SettingsController@updateCompany',
'middleware' => 'permission:manage_company']
);


My question is, is it necessary to make another check on
updateCompany
or is the middleware check sufficient?

public function updateCompany()
{
if(Auth::user()->hasPermission('manage_company'))
{
// Updates Company
}

return abort(403, "Unauthorized");
}

Answer

No, you should not make another check, the middleware will do it.

In fact handling authentication and permission handling is one of the most frequent uses for middleware

when you specify this:

Route::patch('company/{id}', ['as' => 'updateCompany',
                          'uses' => 'SettingsController@updateCompany',
                          'middleware' => 'permission:manage_company']

You're telling laravel that, when it finds a company/{id} route, it should trigger the handle method of the permission:manage_company middleware, before the request is sent to the SettingsController

So, when the request will get to your controller you're sure that it has satisfied all the middleware it went through

Comments