VOOZH about

URL: https://deepwiki.com/hypervel/auth/3-authorization-system

⇱ Authorization System | hypervel/auth | DeepWiki


Loading...
Menu

Authorization

Purpose and Scope

This document provides an overview of the authorization subsystem in the hypervel/auth package. Authorization determines what actions an authenticated user is permitted to perform. While authentication answers "who are you?" (see Authentication), authorization answers "what can you do?".

The authorization system centers on the Gate class, which evaluates permissions through abilities (simple callbacks) and policies (class-based rules). The system supports before/after hooks, resource-based authorization, and comprehensive event-driven auditing.

For detailed documentation of specific components, see:


Core Concepts

Authorization vs Authentication

ConcernAuthenticationAuthorization
Question"Who are you?""What can you do?"
PurposeVerify identityCheck permissions
ResultUser objectAllow/Deny response
Failure HTTP Code401 Unauthorized403 Forbidden
MiddlewareAuthenticateAuthorize

Gate

The Gate is the central authorization engine that evaluates whether a user can perform an action. It is implemented by the Hypervel\Auth\Access\Gate class and registered in the DI container through GateFactory.

The Gate supports multiple authorization strategies:

StrategyUse CaseDefinition
AbilitiesSimple permission checksClosures or callbacks registered via define()
PoliciesResource-based authorizationClasses with methods mapped to model types
Before CallbacksGlobal permission overridesExecute before all checks, can short-circuit
After CallbacksLogging and auditingExecute after checks, can modify results

Abilities

Abilities are named permission checks registered as closures or class methods. They represent discrete actions a user can perform:


Policies

Policies are classes that organize authorization logic around a particular model type. They contain methods corresponding to actions that can be performed on the model:


Sources: src/Access/Gate.php1-654


Authorization Architecture

The following diagram shows the complete authorization subsystem and how components interact:


Sources: src/Access/Gate.php1-654 src/ConfigProvider.php1-34


Authorization Evaluation Flow

The following diagram illustrates how the Gate evaluates an authorization request:


Sources: src/Access/Gate.php303-333 src/Access/Gate.php463-485 src/Access/Gate.php527-554


Key Components

Gate Class

The Gate class (src/Access/Gate.php23-654) is the core authorization engine. It maintains several internal arrays and uses dependency injection:

PropertyTypePurpose
$containerContainerInterfaceDI container for resolving policies
$userResolverClosureCallback that returns current user
$abilitiesarrayRegistered ability callbacks
$stringCallbacksarrayAbilities defined using Class@method notation
$policiesarrayMapping of model classes to policy classes
$beforeCallbacksarrayGlobal callbacks executed before checks
$afterCallbacksarrayGlobal callbacks executed after checks
$defaultDenialResponse?ResponseDefault response when authorization fails

Gate Methods

The Gate provides multiple methods for checking permissions:

MethodReturn TypePurpose
allows()boolCheck if ability is allowed
denies()boolCheck if ability is denied
check()boolCheck if all abilities are allowed
any()boolCheck if any ability is allowed
none()boolCheck if all abilities are denied
authorize()ResponseCheck ability, throw on denial
inspect()ResponseGet detailed Response object
raw()mixedGet raw callback result

Sources: src/Access/Gate.php229-333

Ability Definition

Abilities can be defined in three ways:

1. Closure:


2. Class@method string:


3. Array callback:


Sources: src/Access/Gate.php122-139

Resource Authorization

The resource() method defines multiple abilities for a resource following RESTful conventions:


Default abilities:

  • viewAny - List all resources
  • view - View single resource
  • create - Create new resource
  • update - Update existing resource
  • delete - Delete resource

Sources: src/Access/Gate.php144-159


Policy Resolution

When authorization checks are performed with model arguments, the Gate automatically resolves policies:


The Gate checks:

  1. Exact class match in $policies array
  2. Parent class match using is_subclass_of()
  3. Falls back to ability callbacks if no policy found

Sources: src/Access/Gate.php493-512 src/Access/Gate.php519-522


Before and After Callbacks

Before Callbacks

Before callbacks execute before any authorization check and can short-circuit the entire process:


If a before callback returns a non-null value, that result is used immediately without checking abilities or policies.

Sources: src/Access/Gate.php209-214 src/Access/Gate.php415-426

After Callbacks

After callbacks execute after the authorization check completes and can be used for logging:


After callbacks can also override null results from the main check.

Sources: src/Access/Gate.php219-224 src/Access/Gate.php431-444


Guest Support

The Gate can evaluate permissions for guest users (null) if the callback explicitly allows it:


The Gate checks if callbacks allow guests by inspecting:

  1. Nullable type hints (?User)
  2. Default null parameters ($user = null)

Sources: src/Access/Gate.php338-398


On-Demand Authorization

The Gate provides methods for one-off authorization checks without defining abilities:

MethodPurpose
allowIf()Authorize if condition is true
denyIf()Authorize if condition is false

These methods accept:

  • Boolean values
  • Closures that return booleans
  • Response objects

Sources: src/Access/Gate.php78-115


Integration with Dependency Injection

The authorization system is registered in the DI container via ConfigProvider:


GateFactory creates Gate instances with:

  • Container reference for policy resolution
  • User resolver from AuthManager
  • Empty arrays for abilities, policies, and callbacks (configured at runtime)

Sources: src/ConfigProvider.php18-23


Authorization Response Types

The Gate returns Response objects that contain:

PropertyTypePurpose
allowedboolWhether action is authorized
message?stringHuman-readable reason
code?stringMachine-readable code

The Response class provides:

  • allow() - Create allowed response
  • deny() - Create denied response
  • authorize() - Throw exception if denied
  • allowed() - Check if allowed
  • denied() - Check if denied

For detailed information, see Authorization Responses and Exceptions.

Sources: src/Access/Gate.php281-296


Event-Driven Auditing

Every authorization check dispatches a GateEvaluated event containing:

  • User who performed the check
  • Ability name
  • Arguments passed
  • Result (allow/deny)

This enables comprehensive audit trails for compliance and security monitoring. For details, see Authorization Events.

Sources: src/Access/Gate.php449-458


Code Entity Reference

The following table maps authorization concepts to their code implementations:

ConceptCode EntityLocation
Authorization EngineGate classsrc/Access/Gate.php23
Permission Checkallows(), denies(), check()src/Access/Gate.php229-266
Ability Definitiondefine()src/Access/Gate.php122
Resource Authorizationresource()src/Access/Gate.php144
Policy Registrationpolicy()src/Access/Gate.php199
Before Hookbefore()src/Access/Gate.php209
After Hookafter()src/Access/Gate.php219
Authorization Checkauthorize()src/Access/Gate.php273
Detailed Resultinspect()src/Access/Gate.php281
Raw Resultraw()src/Access/Gate.php303
Policy ResolutiongetPolicyFor()src/Access/Gate.php493
User ResolutionresolveUser()src/Access/Gate.php624
Ability ResolutionresolveAuthCallback()src/Access/Gate.php463
Policy Method CallcallPolicyMethod()src/Access/Gate.php578
Policy Before HookcallPolicyBefore()src/Access/Gate.php562
Event DispatchdispatchGateEvaluatedEvent()src/Access/Gate.php449
DI RegistrationConfigProvidersrc/ConfigProvider.php13
Gate ContractGateContract interfaceReferenced in src/ConfigProvider.php10
Gate FactoryGateFactory classReferenced in src/ConfigProvider.php7

Sources: src/Access/Gate.php1-654 src/ConfigProvider.php1-34