Framework-agnostic authentication library for PHP - Core package

Installs: 200

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

pkg:composer/betterauth/core

v1.0.3 2025-11-23 22:31 UTC

This package is auto-updated.

Last update: 2025-11-23 22:54:21 UTC


README

CI Latest Stable Version Total Downloads License PHP Version

Framework-agnostic authentication library for PHP 8.2+.

โœจ Features

  • ๐Ÿ” Multiple authentication methods: Email/Password, Magic Link, OAuth, Passkeys (WebAuthn), TOTP
  • ๐ŸŒ OAuth Providers: Google, GitHub, Facebook, Microsoft, Discord
  • ๐Ÿ‘ฅ Multi-tenant capabilities: Organizations, Teams, Members, Invitations with RBAC
  • ๐Ÿ”’ Secure by default: Paseto V4 tokens, Argon2id hashing
  • ๐Ÿ’พ Multiple storage adapters: PDO, Eloquent, Doctrine
  • ๐ŸŽฏ Framework-agnostic core: Use with any PHP framework
  • ๐Ÿ†” UUID v7 support: Time-ordered, non-guessable IDs
  • ๐Ÿ”Œ Plugin system: Extensible architecture
  • ๐Ÿ“Š Security audit trail: Events logging & monitoring

๐Ÿ“ฆ Installation

composer require betterauth/core

๐Ÿš€ Framework Integrations

BetterAuth Core is framework-agnostic with official integrations:

  • Symfony (โœ… Production Ready): betterauth/symfony-bundle
  • Laravel (๐Ÿšง In Development): betterauth/laravel
  • Vanilla PHP: Use this package directly with PDO storage adapters

๐Ÿ”ง Requirements

  • PHP 8.2 or higher
  • ext-json
  • ext-openssl
  • ramsey/uuid ^4.7
  • paragonie/paseto ^3.1

๐Ÿš€ Quick Start (Vanilla PHP with PDO)

<?php

use BetterAuth\Core\Config\AuthConfig;
use BetterAuth\Core\TokenAuthManager;
use BetterAuth\Storage\Pdo\PdoUserRepository;

// Database setup
$pdo = new PDO('sqlite:database.db');

// Create repositories
$userRepo = new PdoUserRepository($pdo);

// Configure authentication
$config = new AuthConfig(
    secret: 'your-256-bit-secret-key',
    tokenLifetime: 7200, // 2 hours
    refreshLifetime: 2592000 // 30 days
);

// Create auth manager
$auth = new TokenAuthManager($config, $userRepo);

// Register a user
$user = $auth->register(
    email: 'user@example.com',
    password: 'SecurePassword123',
    name: 'John Doe'
);

// Login
$tokens = $auth->login(
    email: 'user@example.com',
    password: 'SecurePassword123'
);

// Access user with token
$currentUser = $auth->getUserFromToken($tokens['accessToken']);

๐Ÿ’พ Storage Adapters

PDO (Vanilla PHP)

use BetterAuth\Storage\Pdo\PdoUserRepository;
use BetterAuth\Storage\Pdo\PdoSessionRepository;

$pdo = new PDO('mysql:host=localhost;dbname=auth', 'user', 'password');
$userRepo = new PdoUserRepository($pdo);
$sessionRepo = new PdoSessionRepository($pdo);

Eloquent (Laravel)

use BetterAuth\Storage\Eloquent\EloquentUserRepository;

$userRepo = new EloquentUserRepository();

Doctrine (Symfony)

Use the betterauth/symfony-bundle which provides Doctrine integration.

๐Ÿ”‘ Authentication Providers

Email/Password

$auth->register(
    email: 'user@example.com',
    password: 'SecurePassword123',
    name: 'John Doe'
);

$tokens = $auth->login(
    email: 'user@example.com',
    password: 'SecurePassword123'
);

OAuth 2.0

use BetterAuth\Providers\OAuthProvider\OAuthManager;

$oauthConfig = [
    'google' => [
        'clientId' => 'your-google-client-id',
        'clientSecret' => 'your-google-client-secret',
        'redirectUri' => 'https://yourapp.com/auth/google/callback',
    ],
];

$oauth = new OAuthManager($oauthConfig, $userRepo);

// Redirect to OAuth provider
$authUrl = $oauth->getAuthorizationUrl('google');
header("Location: $authUrl");

