Middleware to check if a resource belongs to a user

I'm having problems creating middleware that checks to see if the user owns the requested resource.

For example, if a user navigates to /playlists/1/editand they don’t have their own playlist 1, they should display error 401.

Here is what I still have:

class CheckOwnership {

    public function handle(Request $request, Closure $next)
    {
        if (Playlist::find($request->route()->parameters()['playlists'])->user_id !== $request->user()->id)
        {
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }

}

This is terrible and only works for the Playlist resource, but I cannot find a better way to do this.

thank

+4
source share
2 answers

This can be easily achieved thanks to the recently added form request validation.

( ): http://laravel.com/docs/5.0/validation#form-request-validation

- , , .

Extract:

. , , . , , ?

false authorize, .

+2

Laravel 5 middlewares. .

. , userID playlistID.

public function __construct($playlistID){
    $owner = Playlist::where('playlistID',$playlistID)->pluck('userID');
    Session::put('OWNER',$owner);
    $this->middleware('CheckOwnership',['only'=>'edit']); // apply it to edit function only, assuming you are using a route resource
}

.

public function handle(Request $request, Closure $next)
{
    if (Session::get('OWNER') != $request->user()->id)
    {
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

. , . , !

+1

All Articles