rafalmasiarek / authkit
Lightweight and extensible PHP authentication library
Requires
- php: >=8.1
- ext-pdo: *
Requires (Dev)
- phpunit/phpunit: ^10.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.0
- v1.2.0
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.0
- dev-fix/footer-includes-key
- dev-docs/php-docs-readme-gen
- dev-shared-config/php-AuthKit
- dev-chore/bump-manifest-2.1.2
- dev-fix/abstracthook-missing-onlogoutforced
- dev-5-mask-sensitive-fields-in-usergetall-jsonserialize-and-tojson
- dev-fix-v1.1.0
- dev-pre-release-v1.0.0
This package is auto-updated.
Last update: 2026-11-17 23:37:41 UTC
README
Lightweight, extensible PHP 8.1+ authentication library.
- Registration & login with secure password hashing
- Server-side session tokens stored in DB with optional TTL
- Pluggable login extension pipeline — deny or challenge after credentials pass
- Multi-step challenge flows (MFA, email activation, device check, etc.)
- Pluggable credential provider — local PDO default, Cognito/Keycloak as external packages
- Pluggable password hasher —
NativePasswordHasherdefault - Pluggable token transport — PHP session (web) or Bearer header (API)
- Pluggable user ID policy — auto-increment default, UUID in your app
- Lean core schema —
userstable contains onlyid,email,password_hash; extra columns (e.g.active,suspended_at) declared by the extensions that need them - Optional hooks for audit and policy (rate-limit, IP checks, logging)
- Admin features: force logout by user / token / email
Works with MySQL/MariaDB and SQLite. Designed for Slim, Laminas, Symfony or plain PHP.
License
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
Source: https://opensource.org/licenses/MIT
See LICENSE for full details.
Authors
Installation
composer require rafalmasiarek/authkit
Quick start
use AuthKit\Auth; use AuthKit\Storage\PdoUserStorage; $pdo = new PDO('sqlite:/path/to/auth.sqlite'); $storage = new PdoUserStorage($pdo); $auth = new Auth($storage); $auth->createSchema(); // creates users + sessions tables (+ any registered extension tables) // Register $user = $auth->register('user@example.com', 'secret123'); // Login $login = $auth->login('user@example.com', 'secret123'); if ($login->isSuccess()) { // session stored automatically — redirect to dashboard } if ($login->isFailure()) { echo $login->message(); // "Invalid credentials." } // Current user (reads from session) $user = $auth->getUser(); // ?User // Logout $auth->logout();
Constructor
new Auth( storage: $storage, // UserStorageInterface — required hook: null, // HookInterface|null ttlSeconds: 3600, // int — 0 = no expiry messages: null, // MessageProviderInterface|null throwExceptions: false, // bool — throw AuthException on errors hasher: null, // PasswordHasherInterface|null — default: NativePasswordHasher credentials: null, // CredentialProviderInterface|null — default: PdoCredentialProvider challengeStorage: null, // ChallengeStorageInterface|null — required for challenge flows transport: null, // TokenTransportInterface|null — default: PhpSessionTransport clock: null, // ClockInterface|null — custom clock; takes precedence over timezone timezone: 'UTC', // string — timezone for built-in SystemClock; ignored when clock is provided )
Clock and timezone
By default Auth uses UTC for all session and challenge expiry calculations.
// Use a specific timezone with the built-in clock: new Auth($storage, timezone: 'Europe/Warsaw'); // Inject a custom ClockInterface implementation (clock takes precedence over timezone): new Auth($storage, clock: $appClock);
purgeExpiredTokens() and purgeExpired() are maintenance operations called outside the login flow.
They require an explicit DateTimeImmutable $now from the caller:
$storage->purgeExpiredTokens(new \DateTimeImmutable()); $challengeStorage->purgeExpired(new \DateTimeImmutable());
Login result
login() returns a Login object — never throws by default.
$login = $auth->login($email, $password); $login->isSuccess(); // bool $login->isFailure(); // bool $login->requiresChallenge(); // bool — set when an extension requires an extra step $login->token(); // ?string — session token on success $login->user(); // ?User — on success or challenge $login->message(); // string — failure reason $login->challengeToken(); // ?string — raw token for completeChallenge() $login->challengeType(); // ?string — e.g. 'mfa_totp', 'email_activation'
With throwExceptions: true — failure throws AuthException instead.
Login extension pipeline
Extensions run after credentials are verified. Register them with addLoginExtension().
The first deny or challenge decision terminates the pipeline.
use AuthKit\Extension\LoginExtensionInterface; use AuthKit\LoginContext; use AuthKit\LoginDecision; class ActiveUserExtension implements LoginExtensionInterface { public function decide(LoginContext $context): LoginDecision { if (!$context->user->get('active')) { return LoginDecision::deny('Account is not active.'); } return LoginDecision::allow(); } } $auth->addLoginExtension(new ActiveUserExtension());
LoginContext carries $user, $ip, $userAgent, and $credentialMeta from the credential provider.
Use $context->credential('key') to read individual metadata values.
Challenge flows (MFA, email activation, etc.)
An extension can require a second step instead of immediately allowing or denying.
use AuthKit\Extension\ChallengeExtensionInterface; use AuthKit\Challenge\ChallengeRecord; class TotpExtension implements ChallengeExtensionInterface { public function decide(LoginContext $context): LoginDecision { // trigger challenge — payload stored in ChallengeRecord return LoginDecision::challenge('mfa_totp', [ 'secret' => $context->user->get('totp_secret'), ]); } public function supportsChallenge(string $type): bool { return $type === 'mfa_totp'; } public function completeChallenge(ChallengeRecord $challenge, array $input): LoginDecision { $valid = verify_totp($challenge->payload['secret'], $input['code'] ?? ''); return $valid ? LoginDecision::allow() : LoginDecision::deny('Invalid code.'); } }
Flow:
// Step 1 — login $login = $auth->login($email, $password); if ($login->requiresChallenge()) { $_SESSION['challenge_token'] = $login->challengeToken(); // redirect to /login/mfa — type is $login->challengeType() } // Step 2 — verify code $login = $auth->completeChallenge($_SESSION['challenge_token'], ['code' => $input['code']]); if ($login->isSuccess()) { // session created — redirect to dashboard }
Challenge storage must be provided:
use AuthKit\Challenge\PdoChallengeStorage; $auth = new Auth($storage, challengeStorage: new PdoChallengeStorage($pdo));
Schema: (new PdoChallengeStorage($pdo))->createSchema();
Token transport
Controls how the active token is stored and read on the client side.
Web (default — PHP session)
use AuthKit\Transport\PhpSessionTransport; $auth = new Auth($storage); // PhpSessionTransport('auth_token') used by default // Custom session key: $auth = new Auth($storage, transport: new PhpSessionTransport('my_session_key'));
API (Bearer header)
use AuthKit\Transport\BearerHeaderTransport; $auth = new Auth($storage, transport: new BearerHeaderTransport()); // Login — return token to client in JSON $login = $auth->login($email, $password); // → ['token' => $login->token()] // Subsequent requests — client sends Authorization: Bearer <token> $user = $auth->getUser(); // reads from header automatically
External credential providers
AuthKit core authenticates into a local User object. External providers such as Cognito, Keycloak, Authentik or Zitadel should map their external identity to a local user inside their own CredentialProviderInterface implementation.
A credential provider may pass non-persistent login metadata through CredentialResult::success($user, $meta). This metadata is available in login extensions through LoginContext::credential().
// Inside a custom CognitoCredentialProvider::verify(): return CredentialResult::success($localUser, [ 'provider' => 'cognito', 'subject' => $claims['sub'], 'groups' => $claims['cognito:groups'] ?? [], 'email_verified' => $claims['email_verified'] ?? false, ]); // Inside a login extension: public function decide(LoginContext $ctx): LoginDecision { if ($ctx->credential('email_verified') === false) { return LoginDecision::deny('Email address is not verified.'); } return LoginDecision::allow(); }
Users authenticated via an external provider have no local password — password_hash is NULL in the database. PdoCredentialProvider explicitly rejects login attempts for such accounts.
This keeps AuthKit core storage-agnostic and avoids forcing external identity tables into the base package.
Hooks
All hook methods are optional — implement only what you need.
interface HookInterface { public function onBeforeRegister(string $email, string $password, array $fields): true|string; public function onRegisterSuccess(User $user): void; public function onRegisterFailure(string $email, \Throwable $e): void; public function onBeforeLogin(User $user): true|string; public function onLoginSuccess(User $user): void; public function onLoginFailure(string $email, AuthException $e): void; public function onLogout(User $user): void; public function onLogoutExpired(): void; public function onUserActive(User $user): void; public function onUserUpdated(User $user, array $changedFields): void; public function onLogoutForced(int|string $userId, ?string $reason, int $count): void; }
Force logout
$auth->forceLogoutUser($userOrId); // all sessions for a user $auth->forceLogoutEmail($email); // all sessions by email $auth->forceLogoutToken($token); // single session by token
Storage schema
PdoUserStorage::createSchema() creates the users and sessions tables.
PdoChallengeStorage::createSchema() creates auth_challenges (only needed for challenge flows).
Both support MySQL/MariaDB and SQLite.
Auth::createSchema() — preferred bootstrap entry point
Auth::createSchema() is the single call to initialise the full schema. It:
- Calls
PdoUserStorage::createSchema()with the correct column types for the configured ID policy. - Runs
additionalSchema()for every registered login extension that implementsSchemaProviderInterface. - Accepts extra
SchemaProviderInterfaceinstances for non-extension components (e.g. a mailer).
$auth = new Auth(new PdoUserStorage($pdo, new UuidUserIdPolicy())); $auth->addLoginExtension(new SuspendedUserExtension()); // may declare a suspended_at column $auth->addLoginExtension(new ActiveUserExtension()); // declares user_activations table $auth->createSchema($mailer); // mailer declares mail_tracking table
$storage->createSchema() still works for simple bootstraps without extensions.
User ID policy
UserIdPolicyInterface controls both ID generation and the schema column types used by createSchema().
| Method | Purpose |
|---|---|
generate() |
Returns the ID to insert, or null to let the database auto-increment. |
idColumnDefinition(string $driver) |
Full inline column definition for users.id. Drives PRIMARY KEY placement. |
userIdForeignType(string $driver) |
SQL type for sessions.user_id and any other FK referencing users.id. |
NullUserIdPolicy (default) — delegates to the database:
| Driver | users.id |
sessions.user_id |
|---|---|---|
| MySQL | INT NOT NULL AUTO_INCREMENT |
INT NOT NULL |
| SQLite | INTEGER PRIMARY KEY AUTOINCREMENT |
INTEGER NOT NULL |
Custom policy (e.g. UUID):
use AuthKit\UserId\UserIdPolicyInterface; final class UuidUserIdPolicy implements UserIdPolicyInterface { public function generate(): string { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } public function idColumnDefinition(string $driver): string { return 'CHAR(36) NOT NULL'; // createSchema() adds PRIMARY KEY (id) separately } public function userIdForeignType(string $driver): string { return 'CHAR(36) NOT NULL'; } } $storage = new PdoUserStorage($pdo, new UuidUserIdPolicy()); $auth = new Auth($storage); $auth->createSchema(); // users.id is CHAR(36), sessions.user_id is CHAR(36)
Extension schema — SchemaProviderInterface
Any class can declare the tables or columns it needs by implementing SchemaProviderInterface.
Auth::createSchema() automatically picks it up from registered login extensions and any explicitly
passed providers.
use AuthKit\Extension\LoginExtensionInterface; use AuthKit\Extension\SchemaProviderInterface; use AuthKit\LoginContext; use AuthKit\LoginDecision; final class BruteForceExtension implements LoginExtensionInterface, SchemaProviderInterface { public function decide(LoginContext $context): LoginDecision { // check login_attempts and ip_bans tables … return LoginDecision::allow(); } public function additionalSchema(string $driver): array { return [ 'CREATE TABLE IF NOT EXISTS login_attempts ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ip VARCHAR(45) NOT NULL, email VARCHAR(255) NOT NULL, attempted_at DATETIME NOT NULL DEFAULT NOW(), INDEX idx_ip_time (ip, attempted_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', 'CREATE TABLE IF NOT EXISTS ip_bans ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ip VARCHAR(45) NOT NULL UNIQUE, reason VARCHAR(255) NOT NULL, banned_at DATETIME NOT NULL DEFAULT NOW(), expires_at DATETIME NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', ]; } } // Bootstrap — one call creates everything: $auth->addLoginExtension(new BruteForceExtension($pdo)); $auth->createSchema(); // creates users, sessions, login_attempts, ip_bans
Rules for additionalSchema():
- Every statement must be idempotent —
CREATE TABLE IF NOT EXISTS,ALTER TABLE … ADD COLUMN IF NOT EXISTS, etc. - The method receives the PDO driver name (
'mysql','sqlite', …) so you can emit driver-specific SQL. - Statements run after the core
usersandsessionstables are created.
External users and nullable password_hash
password_hash is NULL in the default schema. PdoCredentialProvider treats a NULL or empty hash
as a disabled local login and returns a failure — this prevents accidental password bypass.
PdoUserStorage::createUser() is intended for local password accounts and requires a non-empty password hash.
External credential providers (Cognito, Keycloak, etc.) should manage user creation with their own logic,
or insert directly with password_hash = NULL for users that only authenticate externally.
v2.1.0 breaking changes
createSchema()no longer creates anactivecolumn on theuserstable.
v2 breaking changes
Auth::login()now returnsAuthKit\Login, not?string. Check$login->isSuccess(),$login->isFailure(), or$login->requiresChallenge().- Login-time
$additionalChecksparameter removed fromlogin(). UseLoginExtensionInterfaceinstead. UserStorageInterface::findByToken()requires a second argument:findByToken(string $token, \DateTimeImmutable $now).ChallengeStorageInterface::complete()requires a second argument:complete(ChallengeRecord $record, \DateTimeImmutable $now).ChallengeStorageInterface::purgeExpired()requires\DateTimeImmutable $now.PdoUserStorage::purgeExpiredTokens()requires\DateTimeImmutable $now.UserStorageInterface::storeToken()accepts?\DateTimeInterfaceinstead of?\DateTime.Authconstructor:$sessionKeyparameter removed — usetransport: new PhpSessionTransport('key')instead.Auth::setSessionKey()removed.- PHP
>=8.1required (was>=8.0). ramsey/uuiddependency removed — tokens are generated withbin2hex(random_bytes(32)).
Index
Classes
Auth—AuthKitChallengeRecord—AuthKit\ChallengePdoChallengeStorage—AuthKit\ChallengeSystemClock—AuthKit\ClockCredentialResult—AuthKit\CredentialPdoCredentialProvider—AuthKit\CredentialAuthException—AuthKit\ExceptionAbstractHook—AuthKit\HookLogin—AuthKitLoginContext—AuthKitLoginDecision—AuthKitDefaultMessageProvider—AuthKit\MessageNativePasswordHasher—AuthKit\PasswordPdoUserStorage—AuthKit\StorageBearerHeaderTransport—AuthKit\TransportPhpSessionTransport—AuthKit\TransportUser—AuthKitNullUserIdPolicy—AuthKit\UserId
Interfaces
ChallengeStorageInterface—AuthKit\ChallengeClockInterface—AuthKit\ClockCredentialProviderInterface—AuthKit\CredentialChallengeExtensionInterface—AuthKit\ExtensionLoginExtensionInterface—AuthKit\ExtensionSchemaProviderInterface—AuthKit\ExtensionHookInterface—AuthKit\HookMessageProviderInterface—AuthKit\MessagePasswordHasherInterface—AuthKit\PasswordSchemaMigrationInterface—AuthKit\StorageUserStorageInterface—AuthKit\StorageTokenTransportInterface—AuthKit\TransportUserIdPolicyInterface—AuthKit\UserId
Auth
final class — AuthKit\Auth · source
Core authentication facade. Handles registration, login (credential verification + extension pipeline), session lifecycle, and optional multi-step challenge flows (MFA, email activation, etc.).
Depends on: UserStorageInterface, HookInterface, MessageProviderInterface, PasswordHasherInterface, CredentialProviderInterface, ChallengeStorageInterface, TokenTransportInterface, ClockInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$throwExceptions |
bool |
private | Whether AuthException is thrown on errors instead of returning a message. |
$messages |
MessageProviderInterface |
private | — |
$hasher |
PasswordHasherInterface |
private | Used by register() to hash new passwords. |
$credentials |
CredentialProviderInterface |
private | Used by login() to verify credentials. |
$transport |
TokenTransportInterface |
private | Handles reading and writing the active token. |
$clock |
ClockInterface |
private | Used for session and challenge expiry calculations. |
$loginExtensions |
array<LoginExtensionInterface> |
private | Evaluated in order after credentials pass. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
addLoginExtension() |
public | void |
Register a login extension to be evaluated after credentials pass. Extensions are evaluated in registration order. The first deny or challenge decision terminates the pipeline. |
createSchema() |
public | void |
Bootstrap the database schema for the configured storage backend. Delegates to the storage layer if it implements SchemaMigrationInterface. Schema providers are collected from two sources: 1. Registered login extensions that implement SchemaProviderInterface (e.g. SuspendedUserExtension, ActiveUserExtension). 2. Any additional providers passed explicitly — use this for components that are not login extensions but own database tables (e.g. Mailer). Does nothing when the active storage does not support schema migration (e.g. an in-memory test stub). Typical bootstrap sequence: $auth = new Auth(new PdoUserStorage($pdo, new UuidUserIdPolicy()), ...); $auth->addLoginExtension(new SuspendedUserExtension()); $auth->addLoginExtension(new ActiveUserExtension()); $auth->createSchema($mailer); // extensions + Mailer mail_tracking table |
setThrowExceptions() |
public | void |
Set whether AuthException is thrown on authentication errors. |
register() |
public | User|string|null |
Register a new user. |
login() |
public | Login |
Verify credentials and run the login extension pipeline. Returns a Login in one of three states: - success : session created, token available. - failure : credentials invalid or an extension denied. - challengeRequired : credentials valid but an extension requires an extra step. |
completeChallenge() |
public | Login |
Complete a pending challenge step and create a session on success. |
isLoggedIn() |
public | bool |
Check whether a user is currently logged in. |
getUser() |
public | User|null |
Retrieve the currently logged-in user from the active session. |
logout() |
public | void |
Log out the currently logged-in user. |
forceLogoutUser() |
public | int |
Invalidate all sessions for a user across every device. |
forceLogoutToken() |
public | int |
Invalidate a single session by its token. |
forceLogoutEmail() |
public | int |
Invalidate all sessions for a user identified by email. |
updateUser() |
public | User |
Update fields on a user record. |
createSession() |
private | Login |
Create a session, persist the token, and store it in $_SESSION. |
issueChallenge() |
private | Login |
Store a ChallengeRecord and return a challengeRequired Login. |
findChallengeExtension() |
private | ChallengeExtensionInterface|null |
Find the first registered extension that handles the given challenge type. |
loginFailure() |
private | Login |
Return Login::failure() and optionally throw AuthException. |
fail() |
private | string |
Handle register-time failure: invoke hook callback, then throw or return message. |
callHook() |
private | void |
Call a hook method if the hook is configured and the method exists. |
callHookResult() |
private | mixed |
Call a hook method that returns a pass/fail result. Returns true when no hook is configured (meaning: proceed). |
__construct()
Auth __construct()
public function __construct(UserStorageInterface $storage, ?HookInterface $hook, int $ttlSeconds, ?MessageProviderInterface $messages, bool $throwExceptions, ?PasswordHasherInterface $hasher, ?CredentialProviderInterface $credentials, ?ChallengeStorageInterface $challengeStorage, ?TokenTransportInterface $transport, ?ClockInterface $clock, string $timezone)
| Param | Type | Description |
|---|---|---|
$storage |
UserStorageInterface |
User persistence layer. |
$hook |
HookInterface|null |
Optional lifecycle hooks. |
$ttlSeconds |
int |
Session TTL in seconds (0 = no expiry). |
$messages |
MessageProviderInterface|null |
Custom error messages. |
$throwExceptions |
bool |
Throw AuthException on errors. |
$hasher |
PasswordHasherInterface|null |
Hasher for register() (default: NativePasswordHasher). |
$credentials |
CredentialProviderInterface|null |
Credential verifier for login() (default: PdoCredentialProvider). |
$challengeStorage |
ChallengeStorageInterface|null |
Required only when using challenge extensions. |
$transport |
TokenTransportInterface|null |
Token read/write transport (default: PhpSessionTransport). |
$clock |
ClockInterface|null |
Custom clock (takes precedence over $timezone when provided). |
$timezone |
string |
Timezone for the built-in SystemClock (e.g. 'Europe/Warsaw'). Ignored when $clock is provided. Defaults to UTC. |
addLoginExtension()
Auth addLoginExtension()
public function addLoginExtension(LoginExtensionInterface $extension): void
Register a login extension to be evaluated after credentials pass. Extensions are evaluated in registration order. The first deny or challenge decision terminates the pipeline.
| Param | Type | Description |
|---|---|---|
$extension |
LoginExtensionInterface |
— |
createSchema()
Auth createSchema()
public function createSchema(SchemaProviderInterface $additionalProviders): void
Bootstrap the database schema for the configured storage backend. Delegates to the storage layer if it implements SchemaMigrationInterface. Schema providers are collected from two sources: 1. Registered login extensions that implement SchemaProviderInterface (e.g. SuspendedUserExtension, ActiveUserExtension). 2. Any additional providers passed explicitly — use this for components that are not login extensions but own database tables (e.g. Mailer). Does nothing when the active storage does not support schema migration (e.g. an in-memory test stub). Typical bootstrap sequence: $auth = new Auth(new PdoUserStorage($pdo, new UuidUserIdPolicy()), ...); $auth->addLoginExtension(new SuspendedUserExtension()); $auth->addLoginExtension(new ActiveUserExtension()); $auth->createSchema($mailer); // extensions + Mailer mail_tracking table
| Param | Type | Description |
|---|---|---|
$additionalProviders |
SchemaProviderInterface |
— |
setThrowExceptions()
Auth setThrowExceptions()
public function setThrowExceptions(bool $value): void
Set whether AuthException is thrown on authentication errors.
| Param | Type | Description |
|---|---|---|
$value |
bool |
— |
register()
Auth register()
public function register(string $email, string $password, array $customFields, array $additionalChecks): User|string|null
Register a new user.
| Param | Type | Description |
|---|---|---|
$email |
string |
User's email address. |
$password |
string |
Plain-text password. |
$customFields |
array<string, mixed> |
Additional fields to persist. |
$additionalChecks |
array<callable> |
Legacy pre-registration callbacks. |
Returns: User\|string\|null — Created User on success, or an error message on failure.
| Throws | When |
|---|---|
AuthException |
When $throwExceptions is true and an error occurs. |
login()
Auth login()
public function login(string $email, string $password): Login
Verify credentials and run the login extension pipeline. Returns a Login in one of three states: - success : session created, token available. - failure : credentials invalid or an extension denied. - challengeRequired : credentials valid but an extension requires an extra step.
| Param | Type | Description |
|---|---|---|
$email |
string |
User's email address. |
$password |
string |
Plain-text password. |
Returns: Login
| Throws | When |
|---|---|
AuthException |
When $throwExceptions is true and login is rejected. |
completeChallenge()
Auth completeChallenge()
public function completeChallenge(string $challengeToken, array $input): Login
Complete a pending challenge step and create a session on success.
| Param | Type | Description |
|---|---|---|
$challengeToken |
string |
Raw token stored client-side (e.g. $_SESSION['authkit_challenge']). |
$input |
array<string, mixed> |
User-supplied verification data. |
Returns: Login
| Throws | When |
|---|---|
AuthException |
When $throwExceptions is true and verification fails. |
\RuntimeException |
When no ChallengeStorageInterface is configured. |
isLoggedIn()
Auth isLoggedIn()
public function isLoggedIn(): bool
Check whether a user is currently logged in.
Returns: bool
getUser()
Auth getUser()
public function getUser(): ?User
Retrieve the currently logged-in user from the active session.
Returns: User\|null
forceLogoutUser()
Auth forceLogoutUser()
public function forceLogoutUser(User|int|string $userOrId, ?string $reason): int
Invalidate all sessions for a user across every device.
| Param | Type | Description |
|---|---|---|
$userOrId |
User|int|string |
User object or ID. |
$reason |
string|null |
Optional audit reason passed to the hook. |
Returns: int — Number of invalidated sessions.
forceLogoutToken()
Auth forceLogoutToken()
public function forceLogoutToken(string $token, ?string $reason): int
Invalidate a single session by its token.
| Param | Type | Description |
|---|---|---|
$token |
string |
Session token to revoke. |
$reason |
string|null |
Optional audit reason. |
Returns: int — 1 if removed, 0 otherwise.
forceLogoutEmail()
Auth forceLogoutEmail()
public function forceLogoutEmail(string $email, ?string $reason): int
Invalidate all sessions for a user identified by email.
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$reason |
string|null |
Optional audit reason. |
Returns: int — Number of invalidated sessions.
updateUser()
Auth updateUser()
public function updateUser(User $user, array $updates): User
Update fields on a user record.
| Param | Type | Description |
|---|---|---|
$user |
User |
User to update. |
$updates |
array<string, mixed> |
Fields to update. |
Returns: User — Updated user.
createSession()
Auth createSession()
private function createSession(User $user): Login
Create a session, persist the token, and store it in $_SESSION.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
Returns: Login
issueChallenge()
Auth issueChallenge()
private function issueChallenge(User $user, LoginContext $context, LoginDecision $decision): Login
Store a ChallengeRecord and return a challengeRequired Login.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
$context |
LoginContext |
— |
$decision |
LoginDecision |
— |
Returns: Login
| Throws | When |
|---|---|
\RuntimeException |
When no ChallengeStorageInterface is configured. |
findChallengeExtension()
Auth findChallengeExtension()
private function findChallengeExtension(string $type): ?ChallengeExtensionInterface
Find the first registered extension that handles the given challenge type.
| Param | Type | Description |
|---|---|---|
$type |
string |
— |
Returns: ChallengeExtensionInterface\|null
loginFailure()
Auth loginFailure()
private function loginFailure(string $message): Login
Return Login::failure() and optionally throw AuthException.
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
Returns: Login
| Throws | When |
|---|---|
AuthException |
— |
fail()
Auth fail()
private function fail(string $message, ?callable $hookCallback): string
Handle register-time failure: invoke hook callback, then throw or return message.
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$hookCallback |
callable|null |
— |
Returns: string
| Throws | When |
|---|---|
AuthException |
— |
callHook()
Auth callHook()
private function callHook(string $method, mixed $args): void
Call a hook method if the hook is configured and the method exists.
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$args |
mixed |
— |
callHookResult()
Auth callHookResult()
private function callHookResult(string $method, mixed $args): mixed
Call a hook method that returns a pass/fail result. Returns true when no hook is configured (meaning: proceed).
| Param | Type | Description |
|---|---|---|
$method |
string |
— |
$args |
mixed |
— |
Returns: mixed
ChallengeRecord
final class — AuthKit\Challenge\ChallengeRecord · source
Immutable value object representing a persisted challenge step. Created when a LoginExtensionInterface returns LoginDecision::challenge(). The raw token travels exclusively on the client side; only its sha256 hash is stored in the database.
Depends on: DateTime
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
isExpired() |
public | bool |
— |
isExhausted() |
public | bool |
— |
isCompleted() |
public | bool |
— |
__construct()
ChallengeRecord __construct()
public function __construct(string $id, int|string $userId, string $type, array $payload, int $maxAttempts, DateTime $expiresAt, string $ip, string $userAgent, int $attempts, ?DateTime $completedAt)
| Param | Type | Description |
|---|---|---|
$id |
string |
UUID v4 record identifier. |
$userId |
int|string |
ID of the user being challenged. |
$type |
string |
Challenge type handled by a ChallengeExtensionInterface. |
$payload |
array |
— |
$maxAttempts |
int |
Maximum allowed verification attempts before exhaustion. |
$expiresAt |
DateTime |
Point in time when this challenge becomes invalid. |
$ip |
string |
Client IP at time of challenge creation. |
$userAgent |
string |
Client User-Agent at time of challenge creation. |
$attempts |
int |
Current failed attempt count (mutable after hydration). |
$completedAt |
DateTime|null |
When the challenge was successfully completed (mutable). |
isExpired()
ChallengeRecord isExpired()
public function isExpired(): bool
Returns: bool — True when the challenge has passed its expiry time.
isExhausted()
ChallengeRecord isExhausted()
public function isExhausted(): bool
Returns: bool — True when the maximum attempt count has been reached.
isCompleted()
ChallengeRecord isCompleted()
public function isCompleted(): bool
Returns: bool — True when the challenge has been successfully completed.
ChallengeStorageInterface
interface — AuthKit\Challenge\ChallengeStorageInterface · source
Persists and retrieves challenge records for multi-step login flows. Only the sha256 hash of the raw token is stored — the raw token travels exclusively on the client side (e.g. $_SESSION['authkit_challenge']).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
store() |
public | void |
Persist a new challenge record. |
findByToken() |
public | ChallengeRecord|null |
Find a non-completed challenge by its raw token. |
complete() |
public | void |
Mark a challenge as successfully completed. The implementation must record $now as the completion timestamp. Pass Auth::now() or an equivalent value from your clock to keep timestamps consistent with the rest of the auth layer. |
incrementAttempts() |
public | void |
Increment the failed attempt counter for a challenge. |
purgeExpired() |
public | void |
Delete all expired challenge records. The caller is responsible for supplying the reference time. Typically called from a maintenance job or cron — not part of the login flow. |
createSchema() |
public | void |
Create the auth_challenges table if it does not exist. |
store()
ChallengeStorageInterface store()
public function store(ChallengeRecord $record, string $rawToken): void
Persist a new challenge record.
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
Challenge data to persist. |
$rawToken |
string |
Raw token sent to the client (sha256 hash stored in DB). |
findByToken()
ChallengeStorageInterface findByToken()
public function findByToken(string $rawToken): ?ChallengeRecord
Find a non-completed challenge by its raw token.
| Param | Type | Description |
|---|---|---|
$rawToken |
string |
The raw token held by the client. |
Returns: ChallengeRecord\|null — Null when not found or already completed.
complete()
ChallengeStorageInterface complete()
public function complete(ChallengeRecord $record, \DateTimeImmutable $now): void
Mark a challenge as successfully completed. The implementation must record $now as the completion timestamp. Pass Auth::now() or an equivalent value from your clock to keep timestamps consistent with the rest of the auth layer.
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
Challenge to mark as completed. |
$now |
\DateTimeImmutable |
Current time used as the completed_at timestamp. |
incrementAttempts()
ChallengeStorageInterface incrementAttempts()
public function incrementAttempts(ChallengeRecord $record): void
Increment the failed attempt counter for a challenge.
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
— |
purgeExpired()
ChallengeStorageInterface purgeExpired()
public function purgeExpired(\DateTimeImmutable $now): void
Delete all expired challenge records. The caller is responsible for supplying the reference time. Typically called from a maintenance job or cron — not part of the login flow.
| Param | Type | Description |
|---|---|---|
$now |
\DateTimeImmutable |
Records with expires_at before this value will be deleted. |
createSchema()
ChallengeStorageInterface createSchema()
public function createSchema(): void
Create the auth_challenges table if it does not exist.
PdoChallengeStorage
final class — AuthKit\Challenge\PdoChallengeStorage · source
PDO-backed challenge storage supporting MySQL/MariaDB and SQLite. Token security: only sha256($rawToken) is stored. The raw token is returned to the caller and kept client-side. A DB leak cannot be used to replay challenges.
implements ChallengeStorageInterface
Depends on: PDO
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
store() |
public | void |
— |
findByToken() |
public | ?ChallengeRecord |
— |
complete() |
public | void |
— |
incrementAttempts() |
public | void |
— |
purgeExpired() |
public | void |
— |
createSchema() |
public | void |
— |
hydrate() |
private | ChallengeRecord |
Hydrate a database row into a ChallengeRecord. |
__construct()
PdoChallengeStorage __construct()
public function __construct(PDO $pdo)
| Param | Type | Description |
|---|---|---|
$pdo |
PDO |
Database connection. |
store()
PdoChallengeStorage store()
public function store(ChallengeRecord $record, string $rawToken): void
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
— |
$rawToken |
string |
— |
findByToken()
PdoChallengeStorage findByToken()
public function findByToken(string $rawToken): ?ChallengeRecord
| Param | Type | Description |
|---|---|---|
$rawToken |
string |
— |
Returns: ?ChallengeRecord
complete()
PdoChallengeStorage complete()
public function complete(ChallengeRecord $record, \DateTimeImmutable $now): void
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
— |
$now |
\DateTimeImmutable |
— |
incrementAttempts()
PdoChallengeStorage incrementAttempts()
public function incrementAttempts(ChallengeRecord $record): void
| Param | Type | Description |
|---|---|---|
$record |
ChallengeRecord |
— |
purgeExpired()
PdoChallengeStorage purgeExpired()
public function purgeExpired(\DateTimeImmutable $now): void
| Param | Type | Description |
|---|---|---|
$now |
\DateTimeImmutable |
— |
hydrate()
PdoChallengeStorage hydrate()
private function hydrate(array $row): ChallengeRecord
Hydrate a database row into a ChallengeRecord.
| Param | Type | Description |
|---|---|---|
$row |
array<string, mixed> |
— |
Returns: ChallengeRecord
ClockInterface
interface — AuthKit\Clock\ClockInterface · source
Provides the current time as an immutable value object. Compatible with the PSR-20 clock contract — any PSR-20 implementation satisfies this interface without modification.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
now() |
public | \DateTimeImmutable |
Return the current time. |
now()
ClockInterface now()
public function now(): \DateTimeImmutable
Return the current time.
Returns: \DateTimeImmutable
SystemClock
final class — AuthKit\Clock\SystemClock · source
System clock — returns the current wall-clock time in the configured timezone.
implements ClockInterface
Depends on: \DateTimeZone
| Property | Type | Visibility | Description |
|---|---|---|---|
$tz |
\DateTimeZone |
private readonly | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
now() |
public | \DateTimeImmutable |
— |
__construct()
SystemClock __construct()
public function __construct(\DateTimeZone|string $timezone)
| Param | Type | Description |
|---|---|---|
$timezone |
\DateTimeZone|string |
Timezone for now(). Defaults to UTC. |
| Throws | When |
|---|---|
\Exception |
When an invalid timezone string is provided. |
CredentialProviderInterface
interface — AuthKit\Credential\CredentialProviderInterface · source
Verifies raw credentials and returns the matching user on success.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
verify() |
public | CredentialResult |
Verify the supplied credentials. |
verify()
CredentialProviderInterface verify()
public function verify(array $credentials, array $context): CredentialResult
Verify the supplied credentials.
| Param | Type | Description |
|---|---|---|
$credentials |
array<string, mixed> |
Raw input (e.g. ['email' => ..., 'password' => ...]). |
$context |
array<string, mixed> |
Optional request context (e.g. 'ip', 'user_agent') for logging or rate-limiting. |
Returns: CredentialResult
CredentialResult
final class — AuthKit\Credential\CredentialResult · source
Result of a credential verification attempt.
Depends on: User
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
private | — | — |
success() |
public static | self |
Create a successful result with the verified user. |
failure() |
public static | self |
Create a failure result with a reason message. |
isSuccess() |
public | bool |
— |
user() |
public | User|null |
— |
message() |
public | string |
— |
meta() |
public | mixed |
Return provider metadata or a single key from it. With no argument, returns the full metadata array. With a key, returns that value or $default when not present. |
__construct()
CredentialResult __construct()
private function __construct(bool $success, ?User $user, string $message, array $meta)
| Param | Type | Description |
|---|---|---|
$success |
bool |
Whether credentials were valid. |
$user |
User|null |
Authenticated user, or null on failure. |
$message |
string |
Failure reason, or empty string on success. |
$meta |
array<string, mixed> |
Provider-specific metadata (e.g. provider name, JWT claims). |
success()
CredentialResult success()
public static function success(User $user, array $meta): self
Create a successful result with the verified user.
| Param | Type | Description |
|---|---|---|
$user |
User |
Authenticated user. |
$meta |
array<string, mixed> |
Optional provider metadata passed to the login extension pipeline. |
Returns: self
failure()
CredentialResult failure()
public static function failure(string $message, array $meta): self
Create a failure result with a reason message.
| Param | Type | Description |
|---|---|---|
$message |
string |
Human-readable failure reason. |
$meta |
array<string, mixed> |
Optional provider metadata (e.g. for audit logging). |
Returns: self
isSuccess()
CredentialResult isSuccess()
public function isSuccess(): bool
Returns: bool — True when credentials were valid.
user()
CredentialResult user()
public function user(): ?User
Returns: User\|null — Authenticated user, or null on failure.
message()
CredentialResult message()
public function message(): string
Returns: string — Failure reason, or empty string on success.
meta()
CredentialResult meta()
public function meta(?string $key, mixed $default): mixed
Return provider metadata or a single key from it. With no argument, returns the full metadata array. With a key, returns that value or $default when not present.
| Param | Type | Description |
|---|---|---|
$key |
string|null |
Key to retrieve, or null for the full array. |
$default |
mixed |
Returned when the key is not found. |
Returns: mixed
PdoCredentialProvider
final class — AuthKit\Credential\PdoCredentialProvider · source
PDO-backed credential provider for email + password authentication. Looks up the user by email, verifies the password via the configured hasher, and automatically re-hashes the stored password if the hasher signals it is outdated.
implements CredentialProviderInterface
Depends on: UserStorageInterface, PasswordHasherInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
verify() |
public | CredentialResult |
— |
__construct()
PdoCredentialProvider __construct()
public function __construct(UserStorageInterface $storage, PasswordHasherInterface $hasher)
| Param | Type | Description |
|---|---|---|
$storage |
UserStorageInterface |
User persistence layer. |
$hasher |
PasswordHasherInterface |
Password hashing and verification. |
verify()
PdoCredentialProvider verify()
public function verify(array $credentials, array $context): CredentialResult
| Param | Type | Description |
|---|---|---|
$credentials |
array{email: string, password: string} |
— |
$context |
array<string, mixed> |
Unused by this provider; available for logging or rate-limiting in custom implementations. |
Returns: CredentialResult
AuthException
class — AuthKit\Exception\AuthException · source
Class AuthException Represents an authentication-related exception.
extends \Exception
ChallengeExtensionInterface
interface — AuthKit\Extension\ChallengeExtensionInterface · source
Extension that both initiates and handles a specific challenge type. When decide() returns LoginDecision::challenge($type), Auth stores a ChallengeRecord and returns a challenge token to the caller. When the user submits their response, Auth::completeChallenge() dispatches to the matching ChallengeExtensionInterface. Only Auth creates the session — never the extension.
extends LoginExtensionInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
supportsChallenge() |
public | bool |
Returns true when this extension handles the given challenge type. |
completeChallenge() |
public | LoginDecision |
Verify the user's response to a pending challenge. Return LoginDecision::allow() to let Auth create the session. Return LoginDecision::deny(reason) on invalid input — Auth increments the attempt counter. |
supportsChallenge()
ChallengeExtensionInterface supportsChallenge()
public function supportsChallenge(string $type): bool
Returns true when this extension handles the given challenge type.
| Param | Type | Description |
|---|---|---|
$type |
string |
Challenge type identifier (e.g. 'mfa_totp', 'email_activation'). |
Returns: bool
completeChallenge()
ChallengeExtensionInterface completeChallenge()
public function completeChallenge(ChallengeRecord $challenge, array $input): LoginDecision
Verify the user's response to a pending challenge. Return LoginDecision::allow() to let Auth create the session. Return LoginDecision::deny(reason) on invalid input — Auth increments the attempt counter.
| Param | Type | Description |
|---|---|---|
$challenge |
ChallengeRecord |
The persisted challenge record. |
$input |
array<string, mixed> |
User-supplied verification data (e.g. ['code' => '123456']). |
Returns: LoginDecision — allow() or deny(reason).
LoginExtensionInterface
interface — AuthKit\Extension\LoginExtensionInterface · source
Evaluates whether a login attempt should proceed after credentials are verified. Extensions are registered via Auth::addLoginExtension() and evaluated in registration order. The first deny or challenge decision terminates the pipeline. A session is created only when every registered extension returns allow.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
decide() |
public | LoginDecision |
Evaluate the login context and return a decision. |
decide()
LoginExtensionInterface decide()
public function decide(LoginContext $context): LoginDecision
Evaluate the login context and return a decision.
| Param | Type | Description |
|---|---|---|
$context |
LoginContext |
Authenticated user with request metadata. |
Returns: LoginDecision — allow(), deny(reason), or challenge(type, payload).
SchemaProviderInterface
interface — AuthKit\Extension\SchemaProviderInterface · source
Declares additional database schema required by an extension or policy. Implement this interface on any class that needs custom tables or columns alongside the core users/sessions tables. PdoUserStorage::createSchema() accepts variadic SchemaProviderInterface instances and executes their SQL after the core tables are created. Every statement in the returned array MUST be idempotent: use CREATE TABLE IF NOT EXISTS, ALTER TABLE … ADD COLUMN IF NOT EXISTS, etc.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
additionalSchema() |
public | list<string> |
Return SQL statements that set up the additional schema this provider needs. |
additionalSchema()
SchemaProviderInterface additionalSchema()
public function additionalSchema(string $driver): array
Return SQL statements that set up the additional schema this provider needs.
| Param | Type | Description |
|---|---|---|
$driver |
string |
PDO driver name: 'mysql', 'sqlite', 'pgsql', etc. |
Returns: list<string> — Idempotent SQL statements executed in order.
AbstractHook
abstract class — AuthKit\Hook\AbstractHook · source
implements HookInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
onRegisterSuccess() |
public | void |
— |
onRegisterFailure() |
public | void |
— |
onLoginSuccess() |
public | void |
— |
onLoginFailure() |
public | void |
— |
onBeforeRegister() |
public | true|string |
— |
onBeforeLogin() |
public | true|string |
— |
onLogout() |
public | void |
— |
onLogoutExpired() |
public | void |
— |
onLogoutForced() |
public | void |
— |
onUpdate() |
public | void |
— |
onUserActive() |
public | void |
— |
onUserUpdated() |
public | void |
— |
onRegisterSuccess()
AbstractHook onRegisterSuccess()
public function onRegisterSuccess(User $user): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onRegisterFailure()
AbstractHook onRegisterFailure()
public function onRegisterFailure(string $email, AuthException $e): void
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$e |
AuthException |
— |
onLoginSuccess()
AbstractHook onLoginSuccess()
public function onLoginSuccess(User $user): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onLoginFailure()
AbstractHook onLoginFailure()
public function onLoginFailure(string $email, AuthException $e): void
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$e |
AuthException |
— |
onBeforeRegister()
AbstractHook onBeforeRegister()
public function onBeforeRegister(string $email, string $password, array $fields): true|string
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$password |
string |
— |
$fields |
array |
— |
Returns: true\|string
onBeforeLogin()
AbstractHook onBeforeLogin()
public function onBeforeLogin(User $user): true|string
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
Returns: true\|string
onLogout()
AbstractHook onLogout()
public function onLogout(User $user): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onLogoutForced()
AbstractHook onLogoutForced()
public function onLogoutForced(int $userId, ?string $reason, int $count): void
| Param | Type | Description |
|---|---|---|
$userId |
int |
— |
$reason |
?string |
— |
$count |
int |
— |
onUpdate()
AbstractHook onUpdate()
public function onUpdate(User $user): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onUserActive()
AbstractHook onUserActive()
public function onUserActive(User $user): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onUserUpdated()
AbstractHook onUserUpdated()
public function onUserUpdated(User $user, array $changedFields): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
$changedFields |
array |
— |
HookInterface
interface — AuthKit\Hook\HookInterface · source
| Method | Visibility | Returns | Summary |
|---|---|---|---|
onBeforeRegister() |
public | true|string |
Called before registration, can return: - true to allow registration - string with error message to block - false to use default error message |
onRegisterSuccess() |
public | void |
Called after successful registration. |
onRegisterFailure() |
public | void |
Called when registration fails due to exception or pre-check. |
onBeforeLogin() |
public | true|string |
Called before login. Can block login. |
onLoginSuccess() |
public | void |
Called after successful login. |
onLoginFailure() |
public | void |
Called when login fails (email not found or password mismatch). |
onUserActive() |
public | void |
Called when user is fetched via getUser() and token is valid. |
onLogoutExpired() |
public | void |
Called when session expires due to TTL. |
onLogout() |
public | void |
Called when logout() is called explicitly. |
onLogoutForced() |
public | void |
Called when sessions are forcibly invalidated by admin or security action. $count = how many sessions were removed. |
onUserUpdated() |
public | void |
Called after updating user data. $changedFields are the keys that were modified. |
onBeforeRegister()
HookInterface onBeforeRegister()
public function onBeforeRegister(string $email, string $password, array $fields): true|string
Called before registration, can return: - true to allow registration - string with error message to block - false to use default error message
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$password |
string |
— |
$fields |
array |
— |
Returns: true\|string
onRegisterSuccess()
HookInterface onRegisterSuccess()
public function onRegisterSuccess(User $user): void
Called after successful registration.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onRegisterFailure()
HookInterface onRegisterFailure()
public function onRegisterFailure(string $email, AuthException $e): void
Called when registration fails due to exception or pre-check.
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$e |
AuthException |
— |
onBeforeLogin()
HookInterface onBeforeLogin()
public function onBeforeLogin(User $user): true|string
Called before login. Can block login.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
Returns: true\|string
onLoginSuccess()
HookInterface onLoginSuccess()
public function onLoginSuccess(User $user): void
Called after successful login.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onLoginFailure()
HookInterface onLoginFailure()
public function onLoginFailure(string $email, AuthException $e): void
Called when login fails (email not found or password mismatch).
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$e |
AuthException |
— |
onUserActive()
HookInterface onUserActive()
public function onUserActive(User $user): void
Called when user is fetched via getUser() and token is valid.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onLogoutExpired()
HookInterface onLogoutExpired()
public function onLogoutExpired(): void
Called when session expires due to TTL.
onLogout()
HookInterface onLogout()
public function onLogout(User $user): void
Called when logout() is called explicitly.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
onLogoutForced()
HookInterface onLogoutForced()
public function onLogoutForced(int $userId, ?string $reason, int $count): void
Called when sessions are forcibly invalidated by admin or security action. $count = how many sessions were removed.
| Param | Type | Description |
|---|---|---|
$userId |
int |
— |
$reason |
?string |
— |
$count |
int |
— |
onUserUpdated()
HookInterface onUserUpdated()
public function onUserUpdated(User $user, array $changedFields): void
Called after updating user data. $changedFields are the keys that were modified.
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
$changedFields |
array |
— |
Login
final class — AuthKit\Login · source
Immutable result of an Auth::login() call. Three possible states: - success : credentials verified, session created, token available. - failure : authentication rejected, message available. - challenge : credentials verified but an extension requires an additional verification step (MFA, email activation, device check, etc.). No session is created until Auth::completeChallenge() succeeds. Usage (simple flow): $login = $auth->login($email, $password); if ($login->isSuccess()) { header('Location: /dashboard'); } echo $login->message(); Usage (challenge flow, e.g. MFA): $login = $auth->login($email, $password); if ($login->requiresChallenge()) { $_SESSION['authkit_challenge'] = $login->challengeToken(); header('Location: /login/challenge/' . $login->challengeType()); }
Depends on: User
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
private | — | — |
success() |
public static | self |
Create a successful login result with a session token. |
failure() |
public static | self |
Create a failure result. |
challengeRequired() |
public static | self |
Create a challenge-required result. Credentials were verified but an extension blocked session creation pending an additional step. No session exists at this point. |
isSuccess() |
public | bool |
— |
requiresChallenge() |
public | bool |
— |
isFailure() |
public | bool |
— |
token() |
public | string|null |
— |
user() |
public | User|null |
— |
challengeToken() |
public | string|null |
— |
challengeType() |
public | string|null |
— |
message() |
public | string |
— |
status() |
public | string |
— |
__construct()
Login __construct()
private function __construct(string $status, string $message, ?string $token, ?User $user, ?string $challengeToken, ?string $challengeType)
| Param | Type | Description |
|---|---|---|
$status |
string |
— |
$message |
string |
— |
$token |
?string |
— |
$user |
?User |
— |
$challengeToken |
?string |
— |
$challengeType |
?string |
— |
success()
Login success()
public static function success(string $token, User $user): self
Create a successful login result with a session token.
| Param | Type | Description |
|---|---|---|
$token |
string |
Session token stored in DB and $_SESSION. |
$user |
User |
Authenticated user. |
Returns: self
failure()
Login failure()
public static function failure(string $message): self
Create a failure result.
| Param | Type | Description |
|---|---|---|
$message |
string |
Human-readable reason shown to the user. |
Returns: self
challengeRequired()
Login challengeRequired()
public static function challengeRequired(string $challengeToken, string $challengeType, User $user, ?string $message): self
Create a challenge-required result. Credentials were verified but an extension blocked session creation pending an additional step. No session exists at this point.
| Param | Type | Description |
|---|---|---|
$challengeToken |
string |
Raw token to pass to Auth::completeChallenge(). Store on the caller side (e.g. $_SESSION['authkit_challenge']). |
$challengeType |
string |
Extension-defined type identifier (e.g. 'mfa_totp', 'email_activation'). |
$user |
User |
Pre-session user — credentials verified, no session yet. |
$message |
string|null |
Optional informational message (e.g. 'A code was sent to your email.'). |
Returns: self
isSuccess()
Login isSuccess()
public function isSuccess(): bool
Returns: bool — True when a session was created and token() is available.
requiresChallenge()
Login requiresChallenge()
public function requiresChallenge(): bool
Returns: bool — True when an additional verification step is required.
isFailure()
Login isFailure()
public function isFailure(): bool
Returns: bool — True when authentication was rejected.
token()
Login token()
public function token(): ?string
Returns: string\|null — Session token (set only when isSuccess() is true).
user()
Login user()
public function user(): ?User
Returns: User\|null — Authenticated user (null on failure).
challengeToken()
Login challengeToken()
public function challengeToken(): ?string
Returns: string\|null — Raw token to pass to completeChallenge() (set only when requiresChallenge()).
challengeType()
Login challengeType()
public function challengeType(): ?string
Returns: string\|null — Challenge type identifier (set only when requiresChallenge()).
message()
Login message()
public function message(): string
Returns: string — Error or informational message (meaningful when isFailure() or requiresChallenge()).
status()
Login status()
public function status(): string
Returns: string — Raw status string ('success', 'failure', 'challenge').
LoginContext
final class — AuthKit\LoginContext · source
Immutable context passed to every LoginExtensionInterface::decide() call. Built after successful credential verification, before session creation. Contains everything an extension needs to make its allow/deny/challenge decision.
Depends on: User
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
credential() |
public | mixed |
Return a single value from credential metadata by key. |
credentials() |
public | array<string, mixed> |
Return all credential metadata from the provider. |
__construct()
LoginContext __construct()
public function __construct(User $user, string $ip, string $userAgent, array $credentialMeta)
| Param | Type | Description |
|---|---|---|
$user |
User |
Authenticated user (credentials verified, no session yet). |
$ip |
string |
Client IP address from the request. |
$userAgent |
string |
Client User-Agent header value. |
$credentialMeta |
array<string, mixed> |
Provider-specific metadata from CredentialResult (e.g. provider name, JWT claims). |
credential()
LoginContext credential()
public function credential(string $key, mixed $default): mixed
Return a single value from credential metadata by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
$default |
mixed |
Returned when the key is not found. |
Returns: mixed
credentials()
LoginContext credentials()
public function credentials(): array
Return all credential metadata from the provider.
Returns: array<string, mixed>
LoginDecision
final class — AuthKit\LoginDecision · source
Immutable decision returned by LoginExtensionInterface::decide(). Three possible states: - allow : this extension permits the login pipeline to continue. - deny : this extension blocks login; session will NOT be created. - challenge : an additional verification step is required before session creation.
Depends on: \DateTimeInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
private | — | — |
allow() |
public static | self |
Allow the login pipeline to proceed to the next extension or session creation. |
deny() |
public static | self |
Block login with a human-readable reason. |
challenge() |
public static | self |
Require an additional verification step before session creation. |
isAllow() |
public | bool |
— |
isDeny() |
public | bool |
— |
isChallenge() |
public | bool |
— |
reason() |
public | string|null |
— |
challengeType() |
public | string|null |
— |
challengePayload() |
public | array<string, mixed> |
— |
challengeMessage() |
public | string|null |
— |
challengeExpiresAt() |
public | \DateTimeInterface|null |
— |
challengeMaxAttempts() |
public | int|null |
— |
status() |
public | string |
— |
__construct()
LoginDecision __construct()
private function __construct(string $status, ?string $reason, ?string $challengeType, array $challengePayload, ?string $challengeMessage, ?\DateTimeInterface $challengeExpiresAt, ?int $challengeMaxAttempts)
| Param | Type | Description |
|---|---|---|
$status |
string |
— |
$reason |
?string |
— |
$challengeType |
?string |
— |
$challengePayload |
array |
— |
$challengeMessage |
?string |
— |
$challengeExpiresAt |
?\DateTimeInterface |
— |
$challengeMaxAttempts |
?int |
— |
allow()
LoginDecision allow()
public static function allow(): self
Allow the login pipeline to proceed to the next extension or session creation.
Returns: self
deny()
LoginDecision deny()
public static function deny(string $reason): self
Block login with a human-readable reason.
| Param | Type | Description |
|---|---|---|
$reason |
string |
Error message returned to the caller (e.g. 'Account suspended.'). |
Returns: self
challenge()
LoginDecision challenge()
public static function challenge(string $type, array $payload, ?string $message, ?\DateTimeInterface $expiresAt, ?int $maxAttempts): self
Require an additional verification step before session creation.
| Param | Type | Description |
|---|---|---|
$type |
string |
Challenge type handled by a ChallengeExtensionInterface. Examples: 'mfa_totp', 'email_activation', 'new_device'. |
$payload |
array<string, mixed> |
Data stored with the challenge record (e.g. hashed OTP code). |
$message |
string|null |
Optional message returned to the caller (e.g. 'A code was sent to your email.'). |
$expiresAt |
\DateTimeInterface|null |
Override default challenge TTL. Defaults to 15 minutes. |
$maxAttempts |
int|null |
Override default max verification attempts. Defaults to 5. |
Returns: self
isAllow()
LoginDecision isAllow()
public function isAllow(): bool
Returns: bool — True when this decision allows the pipeline to continue.
isDeny()
LoginDecision isDeny()
public function isDeny(): bool
Returns: bool — True when this decision blocks login.
isChallenge()
LoginDecision isChallenge()
public function isChallenge(): bool
Returns: bool — True when this decision requires a challenge step.
reason()
LoginDecision reason()
public function reason(): ?string
Returns: string\|null — Denial reason (set only when isDeny() is true).
challengeType()
LoginDecision challengeType()
public function challengeType(): ?string
Returns: string\|null — Challenge type identifier (set only when isChallenge() is true).
challengePayload()
LoginDecision challengePayload()
public function challengePayload(): array
Returns: array<string, mixed> — Challenge payload stored in the challenge record.
challengeMessage()
LoginDecision challengeMessage()
public function challengeMessage(): ?string
Returns: string\|null — Optional message for the caller when a challenge is required.
challengeExpiresAt()
LoginDecision challengeExpiresAt()
public function challengeExpiresAt(): ?\DateTimeInterface
Returns: \DateTimeInterface\|null — Custom challenge expiry, or null to use the default (15 minutes).
challengeMaxAttempts()
LoginDecision challengeMaxAttempts()
public function challengeMaxAttempts(): ?int
Returns: int\|null — Custom max attempts, or null to use the default (5).
status()
LoginDecision status()
public function status(): string
Returns: string — Raw status string ('allow', 'deny', 'challenge').
DefaultMessageProvider
class — AuthKit\Message\DefaultMessageProvider · source
implements MessageProviderInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
userAlreadyExists() |
public | string |
— |
passwordHashingFailed() |
public | string |
— |
invalidCredentials() |
public | string |
— |
registrationBlocked() |
public | string |
— |
userNotFound() |
public | string |
— |
loginBlocked() |
public | string |
— |
userAlreadyExists()
DefaultMessageProvider userAlreadyExists()
public function userAlreadyExists(): string
Returns: string
passwordHashingFailed()
DefaultMessageProvider passwordHashingFailed()
public function passwordHashingFailed(): string
Returns: string
invalidCredentials()
DefaultMessageProvider invalidCredentials()
public function invalidCredentials(): string
Returns: string
registrationBlocked()
DefaultMessageProvider registrationBlocked()
public function registrationBlocked(): string
Returns: string
userNotFound()
DefaultMessageProvider userNotFound()
public function userNotFound(): string
Returns: string
loginBlocked()
DefaultMessageProvider loginBlocked()
public function loginBlocked(): string
Returns: string
MessageProviderInterface
interface — AuthKit\Message\MessageProviderInterface · source
| Method | Visibility | Returns | Summary |
|---|---|---|---|
userNotFound() |
public | string |
— |
userAlreadyExists() |
public | string |
— |
passwordHashingFailed() |
public | string |
— |
invalidCredentials() |
public | string |
— |
registrationBlocked() |
public | string |
— |
loginBlocked() |
public | string |
— |
userNotFound()
MessageProviderInterface userNotFound()
public function userNotFound(): string
Returns: string
userAlreadyExists()
MessageProviderInterface userAlreadyExists()
public function userAlreadyExists(): string
Returns: string
passwordHashingFailed()
MessageProviderInterface passwordHashingFailed()
public function passwordHashingFailed(): string
Returns: string
invalidCredentials()
MessageProviderInterface invalidCredentials()
public function invalidCredentials(): string
Returns: string
registrationBlocked()
MessageProviderInterface registrationBlocked()
public function registrationBlocked(): string
Returns: string
loginBlocked()
MessageProviderInterface loginBlocked()
public function loginBlocked(): string
Returns: string
NativePasswordHasher
final class — AuthKit\Password\NativePasswordHasher · source
Password hasher backed by PHP's native password_* functions.
implements PasswordHasherInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
hash() |
public | string |
— |
verify() |
public | bool |
— |
needsRehash() |
public | bool |
— |
__construct()
NativePasswordHasher __construct()
public function __construct(int|string $algorithm)
| Param | Type | Description |
|---|---|---|
$algorithm |
int|string |
Algorithm constant passed to password_hash() (default: PASSWORD_DEFAULT). |
hash()
NativePasswordHasher hash()
public function hash(string $plain): string
| Param | Type | Description |
|---|---|---|
$plain |
string |
— |
Returns: string
verify()
NativePasswordHasher verify()
public function verify(string $plain, string $hash): bool
| Param | Type | Description |
|---|---|---|
$plain |
string |
— |
$hash |
string |
— |
Returns: bool
needsRehash()
NativePasswordHasher needsRehash()
public function needsRehash(string $hash): bool
| Param | Type | Description |
|---|---|---|
$hash |
string |
— |
Returns: bool
PasswordHasherInterface
interface — AuthKit\Password\PasswordHasherInterface · source
Hashes and verifies passwords for storage and authentication.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
hash() |
public | string |
Hash a plain-text password for storage. |
verify() |
public | bool |
Verify a plain-text password against a stored hash. |
needsRehash() |
public | bool |
Check whether an existing hash should be upgraded. |
hash()
PasswordHasherInterface hash()
public function hash(string $plain): string
Hash a plain-text password for storage.
| Param | Type | Description |
|---|---|---|
$plain |
string |
Plain-text password. |
Returns: string — Hashed password.
verify()
PasswordHasherInterface verify()
public function verify(string $plain, string $hash): bool
Verify a plain-text password against a stored hash.
| Param | Type | Description |
|---|---|---|
$plain |
string |
Plain-text password. |
$hash |
string |
Stored hash to verify against. |
Returns: bool — True when the password matches the hash.
needsRehash()
PasswordHasherInterface needsRehash()
public function needsRehash(string $hash): bool
Check whether an existing hash should be upgraded.
| Param | Type | Description |
|---|---|---|
$hash |
string |
Stored hash to inspect. |
Returns: bool — True when the hash should be re-hashed on next login.
PdoUserStorage
final class — AuthKit\Storage\PdoUserStorage · source
PDO-backed user storage supporting MySQL/MariaDB and SQLite. Implements SchemaMigrationInterface so that Auth::createSchema() can bootstrap the required tables and delegate to registered extension providers.
implements UserStorageInterface, SchemaMigrationInterface
Depends on: PDO, UserIdPolicyInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
findByEmail() |
public | ?User |
— |
findByToken() |
public | ?User |
— |
findById() |
public | ?User |
— |
createUser() |
public | User |
— |
updateUser() |
public | User |
— |
storeToken() |
public | void |
— |
deleteToken() |
public | int |
— |
deleteTokensByUserId() |
public | int |
— |
purgeExpiredTokens() |
public | void |
Delete all expired session tokens. Typically called from a maintenance job or cron — not part of the login flow. The caller is responsible for supplying the reference time to ensure timezone-consistent comparisons against the stored expires_at column. |
createSchema() |
public | void |
Create the core users/sessions tables and run any additional schema declared by the given providers. Column types for the primary key and foreign key columns are determined by the injected UserIdPolicyInterface so that the schema matches the chosen ID strategy (e.g. INT AUTO_INCREMENT for NullUserIdPolicy, CHAR(36) for UUID). The method is idempotent — safe to call multiple times. |
__construct()
PdoUserStorage __construct()
public function __construct(PDO $pdo, UserIdPolicyInterface $userIdPolicy)
| Param | Type | Description |
|---|---|---|
$pdo |
PDO |
Database connection. |
$userIdPolicy |
UserIdPolicyInterface |
ID generation policy (default: database auto-increment). |
findByEmail()
PdoUserStorage findByEmail()
public function findByEmail(string $email): ?User
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
Returns: ?User
findByToken()
PdoUserStorage findByToken()
public function findByToken(string $token, \DateTimeImmutable $now): ?User
| Param | Type | Description |
|---|---|---|
$token |
string |
— |
$now |
\DateTimeImmutable |
— |
Returns: ?User
findById()
PdoUserStorage findById()
public function findById(int|string $id): ?User
| Param | Type | Description |
|---|---|---|
$id |
int|string |
— |
Returns: ?User
createUser()
PdoUserStorage createUser()
public function createUser(string $email, string $passwordHash, array $fields): User
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
$passwordHash |
string |
— |
$fields |
array |
— |
Returns: User
updateUser()
PdoUserStorage updateUser()
public function updateUser(User $user, array $fields): User
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
$fields |
array |
— |
Returns: User
storeToken()
PdoUserStorage storeToken()
public function storeToken(User $user, string $token, ?\DateTimeInterface $expiresAt): void
| Param | Type | Description |
|---|---|---|
$user |
User |
— |
$token |
string |
— |
$expiresAt |
?\DateTimeInterface |
— |
deleteToken()
PdoUserStorage deleteToken()
public function deleteToken(string $token): int
| Param | Type | Description |
|---|---|---|
$token |
string |
— |
Returns: int
deleteTokensByUserId()
PdoUserStorage deleteTokensByUserId()
public function deleteTokensByUserId(int|string $userId): int
| Param | Type | Description |
|---|---|---|
$userId |
int|string |
— |
Returns: int
purgeExpiredTokens()
PdoUserStorage purgeExpiredTokens()
public function purgeExpiredTokens(\DateTimeImmutable $now): void
Delete all expired session tokens. Typically called from a maintenance job or cron — not part of the login flow. The caller is responsible for supplying the reference time to ensure timezone-consistent comparisons against the stored expires_at column.
| Param | Type | Description |
|---|---|---|
$now |
\DateTimeImmutable |
Sessions with expires_at before this value will be deleted. |
createSchema()
PdoUserStorage createSchema()
public function createSchema(SchemaProviderInterface $providers): void
Create the core users/sessions tables and run any additional schema declared by the given providers. Column types for the primary key and foreign key columns are determined by the injected UserIdPolicyInterface so that the schema matches the chosen ID strategy (e.g. INT AUTO_INCREMENT for NullUserIdPolicy, CHAR(36) for UUID). The method is idempotent — safe to call multiple times.
| Param | Type | Description |
|---|---|---|
$providers |
SchemaProviderInterface |
— |
SchemaMigrationInterface
interface — AuthKit\Storage\SchemaMigrationInterface · source
Marks a storage backend that is capable of creating its own database schema. Implement this interface alongside UserStorageInterface when the storage layer can bootstrap its tables on demand (e.g. PdoUserStorage). Storage implementations that keep data entirely in memory or delegate persistence to an external service do not need to implement this. The Auth facade calls createSchema() when Auth::createSchema() is invoked, passing all registered extensions that implement SchemaProviderInterface so that each extension's required tables and columns are created in the same transaction context.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
createSchema() |
public | void |
Create the core schema plus any additional schema declared by the given providers. The method must be idempotent — safe to call multiple times against an already-initialised database (e.g. use CREATE TABLE IF NOT EXISTS). |
createSchema()
SchemaMigrationInterface createSchema()
public function createSchema(SchemaProviderInterface $providers): void
Create the core schema plus any additional schema declared by the given providers. The method must be idempotent — safe to call multiple times against an already-initialised database (e.g. use CREATE TABLE IF NOT EXISTS).
| Param | Type | Description |
|---|---|---|
$providers |
SchemaProviderInterface |
— |
UserStorageInterface
interface — AuthKit\Storage\UserStorageInterface · source
Persists and retrieves user records and session tokens.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
findByEmail() |
public | User|null |
Find a user by their email address. |
findByToken() |
public | User|null |
Find a user by their session token. $now is used to filter out expired sessions at the query level. Pass the current time from your clock to ensure timezone-consistent expiry comparisons against the stored expires_at column. |
findById() |
public | User|null |
Find a user by their ID. |
createUser() |
public | User |
Create and persist a new user. |
updateUser() |
public | User |
Update fields on an existing user. |
storeToken() |
public | void |
Store a session token for a user. |
deleteToken() |
public | int |
Delete a single session token. |
deleteTokensByUserId() |
public | int |
Delete all session tokens for a given user. |
createSchema() |
public | void |
Create the necessary database schema for user storage. |
findByEmail()
UserStorageInterface findByEmail()
public function findByEmail(string $email): ?User
Find a user by their email address.
| Param | Type | Description |
|---|---|---|
$email |
string |
The email address to search for. |
Returns: User\|null
findByToken()
UserStorageInterface findByToken()
public function findByToken(string $token, \DateTimeImmutable $now): ?User
Find a user by their session token. $now is used to filter out expired sessions at the query level. Pass the current time from your clock to ensure timezone-consistent expiry comparisons against the stored expires_at column.
| Param | Type | Description |
|---|---|---|
$token |
string |
The session token to search for. |
$now |
\DateTimeImmutable |
Current time used to filter expired sessions. |
Returns: User\|null
findById()
UserStorageInterface findById()
public function findById(int|string $id): ?User
Find a user by their ID.
| Param | Type | Description |
|---|---|---|
$id |
int|string |
The user ID to search for. |
Returns: User\|null
createUser()
UserStorageInterface createUser()
public function createUser(string $email, string $passwordHash, array $fields): User
Create and persist a new user.
| Param | Type | Description |
|---|---|---|
$email |
string |
User's email address. |
$passwordHash |
string |
Hashed password. |
$fields |
array<string, mixed> |
Additional fields to store. |
Returns: User
updateUser()
UserStorageInterface updateUser()
public function updateUser(User $user, array $fields): User
Update fields on an existing user.
| Param | Type | Description |
|---|---|---|
$user |
User |
The user to update. |
$fields |
array<string, mixed> |
Associative array of fields to update. |
Returns: User — Updated user.
storeToken()
UserStorageInterface storeToken()
public function storeToken(User $user, string $token, ?\DateTimeInterface $expiresAt): void
Store a session token for a user.
| Param | Type | Description |
|---|---|---|
$user |
User |
The user to associate the token with. |
$token |
string |
The session token to store. |
$expiresAt |
\DateTimeInterface|null |
Optional expiration date/time. |
deleteToken()
UserStorageInterface deleteToken()
public function deleteToken(string $token): int
Delete a single session token.
| Param | Type | Description |
|---|---|---|
$token |
string |
The session token to delete. |
Returns: int — Number of tokens deleted (0 or 1).
deleteTokensByUserId()
UserStorageInterface deleteTokensByUserId()
public function deleteTokensByUserId(int|string $userId): int
Delete all session tokens for a given user.
| Param | Type | Description |
|---|---|---|
$userId |
int|string |
The user ID whose tokens should be removed. |
Returns: int — Number of tokens deleted.
createSchema()
UserStorageInterface createSchema()
public function createSchema(): void
Create the necessary database schema for user storage.
BearerHeaderTransport
final class — AuthKit\Transport\BearerHeaderTransport · source
Token transport for stateless API clients using HTTP Bearer authentication. Reads the token from the Authorization: Bearer request header. set() and clear() are no-ops — the client is responsible for storing and discarding the token on its own side.
implements TokenTransportInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
initialize() |
public | void |
— |
get() |
public | ?string |
— |
set() |
public | void |
— |
clear() |
public | void |
— |
set()
BearerHeaderTransport set()
public function set(string $token): void
| Param | Type | Description |
|---|---|---|
$token |
string |
— |
PhpSessionTransport
final class — AuthKit\Transport\PhpSessionTransport · source
Token transport backed by the native PHP session. This is the default transport for web applications. The token is stored under a configurable key in $_SESSION and travels via session cookie.
implements TokenTransportInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
initialize() |
public | void |
— |
get() |
public | ?string |
— |
set() |
public | void |
— |
clear() |
public | void |
— |
__construct()
PhpSessionTransport __construct()
public function __construct(string $key)
| Param | Type | Description |
|---|---|---|
$key |
string |
$_SESSION key used to store the token (default: 'auth_token'). |
set()
PhpSessionTransport set()
public function set(string $token): void
| Param | Type | Description |
|---|---|---|
$token |
string |
— |
TokenTransportInterface
interface — AuthKit\Transport\TokenTransportInterface · source
Abstracts how the active session token is stored and retrieved on the client side. Implement this interface to swap the default PHP session transport for any other mechanism (Bearer header, cookie, in-memory, etc.).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
initialize() |
public | void |
Called once during Auth initialization. Use this to start a session, open storage, or perform any setup required before the transport can be used. |
get() |
public | string|null |
Return the current token, or null if none is present. |
set() |
public | void |
Store the token after a successful login. |
clear() |
public | void |
Remove the stored token on logout. |
initialize()
TokenTransportInterface initialize()
public function initialize(): void
Called once during Auth initialization. Use this to start a session, open storage, or perform any setup required before the transport can be used.
get()
TokenTransportInterface get()
public function get(): ?string
Return the current token, or null if none is present.
Returns: string\|null
set()
TokenTransportInterface set()
public function set(string $token): void
Store the token after a successful login.
| Param | Type | Description |
|---|---|---|
$token |
string |
— |
clear()
TokenTransportInterface clear()
public function clear(): void
Remove the stored token on logout.
User
class — AuthKit\User · source
Class User Represents a user in the authentication system. Provides methods to access user attributes and serialize to JSON.
implements \JsonSerializable
| Property | Type | Visibility | Description |
|---|---|---|---|
$attributes |
array<string, mixed> |
private | — |
$extraHiddenKeys |
string[] |
private static | Extra keys provided by the application to hide in addition to defaults. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | User constructor. Initializes the user with an array of attributes. |
setHiddenKeys() |
public static | void |
Configure additional keys to hide (replaces previously set extra keys). Usage: User::setHiddenKeys(['api_key', 'private_notes']); |
addHiddenKeys() |
public static | void |
Add more keys to hide (keeps any previously configured extras). |
getHiddenKeys() |
public static | string[] |
Returns the complete effective hidden-keys list (defaults + extras). |
filteredAttributes() |
private | array<string, mixed> |
Return a copy of attributes with hidden keys removed. |
get() |
public | mixed |
Returns one field or multiple fields by key(s). Example: get('email') or get(['email', 'name']) |
getAll() |
public | array<string, mixed> |
Returns all available user data EXCEPT hidden keys. |
getId() |
public | int|string|null |
Returns the user's ID, or null if not yet persisted. |
getEmail() |
public | ?string |
Get the user's email address. Returns null if the email is not set. |
jsonSerialize() |
public | array<string, mixed> |
Support for json_encode($user) Returns attributes without hidden keys. |
toJson() |
public | string |
Convert to JSON string manually (without hidden keys). |
_getAllRaw() |
public | array<string, mixed> |
Internal-only raw accessor to full attributes including hidden keys. Prefer NOT to use this in application code. Keep it private/protected if undesired. |
__construct()
User __construct()
public function __construct(array $attributes)
User constructor. Initializes the user with an array of attributes.
| Param | Type | Description |
|---|---|---|
$attributes |
array<string, mixed> |
Associative array of user attributes. |
setHiddenKeys()
User setHiddenKeys()
public static function setHiddenKeys(array $keys): void
Configure additional keys to hide (replaces previously set extra keys). Usage: User::setHiddenKeys(['api_key', 'private_notes']);
| Param | Type | Description |
|---|---|---|
$keys |
string[] |
— |
addHiddenKeys()
User addHiddenKeys()
public static function addHiddenKeys(array $keys): void
Add more keys to hide (keeps any previously configured extras).
| Param | Type | Description |
|---|---|---|
$keys |
string[] |
— |
getHiddenKeys()
User getHiddenKeys()
public static function getHiddenKeys(): array
Returns the complete effective hidden-keys list (defaults + extras).
Returns: string[]
filteredAttributes()
User filteredAttributes()
private function filteredAttributes(): array
Return a copy of attributes with hidden keys removed.
Returns: array<string, mixed>
get()
User get()
public function get(array|string $fields): mixed
Returns one field or multiple fields by key(s). Example: get('email') or get(['email', 'name'])
| Param | Type | Description |
|---|---|---|
$fields |
array<string>|string |
— |
Returns: mixed
getAll()
User getAll()
public function getAll(): array
Returns all available user data EXCEPT hidden keys.
Returns: array<string, mixed>
getId()
User getId()
public function getId(): int|string|null
Returns the user's ID, or null if not yet persisted.
Returns: int\|string\|null
getEmail()
User getEmail()
public function getEmail(): ?string
Get the user's email address. Returns null if the email is not set.
Returns: ?string
jsonSerialize()
User jsonSerialize()
public function jsonSerialize(): array
Support for json_encode($user) Returns attributes without hidden keys.
Returns: array<string, mixed>
toJson()
User toJson()
public function toJson(bool $pretty): string
Convert to JSON string manually (without hidden keys).
| Param | Type | Description |
|---|---|---|
$pretty |
bool |
Whether to pretty-print the JSON. |
Returns: string
_getAllRaw()
User _getAllRaw()
public function _getAllRaw(): array
Internal-only raw accessor to full attributes including hidden keys. Prefer NOT to use this in application code. Keep it private/protected if undesired.
Returns: array<string, mixed>
NullUserIdPolicy
final class — AuthKit\UserId\NullUserIdPolicy · source
Delegates user ID assignment to the database (auto-increment).
implements UserIdPolicyInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
generate() |
public | int|string|null |
— |
idColumnDefinition() |
public | string |
— |
userIdForeignType() |
public | string |
— |
generate()
NullUserIdPolicy generate()
public function generate(): int|string|null
Returns: int\|string\|null
idColumnDefinition()
NullUserIdPolicy idColumnDefinition()
public function idColumnDefinition(string $driver): string
| Param | Type | Description |
|---|---|---|
$driver |
string |
— |
Returns: string
userIdForeignType()
NullUserIdPolicy userIdForeignType()
public function userIdForeignType(string $driver): string
| Param | Type | Description |
|---|---|---|
$driver |
string |
— |
Returns: string
UserIdPolicyInterface
interface — AuthKit\UserId\UserIdPolicyInterface · source
Determines how a new user ID is assigned before insertion and what column type that choice requires in the database schema. Return null from generate() to let the database produce the ID (auto-increment). Return a value to supply the ID from the application layer (e.g. UUID v4). The two schema methods allow PdoUserStorage::createSchema() to emit the correct column definitions without hardcoding a specific strategy.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
generate() |
public | int|string|null |
Generate an ID for a new user, or return null to delegate to the database. |
idColumnDefinition() |
public | string |
Full inline SQL column definition for the users.id primary key column. When the returned string contains the token "PRIMARY KEY", createSchema() omits the separate PRIMARY KEY table constraint (required for SQLite AUTOINCREMENT which must be declared inline). Examples: NullUserIdPolicy / sqlite → "INTEGER PRIMARY KEY AUTOINCREMENT" NullUserIdPolicy / mysql → "INT NOT NULL AUTO_INCREMENT" UuidUserIdPolicy / any → "CHAR(36) NOT NULL" |
userIdForeignType() |
public | string |
SQL type for foreign key columns that reference users.id. Used by createSchema() for the sessions.user_id column and should be compatible with the type chosen by idColumnDefinition(). Examples: NullUserIdPolicy / sqlite → "INTEGER NOT NULL" NullUserIdPolicy / mysql → "INT NOT NULL" UuidUserIdPolicy / any → "CHAR(36) NOT NULL" |
generate()
UserIdPolicyInterface generate()
public function generate(): int|string|null
Generate an ID for a new user, or return null to delegate to the database.
Returns: int\|string\|null — Application-generated ID, or null for database auto-increment.
idColumnDefinition()
UserIdPolicyInterface idColumnDefinition()
public function idColumnDefinition(string $driver): string
Full inline SQL column definition for the users.id primary key column. When the returned string contains the token "PRIMARY KEY", createSchema() omits the separate PRIMARY KEY table constraint (required for SQLite AUTOINCREMENT which must be declared inline). Examples: NullUserIdPolicy / sqlite → "INTEGER PRIMARY KEY AUTOINCREMENT" NullUserIdPolicy / mysql → "INT NOT NULL AUTO_INCREMENT" UuidUserIdPolicy / any → "CHAR(36) NOT NULL"
| Param | Type | Description |
|---|---|---|
$driver |
string |
PDO driver name ('mysql', 'sqlite', …). |
Returns: string — SQL fragment placed immediately after the column name.
userIdForeignType()
UserIdPolicyInterface userIdForeignType()
public function userIdForeignType(string $driver): string
SQL type for foreign key columns that reference users.id. Used by createSchema() for the sessions.user_id column and should be compatible with the type chosen by idColumnDefinition(). Examples: NullUserIdPolicy / sqlite → "INTEGER NOT NULL" NullUserIdPolicy / mysql → "INT NOT NULL" UuidUserIdPolicy / any → "CHAR(36) NOT NULL"
| Param | Type | Description |
|---|---|---|
$driver |
string |
PDO driver name. |
Returns: string — SQL type fragment (no column name).