How to prevent a user from accessing another user’s ID when editing a post by making improper changes?

Asked

Viewed 224 times

0

I was looking for a way that the logged-in user could not access another post when editing, just changing the id on url and implemented something like this, where it will be added to Controller that manipulates the posts, edit, update etc....

I wonder if anyone has ever needed to implement this in Laravel and as did, the code below works for me, but I look for best implementation practices or something standard Laravel.

Route::get('post/{id}/edit', 'PostController@edit');

public function edit(postRegistro  $post, $id)
{    
    $idUserAutenticate = auth()->id();        
    $result = DB::table("post")
      ->whereRaw("id=$id and user_id=$idUserAutenticate")
      ->count();
    if ($result) {
        return view('users.postEdit', compact('post'));
    } else {
        return 'Ação não permitida!!';
    }
}
  • You can easily achieve this level of permission natively in Laravel with Policies and Gates

  • You can use the Model?

  • I have full access to the system, but not much experience with Laravel.

  • From what I understand you want this user filter to be dynamic as the user who is logged in? type user 1 is logged in and consequently only records that have relation to user 1 it can mess with?

  • 1

    This, I checked that when I edit a post the id appears in the url, when changing the id of the url and hit enter, I was able to edit a post of another user.

  • Take the ITL ACL course will help you a lot

Show 1 more comment

1 answer

1


Laravel has Authentication features.

For this you need to run the following Artisan command:

php artisan make:policie UserPolicy

After that you will need to define what the rules will be using the Model User (in App Policies Userpolicy):

public function isAuthor(User $user, Post $post)
{
    return $user->id === $post->user_id;
}

This example is fictitious, you will need to shape better according to your code Remembering that this case supposes that your User and Post tables are related. Otherwise see about relationship in Eloquent ORM.

After that you can enter the rule in your controller or in your view.

To put in the Controllers:

$this->authorize('isAuthor', User::class);

Code to insert in view:

@can('isAdmin', Intranet\User::class)
    <!-- Código HTML -->
@endcan

For more information please visit documentation of the Laravel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.