66e4905796
Behind a proxy REMOTE_ADDR is the proxy, so the per-IP limit would lump every visitor together. New optional CLIENT_IP_HEADER in config.php (e.g. 'CF-Connecting-IP') tells the throttle which header carries the real address; invalid or absent values fall back to REMOTE_ADDR, and configs that predate the setting behave as before. Only for origins unreachable except through the proxy — documented in the README, which also covers the mod_remoteip/real_ip alternative. Claude-Session: https://claude.ai/code/session_01SePf61iazhCLJBefdRLBDm
78 lines
2.4 KiB
PHP
78 lines
2.4 KiB
PHP
<?php
|
|
// GET api/auth.php -> {logged_in, username}
|
|
// POST api/auth.php {action, username?, password?}
|
|
// action: login | register | logout
|
|
require_once __DIR__ . '/../includes/auth.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
|
echo json_encode([
|
|
'logged_in' => currentUserId() !== null,
|
|
'username' => currentUsername(),
|
|
'allow_registration' => ALLOW_REGISTRATION,
|
|
'csrf' => csrfToken(),
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['error' => 'Method not allowed']);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true) ?: [];
|
|
verifyCsrfApi($data);
|
|
$action = $data['action'] ?? '';
|
|
$username = trim($data['username'] ?? '');
|
|
$password = $data['password'] ?? '';
|
|
$ip = clientIp();
|
|
|
|
switch ($action) {
|
|
case 'login':
|
|
$wait = loginRetryAfter($username, $ip);
|
|
if ($wait > 0) {
|
|
http_response_code(429);
|
|
header('Retry-After: ' . $wait);
|
|
echo json_encode(['error' => 'Too many failed sign-in attempts. '
|
|
. 'Try again in ' . max(1, (int)ceil($wait / 60)) . ' min.']);
|
|
break;
|
|
}
|
|
if (attemptLogin($username, $password)) {
|
|
clearLoginFailures($username);
|
|
echo json_encode(['ok' => true, 'username' => currentUsername(), 'csrf' => csrfToken()]);
|
|
} else {
|
|
recordLoginFailure($username, $ip);
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Invalid username or password.']);
|
|
}
|
|
break;
|
|
|
|
case 'register':
|
|
if (!ALLOW_REGISTRATION) {
|
|
http_response_code(403);
|
|
echo json_encode(['error' => 'Registration is disabled.']);
|
|
break;
|
|
}
|
|
$result = registerUser($username, $password);
|
|
if ($result === true) {
|
|
attemptLogin($username, $password);
|
|
echo json_encode(['ok' => true, 'username' => currentUsername(), 'csrf' => csrfToken()]);
|
|
} else {
|
|
http_response_code(422);
|
|
echo json_encode(['error' => $result]);
|
|
}
|
|
break;
|
|
|
|
case 'logout':
|
|
$_SESSION = [];
|
|
session_destroy();
|
|
echo json_encode(['ok' => true]);
|
|
break;
|
|
|
|
default:
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Unknown action']);
|
|
}
|