CZI_presence_detector/website/update.php

70 lines
1.6 KiB
PHP
Raw Permalink Normal View History

2023-08-12 17:23:33 +02:00
<?php
$secret_key = 'CHANGE-THIS';
$present_file = 'present.json';
// check for POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
2023-08-16 16:53:38 +02:00
error_log('FAILED - not POST - ' . $_SERVER['REQUEST_METHOD']);
2023-08-12 17:23:33 +02:00
http_response_code(405);
exit();
}
// get content type
$content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';
if ($content_type != 'application/json') {
2023-08-16 16:53:38 +02:00
error_log('FAILED - not application/json - ' . $content_type);
2023-08-12 17:23:33 +02:00
http_response_code(400);
exit();
}
// get payload
$payload = trim(file_get_contents("php://input"));
if (empty($payload)) {
error_log('FAILED - no payload');
http_response_code(400);
exit();
}
// get header signature
$header_signature = isset($_SERVER['HTTP_X_HMAC_HASH']) ? $_SERVER['HTTP_X_HMAC_HASH'] : '';
if (empty($header_signature)) {
error_log('FAILED - header signature missing');
http_response_code(401);
exit();
}
// calculate payload signature
$payload_signature = hash_hmac('sha256', $payload, $secret_key, false);
// check payload signature against header signature
if ($header_signature !== $payload_signature) {
error_log('FAILED - payload signature');
http_response_code(401);
exit();
}
// convert json to array
$decoded = json_decode($payload, true);
// check for json decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
2023-08-16 16:53:38 +02:00
error_log('FAILED - json decode - ' . json_last_error());
2023-08-12 17:23:33 +02:00
http_response_code(400);
exit();
}
// success, do something
http_response_code(200);
2023-08-17 17:14:58 +02:00
sort($decoded);
2023-08-12 17:23:33 +02:00
$present = array(
"timestamp" => time(),
2023-08-17 17:14:58 +02:00
"names" => $decoded
2023-08-12 17:23:33 +02:00
);
2023-08-16 16:53:38 +02:00
file_put_contents($present_file, json_encode($present));