Element authorization improvements #11808
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds element authorization-check methods and events to the Elements service, with the same names as their
craft\base\Element
counterparts:craft\services\Elements::canView()
+EVENT_AUTHORIZE_VIEW
craft\services\Elements::canSave()
+EVENT_AUTHORIZE_SAVE
craft\services\Elements::canDuplicate()
+EVENT_AUTHORIZE_DUPLICATE
craft\services\Elements::canDelete()
+EVENT_AUTHORIZE_DELETE
craft\services\Elements::canDeleteForSite()
+EVENT_AUTHORIZE_DELETE_FOR_SITE
craft\services\Elements::canCreateDrafts()
+EVENT_AUTHORIZE_CREATE_DRAFTS
There are two notable differences between these and the authorization methods/events on
craft\base\Element
:$user
argument is optional. Ifnull
, it will default to the currently logged-in user, or returnfalse
if there isn’t one.AuthorizationCheckEvent::$authorized
is set tonull
by default, and the methods will only defer to the element’s correspondingcanX()
method if an event handler hasn’t explicitly set it totrue
orfalse
. Which means event handlers have the ability to prevent users from being authorized for certain actions, as opposed to only being able to authorize them (see [4.x]: Issue with `Element::EVENT_AUTHORIZE_DELETE` ? #11759).All internal authorization checks have been updated to call the new Elements service methods. And the old events on
craft\base\Element
are now deprecated, since they’re redundant and less useful.Finally, there’s new global Twig functions that wrap the new Elements service methods, making it a lot easier to check if the current user is authorized to do something with an element: (#11797)