Laravel 5.2授权政策未被阅读

时间:2016-03-15 08:21:20

标签: laravel laravel-5 laravel-5.2

我尝试使用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(&#39; a&#39;)来测试一下,我无法通过它   并且即使我记录的记录也总是在条件内   编辑是不同的用户。

1 个答案:

答案 0 :(得分:0)

中的

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

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