joelatgrayv's avatar

Policies

I use AuthorizesRequests in my constructor, I have a generated Policy with the typical method (viewAny, view, create, update, delete, restore & forceDelete) and it works as expected:

public function __construct()
{
    $this->authorizeResource($this->resourceModel(), $this->resourceName());
}

What is the correct way to add a new method to the Policy? When I add a method to the controller and matching Policy method, it doesn't get checked. For example a new controller method named bulkUpdate and a Policy method called bulkUpdate.

If I add $this->authorize... to the constructor, they it gets check every time the controller is simply created. So when trying to run unit tests and create the controller, authorization errors are thrown because of course I'm not a logged in user yet.

If I move $this->authorize... to the controller's matching method (bulkUpdate) as the first line, it gets checked. . But it feels like it should be somewhere else...

public function bulkUpdate($request) {
    $this->authorize...
}
1 like
1 reply
vincent15000's avatar

It's very simple.

You can create any additional method to the policy.

For example if you have some categories to which a user can subscribe, you can add a subscribe function.

public function subscribe(User $user, Category $category)
{
	return $category->isPublic();
}

And you can use this function to check authorization in your controller.

public function subscribeToCategory(Request $request, Category $category)
{
	$this->authorize('subscribe', $category);

	// your code if the authenticated user is authorized
}

Please or to participate in this conversation.