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

62 lines
2.2 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 'POST':
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || empty($data['email']) || empty($data['password'])) {
sendJsonResponse(['error' => 'Bad Request', 'message' => 'Email and password are required.'], 400);
}
$email = $data['email'];
$password = $data['password'];
try {
$stmt = $pdo->prepare("SELECT id, name, email, password FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
// For a real API, generate and return a token (e.g., JWT)
// For this example, we'll just return a success message and user info (without password)
unset($user['password']);
sendJsonResponse(['message' => 'Login successful.', 'user' => $user]);
} else {
sendJsonResponse(['error' => 'Unauthorized', 'message' => 'Invalid credentials.'], 401);
}
} 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;
}