Laravel/Lumen: 如何授权Controller访问?
Laravel/Lumen: How to authorize Controller access?
这是我的第一个 Laravel/Lumen 项目,因此我的知识还不是最好的。
我的路线:
$router->group(['prefix' => 'rest/v1','middleware' => 'auth'], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
我的控制器:
class ArticleController extends Controller{
public function index(){
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return response()->json(Article::all());
}
public function getArticle($id){
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return response()->json(Article::find($id));
}
}
这当然非常麻烦,尤其是因为它是访问我的控制器中所有功能的相同权限。但是我必须使用我的自定义 CapabilityService
来检查权限。我怎样才能更好地实施它?
您可以通过创建一个新的中间件来做到这一点。
$router->group(['prefix' => 'rest/v1','middleware' => ['auth','your-custom-middleware']], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
现在在你的中间件 handle
方法中做类似
的事情
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return $next($request);
这是我的第一个 Laravel/Lumen 项目,因此我的知识还不是最好的。
我的路线:
$router->group(['prefix' => 'rest/v1','middleware' => 'auth'], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
我的控制器:
class ArticleController extends Controller{
public function index(){
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return response()->json(Article::all());
}
public function getArticle($id){
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return response()->json(Article::find($id));
}
}
这当然非常麻烦,尤其是因为它是访问我的控制器中所有功能的相同权限。但是我必须使用我的自定义 CapabilityService
来检查权限。我怎样才能更好地实施它?
您可以通过创建一个新的中间件来做到这一点。
$router->group(['prefix' => 'rest/v1','middleware' => ['auth','your-custom-middleware']], function($router) {
$router->get('articles','ArticleController@index');
$router->get('article/{id}','ArticleController@getarticle');
});
现在在你的中间件 handle
方法中做类似
if(!CapabilityService::currentUserCan('fetch_basic_content')) {
return response('Insufficient permissions.', 401);
}
return $next($request);