readings.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. require_once dirname(__DIR__, 2) . '/src/bootstrap.php';
  4. header('Access-Control-Allow-Methods: POST, OPTIONS');
  5. header('Access-Control-Allow-Headers: Authorization, Content-Type');
  6. if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  7. http_response_code(204);
  8. exit;
  9. }
  10. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  11. app_json_response([
  12. 'ok' => false,
  13. 'error' => 'Nur POST ist erlaubt.',
  14. ], 405);
  15. }
  16. $config = app_config_repository()->getConfig();
  17. $expectedToken = (string) ($config['api']['bearer_token'] ?? '');
  18. $authHeader = $_SERVER['HTTP_AUTHORIZATION']
  19. ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
  20. ?? '';
  21. if ($authHeader === '' && function_exists('getallheaders')) {
  22. $headers = getallheaders();
  23. $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
  24. }
  25. if (preg_match('/Bearer\s+(.+)/i', $authHeader, $matches) !== 1 || !hash_equals($expectedToken, trim($matches[1]))) {
  26. app_json_response([
  27. 'ok' => false,
  28. 'error' => 'Nicht autorisiert.',
  29. ], 401);
  30. }
  31. try {
  32. $payload = app_read_json_body();
  33. $result = app_monitor_service()->processReading($payload);
  34. app_json_response($result);
  35. } catch (InvalidArgumentException $exception) {
  36. $message = $exception->getMessage();
  37. $status = $message === 'Unbekannter Automat oder Sensor.' ? 404 : 422;
  38. app_json_response([
  39. 'ok' => false,
  40. 'error' => $message,
  41. ], $status);
  42. } catch (RuntimeException $exception) {
  43. app_json_response([
  44. 'ok' => false,
  45. 'error' => $exception->getMessage(),
  46. ], 400);
  47. } catch (Throwable $exception) {
  48. app_json_response([
  49. 'ok' => false,
  50. 'error' => 'Interner Fehler.',
  51. ], 500);
  52. }