65 lines
1.8 KiB
PHP
65 lines
1.8 KiB
PHP
<?php
|
|
require __DIR__ . '/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['error' => 'Method not allowed']);
|
|
exit;
|
|
}
|
|
|
|
if (!REQUIRE_INVITE_CODE) {
|
|
echo json_encode(['valid' => true]);
|
|
exit;
|
|
}
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$code = trim($input['code'] ?? '');
|
|
|
|
if (!$code) {
|
|
http_response_code(400);
|
|
echo json_encode(['valid' => false, 'error' => 'Missing invite code']);
|
|
exit;
|
|
}
|
|
|
|
$url = DIRECTUS_URL . '/items/invite_codes?filter[code][_eq]=' . urlencode($code)
|
|
. '&filter[status][_eq]=active&limit=1';
|
|
|
|
$context = stream_context_create([
|
|
'http' => [
|
|
'header' => "Authorization: Bearer " . DIRECTUS_TOKEN . "\r\n",
|
|
'ignore_errors' => true,
|
|
],
|
|
]);
|
|
|
|
$response = file_get_contents($url, false, $context);
|
|
$data = json_decode($response, true);
|
|
$invite = $data['data'][0] ?? null;
|
|
|
|
if (!$invite) {
|
|
echo json_encode(['valid' => false, 'error' => 'invalid_code']);
|
|
exit;
|
|
}
|
|
|
|
if ($invite['max_uses'] > 0 && $invite['used_count'] >= $invite['max_uses']) {
|
|
echo json_encode(['valid' => false, 'error' => 'code_redeemed']);
|
|
exit;
|
|
}
|
|
|
|
if ($invite['expires_at'] && strtotime($invite['expires_at']) < time()) {
|
|
echo json_encode(['valid' => false, 'error' => 'code_expired']);
|
|
exit;
|
|
}
|
|
|
|
$updateUrl = DIRECTUS_URL . '/items/invite_codes/' . $invite['id'];
|
|
$updateContext = stream_context_create([
|
|
'http' => [
|
|
'method' => 'PATCH',
|
|
'header' => "Content-Type: application/json\r\nAuthorization: Bearer " . DIRECTUS_TOKEN . "\r\n",
|
|
'content' => json_encode(['used_count' => $invite['used_count'] + 1]),
|
|
'ignore_errors' => true,
|
|
],
|
|
]);
|
|
file_get_contents($updateUrl, false, $updateContext);
|
|
|
|
echo json_encode(['valid' => true]);
|