37325-vm/api/users.php
Flatlogic Bot c7e40bdd09 1.1
2026-01-08 17:14:09 +00:00

86 lines
3.1 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
function sendJsonResponse($data, $statusCode = 200) {
http_response_code($statusCode);
echo json_encode($data);
exit();
}
// Basic API Key check (for demonstration purposes)
// In a real application, use a more robust authentication mechanism (e.g., OAuth2, JWT)
function checkApiKey() {
$headers = getallheaders();
$apiKey = $headers['X-Api-Key'] ?? '';
// Replace 'YOUR_SECRET_API_KEY' with a strong, secret API key
// This should ideally be stored in an environment variable or secure configuration
if ($apiKey !== 'YOUR_SECRET_API_KEY') {
sendJsonResponse(['error' => 'Unauthorized', 'message' => 'Invalid API Key.'], 401);
}
}
checkApiKey();
$pdo = db();
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
if (isset($_GET['id'])) {
// Get single user
$id = $_GET['id'];
try {
$stmt = $pdo->prepare("SELECT id, name, email, created_at, updated_at FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
$user = $stmt->fetch();
if ($user) {
sendJsonResponse($user);
} else {
sendJsonResponse(['error' => 'Not Found', 'message' => 'User not found.'], 404);
}
} catch (PDOException $e) {
sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500);
}
} else {
// Get all users
try {
$stmt = $pdo->query("SELECT id, name, email, created_at, updated_at FROM users ORDER BY name");
$users = $stmt->fetchAll();
sendJsonResponse($users);
} catch (PDOException $e) {
sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500);
}
}
break;
case 'POST':
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || empty($data['name']) || empty($data['email']) || empty($data['password'])) {
sendJsonResponse(['error' => 'Bad Request', 'message' => 'Name, email, and password are required.'], 400);
}
$name = $data['name'];
$email = $data['email'];
$password = password_hash($data['password'], PASSWORD_DEFAULT);
try {
$stmt = $pdo->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :password)");
$stmt->execute([
'name' => $name,
'email' => $email,
'password' => $password
]);
sendJsonResponse(['message' => 'User created successfully', 'id' => $pdo->lastInsertId()], 201);
} catch (PDOException $e) {
sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500);
}
break;
default:
sendJsonResponse(['error' => 'Method Not Allowed', 'message' => '' . $method . ' method is not supported.'], 405);
break;
}