From 7783aeb63ec08bed159942fb0df100cfc4e93d3c Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Sun, 2 Jan 2022 02:49:54 +0100 Subject: Build config and check api key --- src/App.php | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) (limited to 'src/App.php') diff --git a/src/App.php b/src/App.php index 20cec62..fcf2699 100644 --- a/src/App.php +++ b/src/App.php @@ -18,7 +18,7 @@ class App $response = new Response(); $content = [ - 'data' => '', + 'data' => [], ]; $contentRoot = dirname(__DIR__) . '/content'; @@ -26,6 +26,19 @@ class App $path = $request->getPathInfo(); try { + $config = $this->buildConfig($contentRoot . $path); + + // check api key + $apiKey = $_GET['key'] ?? $_POST['key'] ?? null; + if (empty($apiKey)) { + $response->setStatusCode(Response::HTTP_BAD_REQUEST); + throw new \Exception('API key missing'); + } + if (! in_array($apiKey, $config['api']['keys'])) { + $response->setStatusCode(Response::HTTP_UNAUTHORIZED); + throw new \Exception('API key does not match'); + } + // GET if ($method == 'GET') { if (str_ends_with($path, '/fields')) { @@ -98,12 +111,12 @@ class App { $fields = Toml::parseFile($formPath . '/fields/_fields.toml')['field'] ?? []; foreach ($fields as $key => $field) { - if (empty($field['name'])) { - $field['name'] = $key; + if (! empty($field['file'])) { + $field = array_replace_recursive($field, Toml::parseFile($formPath . '/fields/' . $field['file'])); } - if (! empty($field['file'])) { - $field = array_merge($field, Toml::parseFile($formPath . '/fields/' . $field['file'])); + if (empty($field['name'])) { + $field['name'] = $key; } $fields[$key] = $field; @@ -127,5 +140,32 @@ class App return $fields; } + + /** + * @param string $formPath + */ + public function buildConfig($formPath) + { + $config = []; + $currentFolder = $formPath; + while (true) { + $configFile = $currentFolder . '/config/config.toml'; + if (file_exists($configFile)) { + $parsedConfig = Toml::parseFile($configFile); + + $apiKeys = array_merge($parsedConfig['api']['keys'] ?? [], $config['api']['keys'] ?? []); + $config = array_replace_recursive($parsedConfig, $config); + $config['api']['keys'] = $apiKeys; + } + + if (str_ends_with($currentFolder, '/content') || $currentFolder == '/') { + break; + } + + $currentFolder = dirname($currentFolder); + } + + return $config; + } } -- cgit v1.2.3