VOOZH about

URL: https://deepwiki.com/hypervel/permission/3-http-middleware-integration

⇱ HTTP Middleware Integration | hypervel/permission | DeepWiki


Loading...
Menu

HTTP Middleware Integration

Purpose and Scope

This document explains how the Hypervel Permission package enforces authorization at the HTTP request level through PSR-15 middleware components. The middleware layer acts as the gatekeeper for protected routes, intercepting requests before they reach application handlers and validating that authenticated users have the required permissions or roles.

This document covers:

  • The architectural role of middleware in the authorization system
  • The request processing lifecycle and authorization flow
  • Exception handling and error responses
  • How middleware components integrate with the authentication system and trait methods

For detailed documentation of specific middleware implementations, see Permission Middleware and Role Middleware. For information about the trait methods that middleware relies on, see HasPermission Trait and HasRole Trait. For exception details, see Exception Handling.

Middleware Architecture

The package provides two PSR-15 compliant middleware classes that intercept HTTP requests and enforce authorization requirements:

Middleware ClassPurposeTrait Method RequiredException on Failure
PermissionMiddlewareValidates user has specific permissionshasAnyPermissions()PermissionException (403)
RoleMiddlewareValidates user has specific roleshasAnyRoles()RoleException (403)

Both middleware classes share common characteristics:

  • Implement Psr\Http\Server\MiddlewareInterface
  • Use dependency injection via Hyperf\Contract\ContainerInterface
  • Retrieve authenticated user through Hypervel\Auth\AuthManager
  • Throw UnauthorizedException (401) when no user is authenticated
  • Throw UnauthorizedException (500) when user model lacks required trait methods

Sources: src/Middlewares/PermissionMiddleware.php19-26 src/Middlewares/RoleMiddleware.php19-26

Request Processing Lifecycle

The following diagram illustrates the complete HTTP request flow when middleware authorization is applied:


Sources: src/Middlewares/PermissionMiddleware.php28-75 src/Middlewares/RoleMiddleware.php28-75

Component Integration

The middleware components integrate with multiple system layers to perform authorization:


Sources: src/Middlewares/PermissionMiddleware.php24-34 src/Middlewares/RoleMiddleware.php24-34

Authorization Validation Process

Both middleware classes follow a three-phase validation process:

Phase 1: Authentication Verification

The middleware first verifies that a user is authenticated by calling AuthManager::user(). If no user is returned, an UnauthorizedException with status code 401 is thrown immediately.

User is not authenticated. Cannot check permissions: {permission_list}
User is not authenticated. Cannot check roles: {role_list}

Sources: src/Middlewares/PermissionMiddleware.php35-43 src/Middlewares/RoleMiddleware.php35-43

Phase 2: Trait Method Verification

The middleware verifies that the user model implements the required trait method using method_exists():

  • PermissionMiddleware checks for hasAnyPermissions method
  • RoleMiddleware checks for hasAnyRoles method

If the method is missing, an UnauthorizedException with status code 500 is thrown, indicating a configuration error:

User "{identifier}" does not have the "hasAnyPermissions" method. Cannot check permissions: {permission_list}
User "{identifier}" does not have the "hasAnyRoles" method. Cannot check roles: {role_list}

Sources: src/Middlewares/PermissionMiddleware.php45-55 src/Middlewares/RoleMiddleware.php45-55

Phase 3: Authorization Check

The middleware calls the appropriate trait method with the required permissions or roles. Parameters are parsed from middleware configuration and split by the pipe (|) delimiter to support multiple values.

If the authorization check returns false, the corresponding exception is thrown with status code 403:

  • PermissionException includes the list of required permissions
  • RoleException includes the list of required roles

Sources: src/Middlewares/PermissionMiddleware.php56-72 src/Middlewares/RoleMiddleware.php56-72

Parameter Parsing

Both middleware classes support flexible input types for specifying permissions or roles:

Input TypeHandlingExample
stringUsed directly'edit-posts'
intCast to string123
BackedEnumExtract ->value propertyPermission::EDIT_POSTS->value
UnitEnumExtract ->name propertyRole::ADMIN->name
arrayFlattened and processed recursively['read', 'write']

The parsePermissionsToString() and parseRolesToString() static methods handle this conversion:

  1. Flatten nested arrays using Collection::make()->flatten()->values()
  2. Map each element based on its type using a match expression
  3. Join results with pipe delimiter: implode('|', $processed)

Multiple permissions/roles are specified by separating them with the pipe character, allowing "any" logic: the user must have at least one of the specified values.

Sources: src/Middlewares/PermissionMiddleware.php85-101 src/Middlewares/RoleMiddleware.php85-101

Middleware Registration Pattern

Both middleware classes provide a static using() method for generating unique middleware identifiers when registering routes. This method:

  1. Accepts variadic parameters of mixed types (strings, integers, enums, arrays)
  2. Converts all parameters to a normalized string representation
  3. Returns a string in the format: {ClassName}:{normalized_parameters}

This allows dynamic middleware registration with parameters:


Sources: src/Middlewares/PermissionMiddleware.php80-83 src/Middlewares/RoleMiddleware.php80-83

Exception Handling Strategy

The middleware layer implements a clear exception hierarchy to communicate different types of authorization failures:

Status CodeException ClassThrown WhenContains
401UnauthorizedExceptionNo authenticated userError message with required permissions/roles
500UnauthorizedExceptionUser model missing trait methodUser identifier and required method name
403PermissionExceptionUser lacks required permissionsUser identifier and permission list
403RoleExceptionUser lacks required rolesUser identifier and role list

The 500 status code for missing trait methods is intentional: this indicates a server configuration error (the developer forgot to add the trait to the user model), not a client authorization error.

Both PermissionException and RoleException store the list of required permissions/roles, allowing exception handlers to provide detailed error messages or logging.

Sources: src/Middlewares/PermissionMiddleware.php36-71 src/Middlewares/RoleMiddleware.php36-71

Trait Method Contracts

The middleware components rely on specific trait methods being present in the user model. These methods are provided by the HasPermission and HasRole traits:

hasAnyPermissions Contract

PermissionMiddleware calls hasAnyPermissions(array $permissions) which:

  • Accepts an array of permission names/IDs
  • Returns true if user has ANY of the specified permissions (OR logic)
  • Checks both direct permissions and permissions inherited through roles
  • Respects forbidden permissions (explicit denials override grants)

hasAnyRoles Contract

RoleMiddleware calls hasAnyRoles(array $roles) which:

  • Accepts an array of role names/IDs
  • Returns true if user has ANY of the specified roles (OR logic)
  • Performs exact role name/ID matching
  • Uses cached role data for performance

For detailed information about these trait methods and their implementation, see HasPermission Trait and HasRole Trait.

Sources: src/Middlewares/PermissionMiddleware.php45-58 src/Middlewares/RoleMiddleware.php45-58

Integration with PSR-15

Both middleware classes fully comply with PSR-15 (HTTP Server Request Handlers) specification:

  1. Interface Implementation: Implement Psr\Http\Server\MiddlewareInterface
  2. Method Signature: Define process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
  3. Request Delegation: Call $handler->handle($request) only after successful authorization
  4. Response Return: Return ResponseInterface from either the handler or by throwing HTTP exceptions

This compliance ensures the middleware works seamlessly with any PSR-15 compatible HTTP framework or middleware pipeline.

Sources: src/Middlewares/PermissionMiddleware.php19-75 src/Middlewares/RoleMiddleware.php19-75