50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
|
|
<?php
|
||
|
|
/**
|
||
|
|
* API Bootstrap - Common setup for API endpoints
|
||
|
|
*
|
||
|
|
* Provides: $conn, $currentUser, $userId, $isAdmin
|
||
|
|
*
|
||
|
|
* Usage:
|
||
|
|
* require_once __DIR__ . '/bootstrap.php';
|
||
|
|
* // $conn, $currentUser, $userId, $isAdmin are now available
|
||
|
|
*/
|
||
|
|
|
||
|
|
ini_set('display_errors', 0);
|
||
|
|
error_reporting(E_ALL);
|
||
|
|
|
||
|
|
// Rate limiting (also starts session)
|
||
|
|
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
||
|
|
RateLimitMiddleware::apply('api');
|
||
|
|
|
||
|
|
// Config and database
|
||
|
|
require_once dirname(__DIR__) . '/config/config.php';
|
||
|
|
require_once dirname(__DIR__) . '/helpers/Database.php';
|
||
|
|
|
||
|
|
// Authentication check
|
||
|
|
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
|
||
|
|
http_response_code(401);
|
||
|
|
header('Content-Type: application/json');
|
||
|
|
echo json_encode(['success' => false, 'error' => 'Authentication required']);
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
|
||
|
|
// CSRF protection for write requests
|
||
|
|
if (in_array($_SERVER['REQUEST_METHOD'], ['POST', 'PUT', 'DELETE'])) {
|
||
|
|
require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php';
|
||
|
|
$csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
|
||
|
|
if (!CsrfMiddleware::validateToken($csrfToken)) {
|
||
|
|
http_response_code(403);
|
||
|
|
header('Content-Type: application/json');
|
||
|
|
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
header('Content-Type: application/json');
|
||
|
|
|
||
|
|
// Common variables
|
||
|
|
$currentUser = $_SESSION['user'];
|
||
|
|
$userId = $currentUser['user_id'];
|
||
|
|
$isAdmin = $currentUser['is_admin'] ?? false;
|
||
|
|
$conn = Database::getConnection();
|