VOOZH about

URL: https://deepwiki.com/hypervel/auth/3.3-authorization-responses

⇱ Authorization Responses | hypervel/auth | DeepWiki


Loading...
Menu

Authorization Responses

Purpose

This document details the Response class, which encapsulates authorization decisions with allow/deny outcomes, optional messages, codes, and HTTP status codes. Authorization responses provide a structured way to represent authorization results that can be inspected programmatically or converted to exceptions for error handling.

For the overall authorization system, see page 3. For the Gate implementation, see page 3.1. For policies, see page 3.2.

Sources: src/Access/Response.php1-159

Overview

The authorization system returns Response objects from all authorization checks. Each response encapsulates:

  • Allowed/Denied state: Boolean indicating authorization success
  • Message: Optional human-readable explanation
  • Code: Optional machine-readable identifier
  • HTTP Status: Optional status code for web framework integration

Sources: src/Access/Response.php10-32

Response Class Structure

Class Definition and Interfaces

The Response class implements two interfaces for flexible usage:

Response Class Structure


Sources: src/Access/Response.php10-32 src/Access/Response.php143-158

Response Properties

PropertyTypeDescriptionAccess
allowedboolAuthorization decision (true = allowed, false = denied)Protected, via constructor
message?stringHuman-readable explanation of the decisionProtected, via constructor
codeint|string|nullMachine-readable identifier for the resultProtected, via constructor
status?intHTTP status code for web responsesProtected, set via methods

Sources: src/Access/Response.php15-27

Creating Responses

Static Factory Methods

The Response class provides static factory methods for creating responses:

Response Factory Methods


Sources: src/Access/Response.php37-64

Factory Method Reference

MethodSignatureReturnsUse Case
allow()allow(?string $message, int|string|null $code): ResponseAllow responseAuthorization granted
deny()deny(?string $message, int|string|null $code): ResponseDeny responseAuthorization denied
denyWithStatus()denyWithStatus(int $status, ?string $message, int|string|null $code): ResponseDeny response with HTTP statusCustom HTTP status needed
denyAsNotFound()denyAsNotFound(?string $message, int|string|null $code): ResponseDeny response with 404 statusHide resource existence

Sources: src/Access/Response.php37-64

Response Methods

Inspection Methods

The Response class provides methods to inspect the authorization decision:

MethodReturnsDescription
allowed()boolReturns true if authorization was granted
denied()boolReturns true if authorization was denied (inverse of allowed())
message()?stringReturns the human-readable message
code()int|string|nullReturns the machine-readable code
status()?intReturns the HTTP status code if set

Sources: src/Access/Response.php69-96 src/Access/Response.php135-138

Fluent Modification Methods

Response objects can be modified using fluent methods:

MethodReturnsDescription
withStatus(int $status)staticSets HTTP status code
asNotFound()staticSets HTTP status to 404

Fluent Method Chaining


Sources: src/Access/Response.php117-130

HTTP Status Code Integration

Status Code Purpose

Authorization responses can include HTTP status codes to provide semantic meaning for web responses:

Status CodeMethodSemantic MeaningUse Case
403withStatus(403)ForbiddenUser authenticated but lacks permission
404asNotFound()Not FoundHide resource existence for security
401withStatus(401)UnauthorizedUser not authenticated (rare, handled by authentication)
CustomwithStatus($code)Application-specificCustom authorization scenarios

Sources: src/Access/Response.php117-130

Status Code Patterns

HTTP Status Decision Tree


Sources: src/Access/Response.php117-130

Practical Status Code Usage

The choice between 403 and 404 depends on security requirements:

  • 403 Forbidden: Use when the user should know the resource exists but lacks permission
  • 404 Not Found: Use to hide the resource's existence from unauthorized users (security through obscurity)

Sources: src/Access/Response.php127-130 src/Access/Response.php53-56

Response Conversion Features

Array Conversion

The Response class implements Arrayable for serialization:

toArray() Output Structure


The toArray() method returns:

[
 'allowed' => bool,
 'message' => ?string,
 'code' => int|string|null
]

Note: HTTP status is not included in the array representation.

Sources: src/Access/Response.php143-150

String Conversion

The Response class implements Stringable via __toString(), which returns the message:

(string) $response === $response->message()

This enables responses to be used directly in string contexts.

Sources: src/Access/Response.php155-158

Exception Handling

The authorize() Method

The authorize() method converts denied responses into exceptions:

Response.authorize() Flow


Sources: src/Access/Response.php103-112

