【问题标题】:Authorizing Nova using Laravel Policy使用 Laravel Policy 授权 Nova
【发布时间】:2023-03-23 19:55:02
【问题描述】:

我目前正在将 Nova 用于我的后台应用程序,并尝试根据用户的角色授予用户身份验证。我已经编写了一些策略,除了一个之外,它们都有效。我一遍又一遍地检查它,看看我是否错过了什么,但我找不到任何东西。我需要你们帮助重新审视一下,以帮助我弄清楚我做错了什么。这是我正在使用的代码

订单政策

<?php

namespace App\Policies;

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

class OrderPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any order.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return $user->hasAnyRole(['crm']);
    }
}

订购新星资源

class Order extends Resource
{
    public static function indexQuery(NovaRequest $request, $query)
    {
        return $query->where('status_id', 'paid');
    }

    public static $model = 'App\Models\Order';

    public static $title = 'id';

    public static $search = [
        'id', 'reference'
    ];

    public function fields(Request $request)
    {
        return [
            // fields that should be displayed
        ];
    }

   // other functions
}

AuthServiceProvider

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // other policies
        'App\Models\Order' => 'App\Policies\OrderPolicy',
    ];

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

        // ....
    }
}

我在这个政策上做错了什么?

【问题讨论】:

  • 究竟是什么不起作用?用户能看能不能看,能不能多解释一下
  • 因此具有不同角色的用户仍然可以查看资源。

标签: laravel laravel-nova


【解决方案1】:

对于 Nova,viewAny 方法几乎总是必须返回 true。在您的示例中,除非用户具有“crm”角色,否则他们将无法查看订单资源。

许多人(包括我自己)认为这是违反直觉的。例如,您可能希望所有用户都能看到订单资源,但只能看到他们的订单。如果没有明显的过度骑行,这在 Laravel Nova 中是不可能的。要过滤用户可以看到的订单,您需要覆盖 indexQuery(您似乎已经完成了)

Github 上的这个问题可能有助于解释它:https://github.com/laravel/nova-issues/issues/1762

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 2020-07-21
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2019-03-20
    • 2017-02-05
    • 2017-09-03
    • 2015-07-29
    相关资源
    最近更新 更多