// Handle callback
$userData = $oauth->handleCallback('google', $_GET['code']);
$user = $auth->createOrUpdateOAuthUser($userData);

Magic Link

use BetterAuth\Providers\MagicLinkProvider\MagicLinkManager;

$magicLink = new MagicLinkManager($config, $userRepo);

// Send magic link
$token = $magicLink->createMagicLink('user@example.com');
// Send $token via email

// Verify magic link
$user = $magicLink->verifyMagicLink($token);

TOTP (Two-Factor Authentication)

use BetterAuth\Providers\TotpProvider\TotpManager;

$totp = new TotpManager($userRepo);

// Enable TOTP for user
$secret = $totp->enableTotp($userId);
$qrCode = $totp->getQrCode($user, $secret);

// Verify TOTP code
$isValid = $totp->verifyTotp($userId, '123456');

Passkeys (WebAuthn)

use BetterAuth\Providers\PasskeyProvider\PasskeyManager;

$passkey = new PasskeyManager($config, $userRepo);

// Register passkey
$options = $passkey->generateRegistrationOptions($userId);
// Send $options to client

// Verify registration
$passkey->verifyRegistration($userId, $clientResponse);

// Authenticate with passkey
$options = $passkey->generateAuthenticationOptions();
// Send $options to client

// Verify authentication
$user = $passkey->verifyAuthentication($clientResponse);

๐Ÿ”’ Security Features

Token Management

BetterAuth uses Paseto V4 tokens (encrypted, authenticated):

// Access token (short-lived)
$accessToken = $tokens['accessToken']; // Valid for 2 hours

// Refresh token (long-lived)
$refreshToken = $tokens['refreshToken']; // Valid for 30 days

// Refresh access token
$newTokens = $auth->refresh($refreshToken);

Password Hashing

Passwords are hashed using Argon2id (memory-hard, resistant to GPU attacks):

// Automatic during registration
$user = $auth->register(
    email: 'user@example.com',
    password: 'SecurePassword123' // Hashed with Argon2id
);

UUID v7 IDs

BetterAuth supports time-ordered UUIDs for better database performance:

// Example UUID v7 (time-ordered, non-guessable)
$user->id; // "019ab13e-40f1-7b21-a672-f403d5277ec7"

// Benefits:
// - Chronologically sortable
// - Non-guessable (secure)
// - No index fragmentation (fast DB queries)

โš™๏ธ Configuration

use BetterAuth\Core\Config\AuthConfig;

$config = new AuthConfig(
    secret: 'your-256-bit-secret-key',
    tokenLifetime: 7200,        // Access token: 2 hours
    refreshLifetime: 2592000,   // Refresh token: 30 days
    passwordMinLength: 8,
    requireEmailVerification: true,
    enableDeviceTrust: true,
    enableSecurityNotifications: true
);

๐Ÿ‘ฅ Multi-Tenancy

use BetterAuth\Providers\AccountLinkProvider\OrganizationManager;

$orgManager = new OrganizationManager($userRepo);

// Create organization
$org = $orgManager->createOrganization(
    name: 'Acme Inc',
    ownerId: $userId
);

// Invite members
$orgManager->inviteMember(
    organizationId: $org->id,
    email: 'member@example.com',
    role: 'admin'
);

// Accept invitation
$orgManager->acceptInvitation($token);

๐Ÿงช Testing

# Run PHPUnit tests
composer test

# Run PHPStan static analysis
composer phpstan

# Run Behat BDD scenarios
vendor/bin/behat

# Run code style fixer
composer cs-fix

๐Ÿ“Š CI/CD

BetterAuth Core includes comprehensive CI/CD with GitHub Actions:

  • โœ… PHPUnit tests (PHP 8.2, 8.3, 8.4)
  • โœ… PHPStan static analysis (level 5)
  • โœ… Security checks (Composer audit + Symfony security checker)
  • โœ… Behat BDD scenarios
  • โœ… Code quality checks (PHP CS Fixer)

All tests run on every push and pull request. View the latest CI results.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ”’ Security

If you discover any security-related issues, please create an issue on GitHub with the security label.

๐Ÿ“„ License

The MIT License (MIT). Please see LICENSE file for details.

๐Ÿ”— Links

๐Ÿ™ Credits

Made with โค๏ธ by the BackToTheFutur Team