61 lines
1.7 KiB
PHP
61 lines
1.7 KiB
PHP
<?php
|
|
require_once '../config.php';
|
|
require_once '../vendor/autoload.php';
|
|
|
|
use Firebase\JWT\JWT;
|
|
use Firebase\JWT\Key;
|
|
|
|
header('Content-Type: application/json');
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: GET, POST');
|
|
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
|
|
|
// Vérification du token JWT
|
|
function verify_token() {
|
|
$headers = getallheaders();
|
|
if (!isset($headers['Authorization'])) {
|
|
http_response_code(401);
|
|
echo json_encode(['message' => 'Token manquant']);
|
|
exit();
|
|
}
|
|
$token = str_replace('Bearer ', '', $headers['Authorization']);
|
|
try {
|
|
return JWT::decode($token, new Key(JWT_SECRET, 'HS256'));
|
|
} catch (Exception $e) {
|
|
http_response_code(401);
|
|
echo json_encode(['message' => 'Token invalide']);
|
|
exit();
|
|
}
|
|
}
|
|
|
|
verify_token();
|
|
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
$db = get_db();
|
|
|
|
// GET — Récupérer toutes les données climatiques
|
|
if ($method === 'GET') {
|
|
$result = $db->query("SELECT * FROM climate_data ORDER BY timestamp DESC LIMIT 50");
|
|
$data = [];
|
|
while ($row = $result->fetch_assoc()) {
|
|
$data[] = $row;
|
|
}
|
|
echo json_encode($data);
|
|
|
|
// POST — Ajouter une donnée climatique
|
|
} elseif ($method === 'POST') {
|
|
$body = json_decode(file_get_contents('php://input'), true);
|
|
$stmt = $db->prepare("INSERT INTO climate_data (temperature, humidity, pressure, luminosity) VALUES (?, ?, ?, ?)");
|
|
$stmt->bind_param("dddd",
|
|
$body['temperature'],
|
|
$body['humidity'],
|
|
$body['pressure'],
|
|
$body['luminosity']
|
|
);
|
|
$stmt->execute();
|
|
http_response_code(201);
|
|
echo json_encode(['message' => 'Donnée ajoutée avec succès']);
|
|
}
|
|
|
|
$db->close();
|
|
?>
|