AuthorizationException Integration

The AuthorizationException class stores the original response and provides bidirectional conversion:

DirectionMethodPurpose
Response → Exceptionauthorize()Throw exception on denial
Exception → ResponsetoResponse()Recreate response from exception

Bidirectional Conversion


Sources: src/Access/Response.php103-112 src/Access/AuthorizationException.php87-90

Exception Properties

The AuthorizationException class extends Exception with authorization-specific features:

Property/MethodTypeDescription
response?ResponseOriginal response object
status?intHTTP status code
response()?ResponseGet the stored response
setResponse(Response)staticSet the response (fluent)
withStatus(int)staticSet HTTP status (fluent)
asNotFound()staticSet status to 404 (fluent)
hasStatus()boolCheck if status is set
status()?intGet the HTTP status
toResponse()ResponseConvert back to response

Sources: src/Access/AuthorizationException.php14-90

Usage Patterns

Pattern 1: Boolean Inspection

Inspect responses without throwing exceptions:

Boolean Inspection Pattern


Use when:

  • Building API responses with detailed authorization info
  • Implementing conditional UI elements
  • Logging authorization decisions without failing

Sources: src/Access/Response.php69-96

Pattern 2: Exception-Based Authorization

Throw exceptions on denial for immediate error handling:

Exception-Based Pattern


Use when:

  • Protecting controller actions
  • Implementing fail-fast authorization
  • Simplifying control flow (exception handling vs explicit checks)

Sources: src/Access/Response.php103-112

Pattern 3: Custom HTTP Status Responses

Set specific HTTP status codes for web responses:

Status Code Pattern


Use when:

  • Hiding resource existence for security
  • Providing semantic HTTP responses
  • Integrating with web frameworks

Sources: src/Access/Response.php117-130 src/Access/Response.php53-64

Integration with Gate System

Gate Method Return Values

The Gate class methods return different types based on their purpose:

Gate MethodReturnsThrows on DenialUse Case
check()boolNoSimple boolean checks
allows()boolNoAlias for check()
denies()boolNoInverse boolean check
inspect()ResponseNoDetailed response inspection
authorize()voidYesException-based authorization
any()boolNoCheck multiple abilities
none()boolNoEnsure all abilities denied

Gate Response Flow


Sources: src/Access/Response.php103-112

Response Lifecycle in Authorization

Complete Authorization Flow with Response


Sources: src/Access/Response.php37-112

Best Practices

Choosing Response Messages and Codes

Authorization responses support three levels of information:

ComponentAudiencePurposeExample
MessageHuman usersUI display, error messages"You cannot edit posts by other users"
CodeApplication codeProgrammatic handling, error classification"insufficient_permissions"
StatusHTTP clientsWeb framework integration, REST semantics403, 404

Information Hierarchy


Sources: src/Access/Response.php24-28

Response vs Exception Pattern Selection

ScenarioRecommended PatternRationale
Controller action protectionGate::authorize() (exception)Fail-fast, simplified control flow
API response buildingGate::inspect() (response)Need full response details for JSON
Conditional UI renderingGate::check() (boolean)Simple true/false needed
Custom error handlingGate::inspect() then authorize()Inspect first, throw if needed
Batch authorization checksGate::inspect() multiple (response)Collect all results, then decide

Sources: src/Access/Response.php69-112

HTTP Status Code Guidelines

Status Code Decision Matrix

User AuthenticatedHas PermissionResource ExistsRecommended StatusMethod
YesNoYes403 Forbiddendeny().withStatus(403)
YesNoNo/Hidden404 Not Founddeny().asNotFound()
YesNoWant to hide404 Not Founddeny().asNotFound()
NoN/AN/A401 UnauthorizedHandled by auth middleware

Sources: src/Access/Response.php117-130 src/Access/AuthorizationException.php53-66

Exception Safety Patterns

When using exception-based authorization:

  1. Always catch AuthorizationException when using authorize() methods unless middleware handles it
  2. Check status availability with hasStatus() before accessing status() to avoid null issues
  3. Preserve response information by using exception.toResponse() to access original response data
  4. Set appropriate status codes early in the response chain for consistent error handling

Sources: src/Access/AuthorizationException.php71-90 src/Access/Response.php103-112

Summary

The Authorization Response system in Hypervel Auth provides a flexible way to represent, communicate, and handle authorization results. Through the Response class and AuthorizationException, the system enables both boolean-based and exception-based handling patterns, with support for messages, codes, and HTTP status integration.

Refresh this wiki

On this page