VOOZH about

URL: https://deepwiki.com/hypervel/auth/5.2-guard-contracts

⇱ Guard Contracts | hypervel/auth | DeepWiki


Loading...
Menu

Guard Contract

Purpose and Scope

This document describes the Guard and StatefulGuard contract interfaces that all authentication guards must implement. These contracts define the core authentication API that guards expose to the rest of the application, ensuring consistent behavior across different authentication strategies.

For information about specific guard implementations, see SessionGuard, JwtGuard, and RequestGuard. For the factory pattern that creates guards, see AuthManager.

Sources: src/Contracts/Guard.php1-39


Guard Interface

The Guard interface defines the fundamental authentication operations that all guards must support. This contract is located at src/Contracts/Guard.php7-38 and specifies six core methods.

Core Methods

MethodReturn TypePurpose
check()boolDetermine if the current user is authenticated
guest()boolDetermine if the current user is a guest (not authenticated)
user()?AuthenticatableGet the currently authenticated user instance
id()int|string|nullGet the ID of the currently authenticated user
validate(array $credentials)boolValidate user credentials without logging in
setUser(Authenticatable $user)voidManually set the current authenticated user

The interface provides type-safe contracts for authentication state checking, user retrieval, credential validation, and user assignment. All guards implementing this interface can be used interchangeably through the AuthManager.

Sources: src/Contracts/Guard.php8-38


Interface Hierarchy

The guard contract system uses a two-tier hierarchy to distinguish between stateless and stateful authentication strategies.


Guard Interface Architecture

The base Guard interface defines authentication state operations, while StatefulGuard adds session-specific login/logout operations. Guards that maintain server-side state (like SessionGuard) implement StatefulGuard, while stateless guards (like JwtGuard and RequestGuard) implement only the base Guard interface. The GuardHelpers trait provides default implementations for shared logic across all guard types.

Sources: src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php1-116


StatefulGuard Interface

The StatefulGuard interface extends the base Guard contract to add methods for managing authentication sessions. Guards implementing this interface maintain server-side authentication state across requests, typically using session storage.

Additional Stateful Methods

Stateful guards must additionally implement:

MethodReturn TypePurpose
attempt(array $credentials, bool $remember)boolAttempt to authenticate using credentials
login(Authenticatable $user, bool $remember)voidLog a user into the application
loginUsingId(mixed $id, bool $remember)Authenticatable|falseLog a user in by their ID
logout()voidLog the user out of the application
viaRemember()boolDetermine if user was authenticated via "remember me" cookie

Only SessionGuard implements the full StatefulGuard interface, as it maintains persistent authentication state across requests. The JwtGuard and RequestGuard implementations do not support stateful sessions and thus implement only the base Guard interface.

Sources: src/Guards/GuardHelpers.php85-94


GuardHelpers Trait: Default Implementations

The GuardHelpers trait at src/Guards/GuardHelpers.php14-115 provides default implementations for most Guard interface methods. All three guard implementations use this trait to avoid code duplication.

Method Implementations Provided


GuardHelpers Method Dependencies

The trait provides implementations that delegate to abstract methods or properties that concrete guards must define. The user() method is the primary abstraction point—most helper methods depend on it. The trait expects guards to define a $provider property and, for stateful guards, login() and attempt() methods.

Sources: src/Guards/GuardHelpers.php14-115

Key Implementation Details

Authentication State Methods (src/Guards/GuardHelpers.php77-80 src/Guards/GuardHelpers.php41-44):

  • check() returns true if user() is not null
  • guest() returns the inverse of check()
  • hasUser() directly checks if user() is not null

User Identification (src/Guards/GuardHelpers.php49-56):

  • id() retrieves the auth identifier from the user via $user->getAuthIdentifier()
  • Returns null if no user is authenticated

Authentication Enforcement (src/Guards/GuardHelpers.php21-28):

  • authenticate() throws AuthenticationException if user() returns null
  • This is used by middleware to enforce authentication requirements

Credential Validation (src/Guards/GuardHelpers.php99-102 src/Guards/GuardHelpers.php107-114):

  • validate() delegates to attempt() with $remember = false
  • hasValidCredentials() uses the provider's validateCredentials() method

