如何在政策中允许新星资源行动

时间:2019-07-03 14:20:30

标签: laravel laravel-nova

Nova 2.0 Laravel 5.8

我有一个新星资源Document(包含文件url,相关外键和标题),为此我定义了policy,其中createupdate为false以及所有其他设置为true时,PDF是从其他资源生成的,因此我不需要允许创建或编辑它,现在一切正常,但是我尝试下载此文档资源上的另一个action这些文件,给我错误“ Sorry you are not authorized to take this action”,因此如何在action上使用此Policy

DocumentPolicy类

<?php

namespace App\Policies;

use App\User;
use App\Models\Document;
use Illuminate\Auth\Access\HandlesAuthorization;

class DocumentPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any documents.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return true;
    }

    /**
     * Determine whether the user can view the document.
     *
     * @param  \App\User  $user
     * @param  \App\Document  $document
     * @return mixed
     */
    public function view(User $user, Document $document)
    {
        return true;
    }

    /**
     * Determine whether the user can create documents.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return false;
    }

    /**
     * Determine whether the user can update the document.
     *
     * @param  \App\User  $user
     * @param  \App\Document  $document
     * @return mixed
     */
    public function update(User $user, Document $document)
    {
        return false;
    }

    /**
     * Determine whether the user can delete the document.
     *
     * @param  \App\User  $user
     * @param  \App\Document  $document
     * @return mixed
     */
    public function delete(User $user, Document $document)
    {
        return true;
    }

    /**
     * Determine whether the user can restore the document.
     *
     * @param  \App\User  $user
     * @param  \App\Document  $document
     * @return mixed
     */
    public function restore(User $user, Document $document)
    {
        return true;
    }

    /**
     * Determine whether the user can permanently delete the document.
     *
     * @param  \App\User  $user
     * @param  \App\Document  $document
     * @return mixed
     */
    public function forceDelete(User $user, Document $document)
    {
        return true;
    }

    public function download(User $user, Document $document)
    {
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

出现错误的原因是因为您的update方法在策略中返回false。

默认情况下,如果更新为false,Nova将不允许该操作。要对此进行测试,您可以尝试将其设置为true,然后再次进行测试。

要解决此问题,您必须更改注册操作的方式,以添加自定义回调以处理用户是否可以运行该操作的情况:

public function actions(Request $request)
{
    return [
        (new DownloadDocument)->canRun(function ($request, $document) {
            return $request->user()->can('download', $document);
        }),
    ];
}

这样,它将检查文档策略中的download方法,而不是操作的update方法。

有关更多信息:https://nova.laravel.com/docs/2.0/actions/registering-actions.html#authorizing-actions-per-resource

相关问题