laravel权限控制流程

权限控制

为了安全起见我们只允许订单的创建者可以看到对应的订单信息,这个需求可以通过授权策略类(Policy)来实现。

通过 make:policy 命令创建一个授权策略类:

$ php artisan make:policy OrderPolicy

app/Policies/OrderPolicy.php

<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class OrderPolicy{
    use HandlesAuthorization;

    public function own(User $user, Order $order)
    {
        return $order->user_id == $user->id;
    }
}    

然后在 AuthServiceProvider 中注册这个策略:
app/Providers/AuthServiceProvider.php

use App\Models\Order;
use App\Policies\OrderPolicy;
.
.
.
    protected $policies = [
        UserAddress::class => UserAddressPolicy::class,
        Order::class       => OrderPolicy::class,
    ];

最后在 OrdersController@show() 中校验权限:

appHttp/Controllers/OrdersController.php

.
.
.
    public function show(Order $order, Request $request)
    {
        $this->authorize('own', $order);
        return view('orders.show', ['order' => $order->load(['items.productSku', 'items.product'])]);
    }
阅读 130

Comments