PHP code example of vercodea / auth-core

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

    

vercodea / auth-core example snippets



reate all database tables automatically
AuthInit::init();

echo "✅ Database initialized successfully!";


ser login
$result = AuthInit::auth_login('johndoe', null, 'password');

// User registration
$result = AuthInit::auth_register('John Doe', 'johndoe', '[email protected]', 'SecurePass123!', '123456');

// User logout
$result = AuthInit::auth_logout();

verify_pipeline_access(['signup.php', 'signin.php', 'index.php']);


============================================
// SETUP: Initialize Database (Run once)
// ============================================
AuthInit::init();
// ✅ All tables created automatically!

// ============================================
// FLOW 1: USER REGISTRATION
// ============================================

// 1. Send OTP to user's email
$result = AuthInit::auth_send_otp('[email protected]');
if ($result['status']) {
    echo "✅ OTP sent to email";
} else {
    echo "❌ " . $result['msg'];
}

// 2. User receives OTP (e.g., "123456"), then register
$result = AuthInit::auth_register(
    name: "John Doe",
    username: "johndoe",
    email: "[email protected]",
    password: "SecurePass123!",
    otp_input: "123456"  // OTP from email
);

if ($result['status']) {
    echo "✅ Registration successful!";
} else {
    echo "❌ " . $result['msg'];
}

// ============================================
// FLOW 2: USER LOGIN
// ============================================

// Option A: Login with username
$result = AuthInit::auth_login(
    username: "johndoe",
    email: null,  // null when using username
    password: "SecurePass123!"
);

// Option B: Login with email
$result = AuthInit::auth_login(
    username: null,  // null when using email
    email: "[email protected]",
    password: "SecurePass123!"
);

if ($result['status']) {
    echo "✅ Login successful! User session established.";
    // User is now authenticated
    // CSRF token and session ID are in secure cookies
} else {
    echo "❌ " . $result['msg'];
}

// ============================================
// FLOW 3: USER LOGOUT
// ============================================

$result = AuthInit::auth_logout();
if ($result['status']) {
    echo "✅ Logged out successfully";
    header('Location: /login');
} else {
    echo "❌ " . $result['msg'];
}

// ============================================
// FLOW 4: PASSWORD RECOVERY (Magic Link)
// ============================================

// Step 1: User requests recovery link
$result = AuthInit::auth_account_recovery_link('[email protected]');
if ($result['status']) {
    echo "✅ Recovery link sent to email";
    // Email contains: /reset?token=abc123xyz&id=456789
} else {
    echo "❌ " . $result['msg'];
}

// Step 2: User clicks link in email and submits new password
$result = AuthInit::auth_verify_recovery(
    magic_id: "456789",              // From URL: ?id=456789
    magic_token: "abc123xyz",        // From URL: ?token=abc123xyz
    new_password: "NewSecurePass456!",
    confirm_password: "NewSecurePass456!"
);

if ($result['status']) {
    echo "✅ Password reset successful!";
    header('Location: /login');
} else {
    echo "❌ " . $result['msg'];
}


[
    'status' => true,      // Success or failure
    'msg'    => 'Message'  // Success or error message
]

$result = AuthInit::auth_login('user', null, 'pass');

if ($result['status']) {
    // Success - user is logged in
    echo $result['msg'];  // "Login successful"
} else {
    // Failure - show error
    echo $result['msg'];  // Error reason
}

AuthInit::init();

$result = AuthInit::auth_send_otp($email);

$result = AuthInit::auth_send_otp('[email protected]');
if ($result['status']) {
    echo "OTP sent successfully";
}

$result = AuthInit::auth_register($name, $username, $email, $password, $otp_input);

$result = AuthInit::auth_register(
    'John Doe',
    'johndoe',
    '[email protected]',
    'SecurePass123!',
    '123456'
);

$result = AuthInit::auth_login($username, $email, $password);

// Login with username
$result = AuthInit::auth_login('johndoe', null, 'SecurePass123!');

// OR login with email
$result = AuthInit::auth_login(null, '[email protected]', 'SecurePass123!');

$result = AuthInit::auth_logout();

$result = AuthInit::auth_logout();
if ($result['status']) {
    header('Location: /login');
}

$result = AuthInit::auth_account_recovery_link($email);

$result = AuthInit::auth_account_recovery_link('[email protected]');
// Email will contain: /reset?token=xyz&id=123456

$result = AuthInit::auth_verify_recovery($magic_id, $magic_token, $new_password, $confirm_password);

$result = AuthInit::auth_verify_recovery(
    '123456',
    'xyz...',
    'NewSecurePass456!',
    'NewSecurePass456!'
);

[
    'status' => true,   // Boolean: success or failure
    'msg'    => 'Text'  // String: message or error description
]

$result = AuthInit::auth_login('user', null, 'pass');

if ($result['status']) {
    // ✅ Success - proceed
    echo $result['msg'];
} else {
    // ❌ Failure - show error
    echo "Error: " . $result['msg'];
}

// In production, force HTTPS
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

// Always check response status
$response = AuthInit::auth_login($username, '', $password);

if (!$response['status']) {
    // Log error, show user-friendly message
    error_log("Login failed: " . $response['msg']);
    // Don't expose details to frontend
}

// Configure based on your user base
// Conservative: MAX_ATTEMPTS=3, PENALTY_PERIOD=300
// Moderate: MAX_ATTEMPTS=5, PENALTY_PERIOD=60
// Lenient: MAX_ATTEMPTS=10, PENALTY_PERIOD=30

// Inform users about limits in UI
if ($response['reason'] === 'Too many attempts') {
    // Show "Please try again in X minutes"
}

// Always validate CSRF token for state-changing operations
$csrf_from_cookie = $_COOKIE['csrf-token'] ?? null;
$csrf_from_form = $_POST['csrf-token'] ?? null;

if (!hash_equals($csrf_from_cookie, $csrf_from_form)) {
    header('HTTP/1.1 403 Forbidden');
    exit('CSRF token mismatch');
}

// Verify OTP within valid window (5 minutes default)
// Rate limit OTP entry attempts (3-5 attempts)
// Log all OTP verification attempts
// Show remaining attempts to user

// Future API
$result = AuthInit::auth_enable_2fa($user_id, $method = 'totp');
$result = AuthInit::auth_verify_2fa($user_id, $code);
$result = AuthInit::auth_recovery_code($user_id); // Generate backup codes

// Future API
$result = AuthInit::auth_register_passkey($user_id, $device_name);
$result = AuthInit::auth_login_passkey($passkey_id, $signature);
$result = AuthInit::auth_list_passkeys($user_id);

// Future API
$result = AuthInit::ip_whitelist_add($ip_range, $description);
$result = AuthInit::ip_blacklist_add($ip, $reason);
$result = AuthInit::ip_check_status($ip);

// Future API
$result = AuthInit::oauth_authorize($client_id, $redirect_uri, $scope);
$result = AuthInit::oauth_token($client_id, $client_secret, $code);
$result = AuthInit::oauth_social_login($provider, $access_token);

// Future API
$result = AuthInit::webhook_register($event, $url, $secret);
$result = AuthInit::webhook_test($webhook_id);
$result = AuthInit::webhook_logs($webhook_id);

// Future API
$result = AuthInit::admin_get_users($filters, $pagination);
$result = AuthInit::admin_get_audit_logs($filters, $date_range);
$result = AuthInit::admin_suspend_user($user_id, $reason, $duration);

// Future API
$result = AuthInit::admin_login($username, $password, $totp_code);
$result = AuthInit::admin_create_user($user_data, $role);
$result = AuthInit::admin_reset_user_password($user_id);