<?php
// Classic SQLi login + plaintext-password brute target.
$dbh = @new mysqli(getenv('DB_HOST') ?: 'db', 'root', getenv('DB_PASS') ?: 'toor', getenv('DB_NAME') ?: 'newploit');

$user = $_POST['username'] ?? $_POST['user'] ?? '';
$pass = $_POST['password'] ?? $_POST['pass'] ?? '';
$csrf = bin2hex(random_bytes(8));
$err  = '';
$ok   = false;

if ($user !== '' || $pass !== '') {
    $sql = "SELECT id, username, role FROM users WHERE username='$user' AND password='$pass'";
    if ($dbh && !$dbh->connect_errno) {
        $res = @$dbh->query($sql);
        if ($res === false) {
            $err = $dbh->error;
        } else {
            $row = $res->fetch_assoc();
            if ($row) {
                $ok = true;
                setcookie('session', base64_encode(json_encode($row)), time() + 3600, '/');
                header("Location: /admin/?welcome=" . urlencode($row['username']));
                exit;
            } else {
                $err = "Invalid username or password";
            }
        }
    } else {
        $err = "Database unavailable";
    }
}

// Open redirect on `next` param.
$next = $_GET['next'] ?? $_GET['url'] ?? '';
if ($next !== '' && $user === '' && !$ok) {
    header("Location: $next", true, 302);
    exit;
}
?><!DOCTYPE html>
<html><body>
<h1>Member login</h1>

<?php if ($err): ?>
<p style="color:red"><?= htmlspecialchars($err) ?></p>
<?php endif; ?>

<form method="post" action="/login.php">
    <input type="hidden" name="csrf" value="<?= $csrf ?>">
    <p><label>username <input name="username" value="<?= htmlspecialchars($user) ?>"></label></p>
    <p><label>password <input name="password" type="password"></label></p>
    <p><button type="submit">sign in</button></p>
</form>

<p><a href="/wp-login.php">blog login</a> &middot; <a href="/admin/">admin</a></p>
</body></html>
