为什么我的视图策略有效,而我的viewAny策略却无​​效?

时间:2019-06-25 09:58:27

标签: laravel view authorization policy

我用php artisan make:policy StudentPolicy --model = Student生成了一个策略。在此策略中,您具有view和viewAny方法。当我正常测试时,viewAny适用于index()以及show()上的视图,但是只有view-policy有效,viewAny无效。我们仍然可以访问页面localhost / student

如果我们将viewAny中的返回值设置为false或true。没有作用。 php artisan route:list的输出如下所示。

|        | POST      | student                               | student.store             | App\Http\Controllers\StudentController@store                           | web,can:create,App\Models\Student

|        | GET|HEAD  | student                               | student.index             | App\Http\Controllers\StudentController@index                           | web

|        | GET|HEAD  | student/create                        | student.create            | App\Http\Controllers\StudentController@create                          | web,can:create,App\Models\Student

|        | GET|HEAD  | student/{student}                     | student.show              | App\Http\Controllers\StudentController@show                            | web,can:view,student

|        | PUT|PATCH | student/{student}                     | student.update            | App\Http\Controllers\StudentController@update                          | web,can:update,student

|        | DELETE    | student/{student}                     | student.destroy           | App\Http\Controllers\StudentController@destroy                         | web,can:delete,student

|        | GET|HEAD  | student/{student}/edit                | student.edit              | App\Http\Controllers\StudentController@edit                            | web,can:update,student

AuthServiceProvider

    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
        Student::class => StudentPolicy::class,

    ];

StudentPolicy

   public function viewAny(User $user)
    {
        //
        return in_array('view.student.all', $user->rights()->pluck('description')->toArray());
    }

    /**
     * Determine whether the user can view the student.
     *
     * @param  \App\Models\User  $user
     * @param  \App\Models\Student  $student
     * @return mixed
     */
    public function view(User $user, Student $student)
    {
        //
        return in_array('view.student.all', $user->rights()->pluck('description')->toArray());
    }

学生控制器

class StudentController extends Controller
{

    public function __construct()
    {
        $this->authorizeResource(Student::class);
    }

如果用户无权查看viewAny,则它可能无法访问localhost /学生,它需要显示未经授权的页面。

1 个答案:

答案 0 :(得分:0)

laravel不匹配。 如果使用Artisan创建策略,则它将生成viewAny方法。 此viewAny方法未映射在resourceAbilityMap下的AuthorizesRequests特性中。如果更改此映射,请向其添加'index'=>'viewAny'。 唯一的问题是,当我执行作曲家更新时,它会被覆盖,因此我需要向Laravel本身执行拉取请求。