PHP code example of ez-php / auth

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

    

ez-php / auth example snippets


$app->register(\EzPhp\Auth\AuthServiceProvider::class);

// Optional — register JWT support:
$app->register(\EzPhp\Auth\JwtServiceProvider::class);

use EzPhp\Auth\UserInterface;
use EzPhp\Auth\UserProviderInterface;

class UserProvider implements UserProviderInterface
{
    // Session restoration (the `auth_id` stored by Auth::login()).
    public function findById(int|string $id): ?UserInterface { ... }

    // AuthMiddleware provider mode: the raw Bearer token from the request.
    public function findByToken(string $token): ?UserInterface { ... }

    // Auth::attempt(): look the user up by login name / e-mail before password_verify().
    public function findByCredentials(string $identifier): ?UserInterface { ... }

    // Auth::attemptRemember(): receives the RAW token from the cookie — look it up by
    // hash('sha256', $token), never store or compare the raw value (see "Remember me").
    public function findByRememberToken(string $token): ?UserInterface { ... }
}

$this->app->bind(UserProviderInterface::class, UserProvider::class);

use EzPhp\Auth\Auth;

// Authenticate
Auth::login($user);
$user = Auth::user();
Auth::logout();

// Protect routes with middleware
$router->get('/dashboard', $handler)->middleware(\EzPhp\Auth\Middleware\AuthMiddleware::class);

$token = Auth::loginWithRemember($user);

// Persist only the hash (e.g. a `remember_token` column on the users table) …
$users->updateRememberToken($user->getAuthId(), hash('sha256', $token));

// … and hand the raw token to the browser.
$response = $response->withCookie('remember', $token, 60 * 60 * 24 * 30, secure: true, httpOnly: true, sameSite: 'Lax');

// On a later request without a session:
$raw = $request->cookie('remember');
if (is_string($raw) && $raw !== '') {
    Auth::attemptRemember($raw, $provider); // provider: WHERE remember_token = hash('sha256', $raw)
}

$jwt = $app->make(\EzPhp\Auth\Jwt\JwtManager::class);

$token    = $jwt->issue($user->getAuthId());
$claims   = $jwt->validate($token);
$response = ['access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => $jwt->ttl()];

// Protect routes
$router->get('/api/me', $handler)->middleware(\EzPhp\Auth\Middleware\JwtMiddleware::class);

use EzPhp\RateLimiter\Middleware\ThrottleMiddleware;

$app->middlewareAlias('throttle', ThrottleMiddleware::class); // before bootstrap

// 5 attempts per 10 minutes in the 'login' bucket, keyed per client IP — independent
// of the throttle guarding any other route.
$router->post('/login', $handler)
    ->middleware('throttle:5,600,login') // runs first — throttled requests never reach AuthMiddleware
    ->middleware(AuthMiddleware::class);

use EzPhp\Auth\LoginThrottle;

$throttle = new LoginThrottle($limiter, maxAttempts: 5, lockoutSeconds: 300, failureDelayMs: 250);
$result = $throttle->attempt($username, $password, $provider, throttleKey: strtolower($username) . '|' . $ip);

if ($result->isLockedOut()) {
    return (new Response('Too many attempts', 429))->withHeader('Retry-After', (string) $result->availableIn);
}

if (!$result->succeeded()) {
    return new Response('Invalid credentials', 401); // $result->remainingAttempts left
}

use EzPhp\Auth\Middleware\SessionAuthMiddleware;

$this->app->bind(SessionAuthMiddleware::class, fn () => new SessionAuthMiddleware(
    static fn (RequestInterface $request) => (new Response('', 302))->withHeader('Location', '/login'),
));

$router->get('/dashboard', $handler)->middleware(SessionAuthMiddleware::class);



$app->registerCommand(\EzPhp\Auth\Console\AuthScaffoldCommand::class);

$manager = $app->make(\EzPhp\Auth\PersonalAccessTokenManager::class);

[$rawToken, $token] = $manager->create($userId, 'my-token', ['read', 'write']);
$token = $manager->find($rawToken);
$manager->revoke($token->id);

$raw = $manager->issueOneTime($userId, 'password-reset', ttl: 3600); // revokes earlier reset links
// … send $raw in the reset link …

$token = $manager->consume($rawFromLink, 'password-reset');          // null if invalid, expired, used or wrong purpose
if ($token !== null) {
    // reset the password of $token->userId
}

$manager->revokeFor($userId, 'password-reset');                      // e.g. after a successful reset

$revoked = $manager->revokeNamed($userId, 'refresh'); // number of deleted tokens

$app->registerCommand(\EzPhp\Auth\Console\TokenCommand::class);
bash
composer 
dotenv
JWT_SECRET=  # at least 32 bytes, e.g. php -r 'echo bin2hex(random_bytes(32));'
JWT_TTL=3600
bash
php ez auth:scaffold

database/migrations/2024_01_01_000000_create_personal_access_tokens_table.php