1. Go to this page and download the library: Download rafalmasiarek/authkit library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rafalmasiarek / authkit example snippets
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('[email protected]', 'secret123');
// Login
$login = $auth->login('[email protected]', '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();
// 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);
$login = $auth->login($email, $password);
$login->isSuccess(); // bool
$login->isFailure(); // bool
$login-> or challenge
$login->message(); // string — failure reason
$login->challengeToken(); // ?string — raw token for completeChallenge()
$login->challengeType(); // ?string — e.g. 'mfa_totp', 'email_activation'
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());
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.');
}
}
// Step 1 — login
$login = $auth->login($email, $password);
if ($login->ct 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
}
use AuthKit\Challenge\PdoChallengeStorage;
$auth = new Auth($storage, challengeStorage: new PdoChallengeStorage($pdo));
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'));
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
// 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();
}
$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
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)
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
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;
}
$auth->forceLogoutUser($userOrId); // all sessions for a user
$auth->forceLogoutEmail($email); // all sessions by email
$auth->forceLogoutToken($token); // single session by token
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.