【问题标题】:Laravel 5.2 Authorization Policy not being readLaravel 5.2 授权政策未被阅读
【发布时间】:2016-05-16 11:42:45
【问题描述】:

我正在尝试使用 Laravel 5.2 身份验证包 Authorization Policies。我遵循了文档。而且我似乎无法让它工作。

我有 User 和 Documents 表,Documents 也有 user_id 字段。

AuthServiceProvider.php

<?php

namespace App\Providers;

use App\Document;
use App\User;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        User::class => Document::class,
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);
    }
}

DocumentPolicy.php

<?php

namespace App\Policies;

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

class DocumentPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function before($user, $ability)
    {
        if ($user->isSuperAdmin()) {
            return true;
        }
    }
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Document $document)
    {
        return $user->id === $document->user_id;
    }
}

DocumentsController编辑功能中

use Gate;
use App\Document;
.......some code here....

public function edit($id){
    $document = Document::findOrFail($id);

        if (Gate::allows('update', $document))
        {
            dd('a');
        }
}

如你所见,我放了 dd('a') 来测试这个,但我无法通过它 并且总是在条件内结束,即使我即将记录的记录 编辑是不同的用户。

【问题讨论】:

    标签: laravel laravel-5 laravel-5.2


    【解决方案1】:

    protected $policies = [ User::class => Document::class, ]; 应该是

      `protected $policies = [
        User::class => DocumentPolicy::class,
    ];`
    

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2017-10-12
      • 2017-09-20
      • 2019-05-04
      • 1970-01-01
      相关资源
      最近更新 更多