VOOZH about

URL: https://deepwiki.com/hypervel/auth/5.3-userprovider-contract

⇱ UserProvider Contract | hypervel/auth | DeepWiki


Loading...
Menu

UserProvider Contract

Purpose and Scope

The UserProvider contract defines the interface for retrieving and validating user data from persistent storage. This contract abstracts the data layer from the authentication guards, enabling different storage strategies (ORM-based, query-based, or custom) to be used interchangeably.

For implementation details, see EloquentUserProvider and DatabaseUserProvider. For an overview of how user providers fit into the authentication system, see User Providers.

Sources: src/Contracts/UserProvider.php1-26


Contract Definition

The UserProvider interface is located at src/Contracts/UserProvider.php7-25 and defines three core methods that all user provider implementations must provide:


Sources: src/Contracts/UserProvider.php7-25


Method Specifications

retrieveById()

Signature: public function retrieveById($identifier): ?Authenticatable

This method retrieves a user by their unique identifier. The identifier is typically a primary key value (e.g., user ID) stored in session data or JWT claims.

ParameterTypeDescription
$identifiermixedThe unique identifier for the user (typically an integer or string)
Returns?AuthenticatableThe authenticated user instance, or null if not found

Behavior Requirements:

  • Must return null if no user exists with the given identifier
  • Must return an object implementing the Authenticatable contract if found
  • Should perform a single query to retrieve the user by their authentication identifier name (as defined by getAuthIdentifierName())

Example Usage by Guards:

  • SessionGuard calls this method when retrieving the user from session ID stored in auth.{guard}.id
  • JwtGuard calls this method using the subject claim (sub) from the JWT token

Sources: src/Contracts/UserProvider.php9-14 src/Providers/EloquentUserProvider.php37-44


retrieveByCredentials()

Signature: public function retrieveByCredentials(array $credentials): ?Authenticatable

This method retrieves a user by searching for matches against the provided credentials array, excluding password fields. This is typically used during login to find a user by their username, email, or other identifying attributes.

ParameterTypeDescription
$credentialsarrayAssociative array of user attributes (e.g., ['email' => 'user@example.com', 'password' => '...'])
Returns?AuthenticatableThe matched user instance, or null if not found

Behavior Requirements:

  • Must exclude any key containing the word "password" from the search criteria
  • Must return null if credentials array is empty after filtering
  • Should support multiple credential fields (e.g., searching by email OR username)
  • Should support array values for whereIn queries
  • Should support Closure values for custom query logic
  • Must return the first matching user if multiple matches exist

Example Credential Arrays:


Sources: src/Contracts/UserProvider.php16-19 src/Providers/EloquentUserProvider.php49-77


validateCredentials()

Signature: public function validateCredentials(Authenticatable $user, array $credentials): bool

This method validates that the provided credentials match the given user instance. This is primarily used to verify passwords during authentication attempts.

ParameterTypeDescription
$userAuthenticatableThe user instance to validate against
$credentialsarrayThe credentials to validate (must contain a password key)
Returnsbooltrue if credentials are valid, false otherwise

Behavior Requirements:

  • Must extract the password from $credentials['password']
  • Must compare the plain-text password against the user's hashed password using a secure hasher
  • Must call $user->getAuthPassword() to retrieve the user's stored password hash
  • Should use the hypervel/hashing package for password verification

Security Considerations:

  • This method must use timing-safe comparison through the hasher to prevent timing attacks
  • The plain-text password should never be stored or logged
  • Failed validation should not reveal whether the user exists or if the password is wrong

Sources: src/Contracts/UserProvider.php21-24 src/Providers/EloquentUserProvider.php94-99


Integration with Authentication System

The UserProvider contract serves as the bridge between authentication guards and the persistent user data store:


Sources: src/Contracts/UserProvider.php1-26 src/Providers/EloquentUserProvider.php1-185


Authentication Flow Sequence

The following sequence demonstrates how guards use user provider methods during authentication:


Sources: src/Contracts/UserProvider.php1-26 src/Providers/EloquentUserProvider.php37-99


Method Call Patterns by Guard Type

Different guard implementations use the UserProvider methods in distinct patterns:

Guard TyperetrieveById()retrieveByCredentials()validateCredentials()
SessionGuardEvery request (to load user from session ID)During attempt() loginDuring attempt() login
JwtGuardEvery request (to load user from JWT sub claim)During attempt() loginDuring attempt() login
RequestGuardNever (uses callback)Never (uses callback)Never (uses callback)

Notes:

  • SessionGuard and JwtGuard cache the user in request context after first retrieval to avoid redundant queries
  • RequestGuard bypasses the user provider entirely, using custom callback logic
  • Password validation only occurs during initial authentication, not on subsequent requests

Sources: src/Contracts/UserProvider.php1-26


Contract Relationship with Authenticatable

The UserProvider contract has a tight coupling with the Authenticatable contract:


Required Authenticatable Methods:

  • getAuthIdentifierName() - Returns the name of the unique identifier column (e.g., "id")
  • getAuthIdentifier() - Returns the unique identifier value for the user
  • getAuthPassword() - Returns the password hash for validation

For details on the Authenticatable contract, see Authenticatable Contract.

Sources: src/Contracts/UserProvider.php1-26 src/Providers/EloquentUserProvider.php37-99


Configuration

User providers are configured in the auth.php configuration file under the providers key:

Configuration KeyTypeDescription
driverstringThe provider driver name (e.g., "eloquent", "database")
modelstringThe fully-qualified class name of the user model (for eloquent driver)
tablestringThe database table name (for database driver)

Example Configuration:


Guards reference user providers by name:


For more details on configuration, see Configuration.

Sources: src/Contracts/UserProvider.php1-26


Implementation Requirements

When implementing the UserProvider contract, implementations must:

  1. Return Type Compliance: Methods must return ?Authenticatable or bool as specified
  2. Null Safety: Handle missing users gracefully by returning null
  3. Security: Use secure password hashing through hypervel/hashing
  4. Performance: Consider caching strategies to minimize database queries
  5. Query Flexibility: Support various credential formats (arrays, closures, etc.)
  6. Password Exclusion: Never include password fields in search queries

Available Implementations:

Sources: src/Contracts/UserProvider.php1-26 src/Providers/EloquentUserProvider.php1-185


Common Implementation Patterns

Password Hashing Dependency

All user provider implementations should accept a Hypervel\Hashing\Contracts\Hasher instance for secure password validation:

Constructor Pattern:


Validation Pattern:


Sources: src/Providers/EloquentUserProvider.php26-29 src/Providers/EloquentUserProvider.php94-99


Credential Filtering

Implementations must filter out password fields when searching by credentials:

Standard Pattern:


This prevents password hashes from being used as search criteria and ensures at least one non-password field is provided.

Sources: src/Providers/EloquentUserProvider.php51-59


Extension Points

The UserProvider contract enables several extension patterns:

Custom Provider Registration

Custom user providers can be registered through the AuthManager:


Query Modification

Some implementations support query callbacks for modifying retrieval logic:


For details on custom guard and provider registration, see AuthManager.

Sources: src/Providers/EloquentUserProvider.php179-184