简体   繁体   中英

Laravel - Authorize with other policy

I have a gallery policy and a photo policy, a gallery controller, and a photo controller.

It works like this:

user-> hasMany galleries -> hasMany photos

I do have a photo upload page (with dropzone), that uses the photo controller.

the url is like this: /gallery/3/upload

I want to restrict access to this page only if the user is the owner of the gallery 3. But this page uses the PhotoPolicy, that makes use of the Photo model, not the Gallery model.

How can I authorize this page, using the GalleryPolicy instead of the PhotoPolicy? Or do I have to copy over the view method from the GalleryPolicy and have it also in the PhotoPolicy?

EDIT:

I do not understand this...

In my PhotoPolicy:

 public function view(User $user, Photo $photo)
{
    return false;        
}

In my Photos controller:

        $this->authorize('view',  $photo);

In my AuthenticationServiceProvider:

protected $policies = [
    \App\Gallery::class => \App\Policies\GalleryPolicy::class,
    \App\Photo::class => \App\Policies\PhotoPolicy::class,
];

Restult: page loads just fine.. even if return is false.. why?

You can authorize this page in PhotoPolicy in create method, because you have just one way to upload images which is also using this url. In PhotoPolicy you have gallery's id which it was passed as params, so you can check owner of gallery and restrict them.

And another point is according to API rules it's better change upload's url to gallery/3/photos .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM