Laravel 中如何检查用户是否有权访问此功能

Ahm*_*sam 4 php laravel laravel-5.5

我有一个函数可以检查用户是否拥有权限并返回Boolean

问题是

我如何检查每个功能用户是否拥有权限。例如在用户控制器中我有两个功能:

  1. index():显示所有用户
  2. delete($id): 删除单个用户

指数():

public function index () {
    if(Auth::user() -> hasPermissionTo('show all users')) {
        // continue for API
    } else {
        // response with error for API
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道有更好的方法来做到这一点,因为我不想在所有函数中重复这个 if 语句。

我尝试做的事情:

我尝试创建一个辅助函数来检查用户是否具有权限,并在用户没有权限时返回响应错误。并在每个函数中调用它,但它不起作用。

辅助函数代码:

if(!function_exists('userHasPermission')) {
    function userHasPermission ($permission) {
        $main_permission = 'do everything';
        if (!Auth::user() -> hasPermissionTo($main_permission) || !Auth::user() -> hasPermissionTo($permission)) {
            $res = trans('api_responses.authorization_failed');
            return Response::json([
                'message'   =>  $res['message'],
                'code'      =>  $res['code']
            ], $res['code']);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

索引函数调用

public function index()
    {
        // PERMISSIONS CHECK
        userHasPermission('users show active');
        $getUsers = $this -> users -> getAllActive();
        return Response::json($getUsers);
    }
Run Code Online (Sandbox Code Playgroud)

但即使用户没有权限,即使它在我的助手中输入了 if 语句,它也永远不会返回错误响应!

Pet*_*ter 7

使用 Laravel,您可以使用门来实现此目的。

在你的App\Providers\AuthServiceProvider文件中做这样的事情:

public function boot()
{
    $this->registerPolicies();

    Gate::define('do-everything', function ($user) {
        return $user->hasPermission('do-everything');
    });

    Gate::define('do-one-thing', function ($user) {
        return $user->hasPermission('do-one-thing');
    });
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

if (Auth::user()->can('do-everything')) {
    // the user can do everything
}

if (Auth::user()->can('do-one-thing')) {
    // the user can just do one thing
}
Run Code Online (Sandbox Code Playgroud)

或者

if (!Auth::user()->can('do-everything')) {
    abort(403);
}
// user has permission to the everything from here on
Run Code Online (Sandbox Code Playgroud)

或者在你的routes/web.php你可以这样做:

Route::get('/things', 'ThingController@action')->middleware(['can:do-one-thing']);
Run Code Online (Sandbox Code Playgroud)

或者您可以像这样对路线进行分组:

Route::middleware(['can:do-everything'])->group(function () {
    Route::get('/things', 'ThingController@index');
    Route::get('/other-things', 'OtherThingController@index');
    ...
}
Run Code Online (Sandbox Code Playgroud)

您还可以查看https://laravel.com/docs/5.7/authorization以获取更多想法。