首页 > 解决方案 > 如何检查我的控制器中的权限

问题描述

我是 Laravel 的新手,我正在自己编写一个用户管理系统。此时,

public function boot()
{
    Gate::before( function (User $user , $permission) {
        // App administrator
        if($user->getPermissions()->contains('appAll'))
        {
            return true;
        }
        // Permission check
        return $user->getPermissions()->contains($permission);
    });
}

在我的 AdminUserController 中,我可以像这样检查权限:

public function index()
{
    if( Gate::check('createUser') || Gate::check('readUser') || Gate::check('updateUser') || Gate::check('deleteUser')) {
        return view('userMgmt/users/index', [
            'users' => User::getUsersWithRolesWithTexts()
        ]);
    }
    else
    {
        return redirect(route('home'))->withErrors('You do not have required permission');
    }
}

那运作良好。

但是这是包装每个控制器方法的正确方法:

if( Gate::check(...) ...) {
    //Do what the method is supposed to do
}
else
{
    return redirect(route('SOME.ROUTE'))->withErrors('FUCK ALL');
}

如果有人能给我一些想法,那就太好了。保护你

标签: permissionslaravel-8roles

解决方案


有一个名为authorize的控制器辅助函数,您可以从扩展的控制器中的任何方法调用它App\Http\Controllers\Controller。该方法接受动作名称和模型,如果用户没有被授权,它会抛出异常。因此,代替if...else语句,它将是一行:

public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

    // The current user can update the blog post...
}

推荐阅读