Authorization policy without model

I need to authorize users on the forum. So in the blade I have @can('editPost', $post)before showing the form for the answer on the topic. My class PostPolicyhas a method editPostthat authenticates if it belongs to the user.

However, the problem occurs when I want to perform a simple check, for example deletePost(). This checks if there is anyAuth::user()->isAdmin

public function deletePost(User $user) {
    return Auth::user()->isAdmin;
    // return $user->isAdmin
}

However, this will not even be called as I am not passing an instance Post

My application in the real world is much more complicated, but I use it isAdminas a simple example.

I think that defining $gate->define('deletePost', 'App\Policies\PostPolicy@deletePost');in AuthServiceProvidercould work, but ultimately would separate my definitions and methods and, ultimately, into a big mess of applicationAuthServiceProvider

+4
source share
2 answers

When you register a policy, this is the class name that is used to route checks to the class, so in order to be redirected to the policy, you can simply pass the class name of the type in which you registered it.

Try using @can ('delete', Post :: class) and see if you got there

see Light \ Auth \ Access \ Gate :: firstArgumentCorrespondsToPolicy

EDIT After a bit more diggin I found this https://github.com/laravel/framework/commit/70f75255808ffc96275e6f2f356616dd2e163434#diff-961368895033e553787b301c3be0e17a

, 5.1.23, ,

+4

$this->authorize('<ability>', <Class-With-Rule::class> | <Full-Path-To-Class>);

Blade

@can('<ability>', <Class-With-Rule>::class> | <Full-Path-To-Class>)

Eloquent

$user->can('<ability>', <Class-With-Rule>::class> | <Full-Path-To-Class>);
0

Source: https://habr.com/ru/post/1614815/


All Articles