Stateful Operations (src/Guards/GuardHelpers.php85-94):

  • loginUsingId() retrieves user from provider then calls login()
  • Returns the user object on success, false on failure

Sources: src/Guards/GuardHelpers.php21-114


Implementation Pattern

Concrete guard classes follow a consistent pattern when implementing the Guard contract with GuardHelpers.

Typical Guard Structure


Guard Implementation Pattern

Each guard must implement the core user() and setUser() methods, define a $provider property, and use the GuardHelpers trait. Stateful guards additionally implement session management methods. This pattern ensures consistent behavior while allowing guards to customize authentication logic.

Sources: src/Guards/GuardHelpers.php1-116 src/Contracts/Guard.php1-39

Minimum Implementation Requirements

To create a functional guard, the following must be provided:

  1. User Resolution - Implement user(): ?Authenticatable to retrieve the authenticated user
  2. User Assignment - Implement setUser(Authenticatable $user): void to manually set the user
  3. Provider Property - Define protected UserProvider $provider for user data access
  4. Interface Declaration - Declare implementation of Guard or StatefulGuard
  5. Trait Usage - Use GuardHelpers trait for default implementations

For stateful guards, additionally implement:

  • attempt(array $credentials, bool $remember): bool
  • login(Authenticatable $user, bool $remember): void
  • logout(): void

Sources: src/Guards/GuardHelpers.php14-115 src/Contracts/Guard.php7-38


Method Execution Flow

The following diagram illustrates the call chain when common guard methods are invoked.


Guard Method Execution Flow

This sequence shows how guard method calls flow through the trait's default implementations to the concrete guard's user() method. Most operations depend on user() returning the authenticated user instance. The validate() method follows a more complex path through attempt() and the user provider.

Sources: src/Guards/GuardHelpers.php21-114 src/Contracts/Guard.php7-38


Contract Usage in the Authentication System

The Guard contract enables polymorphic guard resolution through the AuthManager factory.

Guard Contract Integration


Guard Contract in Authentication Flow

The AuthManager returns guards typed as the Guard interface, allowing application code to work with any guard implementation without knowing its concrete type. This abstraction enables configuration-driven guard selection and simplifies guard customization.

Sources: src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php1-116

Type Safety and Interface Segregation

The two-tier contract hierarchy provides interface segregation:

  • Base Guard: Suitable for stateless authentication (JWT, custom callbacks)
  • StatefulGuard: Required for session-based authentication with login/logout

This design prevents stateless guards from exposing misleading session-related methods. Code that needs session features can type-hint StatefulGuard, while code that only needs authentication state can type-hint the base Guard interface.

Sources: src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php85-94


Complete Method Reference

The following table catalogs all methods across the Guard and StatefulGuard interfaces, showing where each is defined and implemented.

MethodContractProvided ByPurposeReturns
check()GuardGuardHelpers Line 77-80Check if authenticatedbool
guest()GuardGuardHelpers Line 41-44Check if guestbool
user()GuardConcrete guardGet current user?Authenticatable
id()GuardGuardHelpers Line 49-56Get user IDint|string|null
validate()GuardGuardHelpers Line 99-102Validate credentialsbool
setUser()GuardConcrete guardSet current uservoid
authenticate()ExtensionGuardHelpers Line 21-28Get user or throwAuthenticatable
hasUser()ExtensionGuardHelpers Line 33-36Check user existsbool
getProvider()ExtensionGuardHelpers Line 61-64Get user providerUserProvider
setProvider()ExtensionGuardHelpers Line 69-72Set user providervoid
loginUsingId()ExtensionGuardHelpers Line 85-94Login by IDAuthenticatable|bool
attempt()StatefulGuardConcrete stateful guardAttempt loginbool
login()StatefulGuardConcrete stateful guardPerform loginvoid
logout()StatefulGuardConcrete stateful guardPerform logoutvoid
viaRemember()StatefulGuardConcrete stateful guardCheck remember cookiebool

Methods listed as "Extension" are provided by GuardHelpers but not defined in the Guard interface contract—they are convenience methods available to all guards using the trait.

Sources: src/Contracts/Guard.php8-38 src/Guards/GuardHelpers.php14-115