PHP code example of betterauth / multimodal-php

1. Go to this page and download the library: Download betterauth/multimodal-php 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/ */

    

betterauth / multimodal-php example snippets


use BetterAuth\Core\AuthManager;
use BetterAuth\Core\SessionAuthManager;
use BetterAuth\Core\SessionService;
use BetterAuth\Core\PasswordHasher;
use BetterAuth\Core\Config\AuthConfig;
use BetterAuth\Storage\Pdo\PdoUserRepository;
use BetterAuth\Storage\Pdo\PdoSessionRepository;

// The bundled PDO storage (createTable / upserts) targets MySQL/MariaDB.
// For SQLite or PostgreSQL, provide your own storage implementation.
$pdo = new PDO('mysql:host=127.0.0.1;dbname=auth', 'user', 'pass');

$config   = AuthConfig::forMonolith('your-secret-key-min-32-chars');
$users    = new PdoUserRepository($pdo);
$sessions = new PdoSessionRepository($pdo);
$hasher   = new PasswordHasher();
$service  = new SessionService($sessions, $config);

$sessionAuth = new SessionAuthManager($users, $service, $hasher);
$auth        = new AuthManager($config, sessionAuth: $sessionAuth);

// Sign up
$result = $auth->signUp('[email protected]', 'SecureP@ss2024!', 'Alice');

// Sign in
$result = $auth->signIn('[email protected]', 'SecureP@ss2024!');
// $result = ['user' => UserDto, 'session' => Session]

// Validate session
$user = $auth->validateSession($result['session']->getToken());

use BetterAuth\Core\AuthManager;
use BetterAuth\Core\TokenAuthManager;
use BetterAuth\Core\TokenService;
use BetterAuth\Core\PasswordHasher;
use BetterAuth\Core\Config\AuthConfig;
use BetterAuth\Storage\Pdo\PdoUserRepository;
use BetterAuth\Storage\Pdo\PdoRefreshTokenRepository;

// The bundled PDO storage (createTable / upserts) targets MySQL/MariaDB.
// For SQLite or PostgreSQL, provide your own storage implementation.
$pdo = new PDO('mysql:host=127.0.0.1;dbname=auth', 'user', 'pass');

$config   = AuthConfig::forApi('your-secret-key-min-32-chars');
$users    = new PdoUserRepository($pdo);
$refresh  = new PdoRefreshTokenRepository($pdo);
$hasher   = new PasswordHasher();
$signer   = new TokenService($config);

$tokenAuth = new TokenAuthManager($users, $refresh, $signer, $hasher, $config);
$auth      = new AuthManager($config, tokenAuth: $tokenAuth);

// Sign in
$result = $auth->signIn('[email protected]', 'SecureP@ss2024!');
// $result = ['user' => UserDto, 'access_token' => '...', 'refresh_token' => '...', 'expires_in' => 3600]

// Refresh tokens (atomic rotation)
$newTokens = $auth->refresh($result['refresh_token']);

$config = AuthConfig::forMonolith($secret);  // Session mode
$config = AuthConfig::forApi($secret);       // Token mode
$config = AuthConfig::forHybrid($secret);    // Both

use BetterAuth\Providers\OAuthProvider\OAuthManager;
use BetterAuth\Providers\OAuthProvider\GoogleProvider;
use BetterAuth\Providers\OAuthProvider\GitHubProvider;

$oauth = new OAuthManager($auth, $users, $accountLinks);

$oauth->addProvider(new GoogleProvider($clientId, $clientSecret, $redirectUri));
$oauth->addProvider(new GitHubProvider($clientId, $clientSecret, $redirectUri));

// Step 1 — redirect
$authUrl = $oauth->getAuthorizationUrl('google', ['scope' => 'email profile']);
// redirect user to $authUrl['url'], store $authUrl['state'] in session

// Step 2 — callback
$result = $oauth->handleCallback('google', $code, $redirectUri, $ip, $userAgent, $state, $expectedState);

use BetterAuth\Providers\TotpProvider\TotpProvider;

$totp = new TotpProvider($totpStorage, $users);

// Enable 2FA
$setup = $totp->generateSecret($userId, 'MyApp');
// $setup = ['secret' => '...', 'uri' => 'otpauth://totp/...', 'backup_codes' => [...]]

// Verify setup
$totp->enableTotp($userId, $setup['secret'], $codeFromApp);

// Validate on login
$totp->verifyTotp($userId, $codeFromApp);

use BetterAuth\Providers\MagicLinkProvider\MagicLinkProvider;

$magicLink = new MagicLinkProvider($storage, $auth, $users, $config);

// Send link
$magicLink->sendMagicLink('[email protected]', $emailSender, 'https://app.com/auth/verify');

// Verify (from callback)
$result = $magicLink->verifyMagicLink($token, $ip, $userAgent);

use BetterAuth\Providers\OidcProvider\OidcProvider;

$oidc = new OidcProvider($clients, $codes, $tokenManager, $users, $config);

// Authorization endpoint
$result = $oidc->authorize($clientId, $redirectUri, 'openid profile email', $state, $userId, $codeChallenge, 'S256');

// Token endpoint
$tokens = $oidc->token($grantType, $code, $redirectUri, $clientId, $clientSecret, $codeVerifier);

// Discovery
$config = $oidc->getDiscoveryConfig('https://auth.example.com');

// Organizations, teams, members, invitations
$org = $orgRepo->create('Acme Corp', 'acme-corp', $creatorId);
$teamRepo->create($org->getId(), 'Engineering', 'engineering');
$invitationRepo->create($org->getId(), '[email protected]', 'member', $inviterId);

use BetterAuth\Core\Plugin\PluginManager;
use BetterAuth\Core\Plugin\PluginInterface;
use BetterAuth\Core\Plugin\PluginContext;

class AuditPlugin implements PluginInterface
{
    public function getName(): string { return 'audit'; }
    public function getVersion(): string { return '1.0.0'; }
    public function getDependencies(): array { return []; }
    public function isEnabled(): bool { return true; }
    public function getConfig(): array { return []; }

    public function install(PluginContext $context): void
    {
        $context->registerHook('user.logged_in', function (array $data) {
            // log login event
        });
    }
}

$plugins = new PluginManager();
$plugins->register(new AuditPlugin());
$plugins->loadAll();
bash
composer