授权不适用于用户搜索


Authorization not working for Users Search

我使用的是Laravel 5.1.26,包括带有策略的授权。我有一个基本的ACL模型,其中用户有一个Role,当然是一个整数Role字段。

我的角色是:0-管理员(可以对用户执行任何操作);1-操作员(不能对用户进行任何操作);2-查看器(无法对用户执行任何操作)。

我提供了执行用户搜索的选项。由于我的角色定义,只有管理员才能执行此操作。因此,我在UserController中有一个方法来显示我的结果:

public function postSearch(Request $request)
    {
        $this->authorize('search', User::class);
        $query = User::select('name', 'email')
                    ->where('name', 'LIKE', "%$request->name%")
                    ->where('email', 'LIKE', "%$request->email%")
                    ->where('role', '=', "%$request->role%");
        return $this->displayResult($query, $request);
    }

如您所见,authorize方法执行验证,其余代码创建结果。易于理解的

问题是,如果我搜索(在所有情况下都使用管理员用户)操作员用户,则我的所有操作都将被禁用:创建、删除、编辑等。如果我搜索查看器用户,则会出现相同的行为。

但是,如果我搜索管理员用户,那么我的所有操作都将启用!

所以,我猜授权方法是接收用户找到的!用户未通过身份验证。我该如何解决这个问题?我正在传递User::类,因为如果我不传递任何内容,那么我的策略就不起作用(因此,我在这里遵循了最后一条注释https://laracasts.com/discuss/channels/laravel/laravel-511s-new-authorization-doesnt-read-policies/?page=2)。

谢谢。

在我的应用程序上执行另一个搜索选项后,我发现Eloquent与平时有点不同,于是我在我的模型上创建了一个搜索方法。基本上执行此操作:

public function scopeSearch($query, $field, $value)
    {
        if(is_numeric($value))
            return $query->where($field, '=', "$value");
        else
            return $query;
    }

所以,我把我原来的代码改成了这个,我的角色是一个整数:

public function postSearch(Request $request)
    {
        $this->authorize('search', User::class);
        $query = User::select('name', 'email')
                    ->where('name', 'LIKE', "%$request->name%")
                    ->where('email', 'LIKE', "%$request->email%")
                    ->search('role', "$request->role");
        return $this->displayResult($query, $request);
}

现在运行良好!