VOOZH about

URL: https://deepwiki.com/hypervel/permission/3.2-role-middleware

⇱ Role Middleware | hypervel/permission | DeepWiki


Loading...
Menu

Role Middleware

The RoleMiddleware class provides HTTP route-level access control by verifying authenticated users possess required roles. It implements the PSR-15 MiddlewareInterface and acts as a gatekeeper for protected routes by delegating role checking to the user model's hasAnyRoles method. For permission-based route protection, see page 3.1.

Overview

Located at src/Middlewares/RoleMiddleware.php RoleMiddleware intercepts HTTP requests and enforces role-based authorization before request handlers execute. It integrates with AuthManager for authentication and requires user models to implement the hasAnyRoles method (provided by the HasRole trait documented in page 2.2).


Middleware Authorization Flow

Sources: src/Middlewares/RoleMiddleware.php28-75


Middleware Request Processing Flow

Sources: src/Middlewares/RoleMiddleware.php28-75

Core Implementation

Constructor and Dependency Injection

The RoleMiddleware constructor accepts ContainerInterface to resolve the AuthManager instance at runtime:


Sources: src/Middlewares/RoleMiddleware.php24-26

Process Method Workflow

The process method signature accepts variadic role arguments:


Authorization Steps:

StepActionCode ReferenceException on Failure
1Retrieve authenticated user$auth->user()UnauthorizedException (401)
2Verify hasAnyRoles method existsmethod_exists($user, 'hasAnyRoles')UnauthorizedException (500)
3Parse and split roles`explode('', ...)`
4Check user has any required roles$user->hasAnyRoles($roles)RoleException (403)
5Continue to handler$handler->handle($request)None

Sources: src/Middlewares/RoleMiddleware.php28-75

Role Specification and Parsing

Role Input Formats

The static parseRolesToString method normalizes various role input types into a pipe-separated string for OR-based role checking:


Role Parsing Flow

Supported Input Types:

TypeExtraction MethodExample
BackedEnum$role->valueString/int value
UnitEnum$role->nameEnum case name
stringDirect value'admin'
intDirect value1
arrayFlattened, then processed['admin', 'editor']

The method uses Collection::make()->flatten()->values()->all() to normalize nested arrays before mapping enum types and joining with pipe delimiter.

Sources: src/Middlewares/RoleMiddleware.php85-101

Middleware Registration

The using() Method

The static using method generates unique middleware identifiers for route registration:


The method returns a string in the format: Hypervel\Permission\Middlewares\RoleMiddleware:role1|role2|role3


Middleware Identifier Generation

This identifier pattern enables framework routing systems to:

  • Cache middleware instances with specific role configurations
  • Reuse identical middleware configurations across routes
  • Differentiate between middleware with different role requirements

Sources: src/Middlewares/RoleMiddleware.php80-83

Exception Handling

Exception Types and Conditions

The middleware throws three exception types based on specific failure conditions:

Exception ClassHTTP StatusConditionThrown AtAdditional Context
UnauthorizedException401$user is nullLine 36Required roles in message
UnauthorizedException500hasAnyRoles method missingLine 46User identifier + required roles
RoleException403hasAnyRoles() returns falseLine 59User identifier + roles array

Sources: src/Middlewares/RoleMiddleware.php36-43 src/Middlewares/RoleMiddleware.php45-55 src/Middlewares/RoleMiddleware.php58-72

RoleException Details

The RoleException class extends Hypervel\HttpMessage\Exceptions\HttpException and includes role context:


The exception provides a roles() method returning the array of required roles that the user failed to possess. This enables error handlers and loggers to capture role-based authorization failures with full context.

Sources: src/Exceptions/RoleException.php12-27

hasAnyRoles Contract Requirement

The middleware expects the authenticated user object to implement the hasAnyRoles method. This method is provided by the HasRole trait (see page 2.2) and accepts an array of role identifiers, returning true if the user possesses any of the specified roles.

If the method is missing, the middleware throws UnauthorizedException with status 500, indicating a configuration or integration error rather than an authorization failure.

Sources: src/Middlewares/RoleMiddleware.php45-55

Integration with Auth System


Authentication and Role Verification Sequence

The middleware relies on the AuthManager from the hypervel/auth package and expects user models to implement the hasAnyRoles method from the HasRole trait.

Sources: src/Middlewares/RoleMiddleware.php33-34 src/Middlewares/RoleMiddleware.php45-46 src/Middlewares/RoleMiddleware.php58