VOOZH about

URL: https://deepwiki.com/hypervel/auth/6.2-utility-traits

⇱ Utility Traits | hypervel/auth | DeepWiki


Loading...
Menu

Utility Traits

Purpose and Scope

This document covers the utility traits provided by the hypervel/auth package that simplify common authorization patterns. These traits offer convenience methods for creating authorization responses, performing authorization checks, and integrating authorization into controllers and models.

Three primary utility traits are documented here:

  • HandlesAuthorization: Helper methods for creating authorization responses in policy classes
  • Authorizable: Authorization check methods for user models and entities (for architectural details, see Authorizable Trait)
  • AuthorizesRequests: Authorization methods for controllers with automatic ability name resolution

For information about the underlying authorization contracts, see Contracts and Interfaces. For policy implementation details, see Policies and Abilities.


HandlesAuthorization Trait

The HandlesAuthorization trait provides convenience methods for creating Response objects within policy classes. Instead of directly instantiating Response::allow() or Response::deny(), policies can use this trait to streamline response creation.

Sources: src/Access/HandlesAuthorization.php1-41

Methods

MethodReturn TypeDescription
allow(?string $message, int|string|null $code)ResponseCreates an authorization response that allows the action
deny(?string $message, int|string|null $code)ResponseCreates an authorization response that denies the action
denyWithStatus(int $status, ?string $message, int|string|null $code)ResponseDenies the action with a specific HTTP status code
denyAsNotFound(?string $message, int|string|null $code)ResponseDenies the action with a 404 HTTP status code

All methods are protected and intended for use within policy classes. They delegate to the corresponding static methods on the Response class src/Access/HandlesAuthorization.php12-38

Usage Pattern


Typical Implementation:


The trait is particularly useful when policies need to return responses with custom messages or HTTP status codes. The denyAsNotFound() method implements a common security pattern where unauthorized access returns 404 instead of 403 to avoid revealing resource existence src/Access/HandlesAuthorization.php36-39

Sources: src/Access/HandlesAuthorization.php1-41


Authorizable Trait

The Authorizable trait implements the Hypervel\Auth\Contracts\Authorizable interface, providing authorization check methods that can be used directly on user models and other authenticatable entities. This trait integrates with the Gate system to perform authorization checks in the context of a specific user.

For detailed architectural information about the Authorizable system, see Authorizable Trait and Authorizable Contract.

Sources: src/Access/Authorizable.php1-44 src/Contracts/Authorizable.php1-14

Methods

MethodParametersReturn TypeDescription
can(iterable|string $abilities, mixed $arguments)abilities, argumentsboolCheck if entity has the given abilities
canAny(iterable|string $abilities, mixed $arguments)abilities, argumentsboolCheck if entity has any of the given abilities
cant(iterable|string $abilities, mixed $arguments)abilities, argumentsboolCheck if entity does not have the abilities
cannot(iterable|string $abilities, mixed $arguments)abilities, argumentsboolAlias for cant()

All methods are public and delegate to the Gate system via ApplicationContext::getContainer()->get(Gate::class)->forUser($this) src/Access/Authorizable.php15-42

Gate Integration


The trait creates a user-scoped gate instance using forUser($this), ensuring all authorization checks are performed in the context of the entity using the trait src/Access/Authorizable.php17

Sources: src/Access/Authorizable.php1-44 src/Contracts/Authorizable.php1-14

Usage Pattern

The trait is typically used in user models to enable convenient authorization checks:


The canAny() method checks multiple abilities using OR logic - it returns true if the user has any of the specified abilities src/Access/Authorizable.php23-26

Sources: src/Access/Authorizable.php1-44


AuthorizesRequests Trait

The AuthorizesRequests trait provides authorization methods designed for use in controllers and request handlers. It includes intelligent ability name resolution that automatically maps controller method names to standard resource ability names (e.g., indexviewAny, showview).

Sources: src/Access/AuthorizesRequests.php1-77

Methods

MethodParametersReturn TypeDescription
authorize(mixed $ability, mixed $arguments)ability, argumentsResponseAuthorize action for current user (throws on failure)
authorizeForUser(?Authenticatable $user, mixed $ability, mixed $arguments)user, ability, argumentsResponseAuthorize action for specific user (throws on failure)
parseAbilityAndArguments(mixed $ability, mixed $arguments)ability, argumentsarrayParse and normalize ability name and arguments
normalizeGuessedAbilityName(string $ability)abilitystringMap controller method name to ability name
resourceAbilityMap()nonearrayGet the resource method to ability name mapping

The authorize() methods throw AuthorizationException on failure src/Access/AuthorizesRequests.php16-35

Sources: src/Access/AuthorizesRequests.php1-77

Ability Name Resolution

The trait implements automatic ability name detection using the resource ability map. When a model instance is passed as the first argument instead of a string ability name, the trait uses debug_backtrace() to determine the calling method name and maps it to the appropriate ability src/Access/AuthorizesRequests.php40-49


Sources: src/Access/AuthorizesRequests.php40-59

Resource Ability Map

The default resource ability mapping aligns with RESTful controller conventions src/Access/AuthorizesRequests.php64-75:

Controller MethodAbility NameCommon Use Case
indexviewAnyList all resources
showviewView a single resource
createcreateShow create form
storecreateStore new resource
editupdateShow edit form
updateupdateUpdate existing resource
destroydeleteDelete resource

The mapping can be customized by overriding the resourceAbilityMap() method in controller classes.

Sources: src/Access/AuthorizesRequests.php64-75

Usage Patterns


Example Usage:


Sources: src/Access/AuthorizesRequests.php1-77


Trait Relationships and Integration

The three utility traits serve distinct purposes within the authorization system:


Sources: src/Access/HandlesAuthorization.php1-41 src/Access/Authorizable.php1-44 src/Access/AuthorizesRequests.php1-77


Trait Comparison

AspectHandlesAuthorizationAuthorizableAuthorizesRequests
Primary UsePolicy classesUser modelsControllers
PurposeCreate authorization responsesCheck user abilitiesAuthorize controller actions
Method Visibilityprotectedpublicpublic (authorize), protected (helpers)
Gate IntegrationNone (response creation only)Via Gate::forUser($this)Via Gate::authorize()
ReturnsResponse objectsbool valuesResponse (throws on deny)
Key FeatureStatus code customizationFluent ability checksAutomatic ability name resolution
Typical Locationapp/Policies/*.phpapp/Models/User.phpapp/Controller/*.php
Throws ExceptionsNoNoYes (AuthorizationException)
Contract ImplementationNoneAuthorizable contractNone

Sources: src/Access/HandlesAuthorization.php1-41 src/Access/Authorizable.php1-44 src/Access/AuthorizesRequests.php1-77


Method Invocation Flow


This diagram illustrates how the three traits work together in a typical authorization flow. The controller uses AuthorizesRequests to authorize an action, which invokes the Gate. The Gate evaluates the policy, which uses HandlesAuthorization to create responses. Separately, the controller can check abilities on the user model via the Authorizable trait, which also delegates to the Gate.

Sources: src/Access/HandlesAuthorization.php1-41 src/Access/Authorizable.php1-44 src/Access/AuthorizesRequests.php1-77