%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/
Upload File :
Create Path :
Current File : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/auth.php

<?php
/**
 * Auth Middleware — Session-based authentication (Hardened)
 */

// ============================================================
// Session Security Settings (BEFORE session_start)
// ============================================================
ini_set('session.cookie_httponly', 1);
// Secure cookies cannot be sent over HTTP, which would discard a successful
// login when the app is run locally without HTTPS.
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (int) ($_SERVER['SERVER_PORT'] ?? 80) === 443;
ini_set('session.cookie_secure', $isHttps ? '1' : '0');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.gc_maxlifetime', 31536000);       // 1 year
ini_set('session.cookie_lifetime', 31536000);       // 1 year — session selamanya
ini_set('session.use_strict_mode', 1);

session_start();

require_once __DIR__ . '/config.php';


// ============================================================
// CSRF Token Functions
// ============================================================

/**
 * Generate CSRF token and store in session
 */
function generateCSRFToken(): string {
    $token = bin2hex(random_bytes(32));
    $_SESSION['csrf_token'] = $token;
    return $token;
}

/**
 * Validate CSRF token against session token
 */
function validateCSRFToken(?string $token): bool {
    if (empty($token) || empty($_SESSION['csrf_token'])) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Return hidden input HTML for CSRF token
 */
function getCSRFTokenField(): string {
    $token = generateCSRFToken();
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
}


// ============================================================
// Rate Limiting Functions (IP-based, database-backed)
// ============================================================

/**
 * Return the connection IP address. Proxy headers are deliberately ignored
 * because clients can forge them unless a trusted proxy is configured.
 */
function getClientIP(): string {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';
}

/**
 * Ensure login_attempts table exists
 */
function ensureLoginAttemptsTable(): void {
    static $checked = false;
    if ($checked) return;

    try {
        $db = getDB();
        $db->exec("
            CREATE TABLE IF NOT EXISTS `login_attempts` (
                `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                `ip_address` VARCHAR(45) NOT NULL,
                `attempted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `success` TINYINT(1) NOT NULL DEFAULT 0,
                INDEX `idx_ip_attempted` (`ip_address`, `attempted_at`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
        $checked = true;
    } catch (PDOException $e) {
        // Silently fail — don't block login if table creation fails
    }
}

/**
 * Check if IP is rate-limited
 * Returns array: ['blocked' => bool, 'remaining_seconds' => int]
 */
function checkLoginRateLimit(string $ip): array {
    ensureLoginAttemptsTable();

    try {
        $db = getDB();

        // Count failed attempts in last 15 minutes
        $stmt = $db->prepare("
            SELECT COUNT(*) as attempts, MAX(attempted_at) as last_attempt
            FROM login_attempts
            WHERE ip_address = :ip
              AND success = 0
              AND attempted_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
        ");
        $stmt->execute([':ip' => $ip]);
        $row = $stmt->fetch();

        if ($row && (int) $row['attempts'] >= 5) {
            // Check if lockout period (30 minutes from last failed attempt) has passed
            $lastAttempt = strtotime($row['last_attempt']);
            $lockoutEnd = $lastAttempt + (30 * 60); // 30 minutes lockout
            $now = time();

            if ($now < $lockoutEnd) {
                return [
                    'blocked' => true,
                    'remaining_seconds' => $lockoutEnd - $now,
                ];
            }
        }

        return ['blocked' => false, 'remaining_seconds' => 0];
    } catch (PDOException $e) {
        // Don't block login if rate limit check fails
        return ['blocked' => false, 'remaining_seconds' => 0];
    }
}

/**
 * Record a login attempt
 */
function recordLoginAttempt(string $ip, bool $success): void {
    ensureLoginAttemptsTable();

    try {
        $db = getDB();
        $stmt = $db->prepare("
            INSERT INTO login_attempts (ip_address, attempted_at, success)
            VALUES (:ip, NOW(), :success)
        ");
        $stmt->execute([
            ':ip'      => $ip,
            ':success' => $success ? 1 : 0,
        ]);
    } catch (PDOException $e) {
        // Silently fail
    }
}

/**
 * Clear failed login attempts for an IP on successful login
 */
function clearLoginAttempts(string $ip): void {
    ensureLoginAttemptsTable();

    try {
        $db = getDB();
        $stmt = $db->prepare("DELETE FROM login_attempts WHERE ip_address = :ip");
        $stmt->execute([':ip' => $ip]);
    } catch (PDOException $e) {
        // Silently fail
    }
}


// ============================================================
// Auth Functions
// ============================================================

/**
 * Check if user is logged in
 */
function isLoggedIn(): bool {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}


/**
 * Get current logged-in user data
 */
function getCurrentUser(): ?array {
    if (!isLoggedIn()) return null;

    return [
        'id'    => $_SESSION['user_id'],
        'email' => $_SESSION['user_email'] ?? '',
        'name'  => $_SESSION['user_name'] ?? '',
    ];
}


/**
 * Require authentication — redirect to gate if not logged in
 * Use for page routes (index.php)
 */
function requireAuth(): void {
    if (!isLoggedIn()) {
        header('Location: gate.php');
        exit;
    }
}


/**
 * Require authentication — return JSON error if not logged in
 * Use for API routes (api.php)
 */
function requireAuthAPI(): void {
    if (!isLoggedIn()) {
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'error'   => 'Unauthorized. Silakan login terlebih dahulu.',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}


/**
 * Login user (hardened)
 */
function loginUser(string $email, string $password): array {
    $email = trim($email);
    $ip = getClientIP();

    // Generic error message — don't reveal specifics
    $genericError = 'Email atau password salah.';

    // Check rate limit first
    $rateLimit = checkLoginRateLimit($ip);
    if ($rateLimit['blocked']) {
        $minutes = ceil($rateLimit['remaining_seconds'] / 60);
        return [
            'success' => false,
            'error'   => 'Terlalu banyak percobaan login. Coba lagi dalam ' . $minutes . ' menit.',
        ];
    }

    // Validate inputs
    if (empty($email) || empty($password)) {
        return ['success' => false, 'error' => 'Email dan password wajib diisi.'];
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return ['success' => false, 'error' => $genericError];
    }

    // Password minimum length check
    if (strlen($password) < 6) {
        return ['success' => false, 'error' => $genericError];
    }

    try {
        $db = getDB();
        $stmt = $db->prepare('SELECT id, email, password, name FROM users WHERE email = :email LIMIT 1');
        $stmt->execute([':email' => $email]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($password, $user['password'])) {
            // Record failed attempt
            recordLoginAttempt($ip, false);
            return ['success' => false, 'error' => $genericError];
        }

        // Successful login — record and clear attempts
        recordLoginAttempt($ip, true);
        clearLoginAttempts($ip);

        // Set session
        $_SESSION['user_id']    = (int) $user['id'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_name']  = $user['name'];

        // Regenerate session ID to prevent fixation
        session_regenerate_id(true);

        return ['success' => true, 'user' => [
            'id'    => (int) $user['id'],
            'email' => $user['email'],
            'name'  => $user['name'],
        ]];

    } catch (PDOException $e) {
        // DO NOT expose database errors to users
        error_log('Login error: ' . $e->getMessage());
        return ['success' => false, 'error' => 'Terjadi kesalahan sistem. Silakan coba lagi.'];
    }
}


/**
 * Logout user
 */
function logoutUser(): void {
    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $p['path'], $p['domain'], $p['secure'], $p['httponly']
        );
    }

    session_destroy();
}

Zerion Mini Shell 1.0