| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- <?php
- declare(strict_types=1);
- require_once dirname(__DIR__, 2) . '/src/bootstrap.php';
- header('Access-Control-Allow-Methods: POST, OPTIONS');
- header('Access-Control-Allow-Headers: Authorization, Content-Type');
- if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
- http_response_code(204);
- exit;
- }
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- app_json_response([
- 'ok' => false,
- 'error' => 'Nur POST ist erlaubt.',
- ], 405);
- }
- $config = app_config_repository()->getConfig();
- $expectedToken = (string) ($config['api']['bearer_token'] ?? '');
- $authHeader = $_SERVER['HTTP_AUTHORIZATION']
- ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
- ?? '';
- if ($authHeader === '' && function_exists('getallheaders')) {
- $headers = getallheaders();
- $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
- }
- if (preg_match('/Bearer\s+(.+)/i', $authHeader, $matches) !== 1 || !hash_equals($expectedToken, trim($matches[1]))) {
- app_json_response([
- 'ok' => false,
- 'error' => 'Nicht autorisiert.',
- ], 401);
- }
- try {
- $payload = app_read_json_body();
- $result = app_monitor_service()->processReading($payload);
- app_json_response($result);
- } catch (InvalidArgumentException $exception) {
- $message = $exception->getMessage();
- $status = $message === 'Unbekannter Automat oder Sensor.' ? 404 : 422;
- app_json_response([
- 'ok' => false,
- 'error' => $message,
- ], $status);
- } catch (RuntimeException $exception) {
- app_json_response([
- 'ok' => false,
- 'error' => $exception->getMessage(),
- ], 400);
- } catch (Throwable $exception) {
- error_log((string) $exception);
- app_json_response([
- 'ok' => false,
- 'error' => 'Interner Fehler.',
- ], 500);
- }
|