Reputation: 1507
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");
}
Upvotes: 4
Views: 2043
Reputation: 19275
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
Upvotes: 5