Sead Silajdzic
Sead Silajdzic

Reputation: 319

Weird laravel authorization issue

Can someone help me and explain why this issue occurs? I was working with posts and after I finished all regarding CRUD and policies. Then I added logic for tags and this issue occurred. I can't delete (soft) posts, recover or forceDelete them anymore.

This is the code related to posts:

public function delete(User $user, Post $post)
{
    return true;


//      if($user->isAdmin) {
//            return true;
//        }
//
//        return false;
}

/**
 * Determine whether the user can restore the model.
 *
 * @param User $user
 * @param Post $post
 * @return Response|bool
 */
public function restore(User $user, Post $post)
{
    if($user->isAdmin || $user->id == $post->user_id) {
        return true;
    }

    return false;
}

/**
 * Determine whether the user can permanently delete the model.
 *
 * @param User $user
 * @param Post $post
 * @return Response|bool
 */
public function forceDelete(User $user, Post $post)
{
    if($user->isAdmin || $user->id == $post->user_id) {
        return true;
    }

    return false;
}

/**
 * Determine whether the user can check the list of archived users.
 *
 * @param User $user
 * @return bool
 */
public function archived(User $user) {
    if($user->isAdmin) {
        return true;
    }

    return false;
}

As you can see for DELETE method I removed all checks and just want to return true, but it still returns an unauthorized action error.

Here is the delete method from the post controller:

/**
 * Remove the specified resource from storage.
 *
 * @param Post $post
 * @return void
 * @throws AuthorizationException
 */
public function destroy(Post $post)
{
    $currentUser = auth()->user();
    $this->authorize('delete', $currentUser);
    $post->delete();
    return redirect()->route('dashboard.post.index')->with('warning', 'Archived');
}

AuthServiceProvider

protected $policies = [
    User::class => UserPolicy::class,
    Post::class => PostPolicy::class,
    Tag::class => TagPolicy::class
];

ROUTES

        Route::resource('/tag', TagController::class)->except(['create', 'show']);

Upvotes: -2

Views: 55

Answers (1)

Sead Silajdzic
Sead Silajdzic

Reputation: 319

SOLVED:

The issue in my case was the second parameter in the authorization. I have sent $currentUser and I should've sent $post. Then if I want to give this ability only to admins it is totally fine not to use $post in policies. Something like: `public

function delete(User $user, Post $post)
    {
        if($user->isAdmin) {
            return true;
        }

    return false;
}

Upvotes: 0

Related Questions