Aleq Baghumyan
Aleq Baghumyan

Reputation: 13

Laravel: Prevent user access to specific resource

I have recourse api in my application. Currently there's 'domain.com/posts/:id' route which returns specific post by id. All of users have access to it. But I want to allow user to see a post, if only he is author or editor of that post:

My post table has author_id and editor_id columns. Both columns have referenced to user table's id.

Is it good practice to solve this problem with middlware/ (to create middlware for only one route?). Any suggestions ?

Upvotes: 1

Views: 1562

Answers (2)

thearyanahmed
thearyanahmed

Reputation: 606

You can use authorization/policy or event Gates provided by laravel.

or just to keep it simple,

in your Post model

public function canView()
{
    return $this->author_id === auth()->id() || $this->editor_id === auth()->id();
}

in your controller

public function show(Post $post)
{
    //you already have the $post
    if(! $post->canView()) {
        // cannot view post
    }

   // can view post.
}

Following this way, you can use the same source of truth for authorization throughout your application easily as you'll probably use eloquent's instance throughout your application.

If your logic is more complex, reach for Laravel's Policy

Upvotes: 1

mllnd
mllnd

Reputation: 575

This can be solved with either a middleware or just a user check in the controller method. Here is a simple example on how to do it in controller method:

public function view(Request $request, Post $post) {
    // Currently logged in user.
    $user = auth()->user();
    // Check if the current user is either the author or editor.
    if ($user->id == $post->author_id || $user->id == $post->editor_id) {
       // Your controller logic.
    }
    abort(403);
}

Edit: I recommend you to change your route pattern to domain.com/posts/:post, this way you can use route model binding in your controller method.

Upvotes: 0

Related Questions