mardi 15 mars 2016

Laravel 5.2 Authorization Policy not being read

I'm trying to use the Laravel 5.2 Authentication package Authorization Policies. I have followed the docs. And I can't seem to make it work.

I have User and Documents table, Documents has user_id field also.

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;
    }
}

In DocumentsController edit function

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

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

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

As you can see I put dd('a') to test this, and I can't pass through it and always end up inside the condition even if the record I'm about to edit is different user.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire