From 576160b4d38d28fc5aa70fa5c03d38712dc8ac17 Mon Sep 17 00:00:00 2001 From: "David T. Sadler" Date: Thu, 1 Jul 2021 21:32:48 +0100 Subject: Implement simple add bookmark API --- .gitignore | 1 + public/bookmarks/index.php | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 .gitignore create mode 100644 public/bookmarks/index.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4f4773f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.php diff --git a/public/bookmarks/index.php b/public/bookmarks/index.php new file mode 100644 index 0000000..8ecfe24 --- /dev/null +++ b/public/bookmarks/index.php @@ -0,0 +1,47 @@ + 'Method Not Allowed']); +} + +if ('Bearer '.$config['bearer_token'] !== ($_SERVER['HTTP_AUTHORIZATION'] ?? null)) { + respondAndExit([ + 401 => 'Unauthorized', + 0 => 'WWW-Authenticate: Bearer realm="Bookmarks"', + ]); +} + +if ('application/x-www-form-urlencoded' !== ($_SERVER['CONTENT_TYPE'] ?? null)) { + respondAndExit([415 => 'Unsupported Media Type']); +} + +$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL); + +if (!$url || !strlen($url) === 0 || strlen($url) > $config['max_url_length']) { + respondAndExit([400 => 'Bad Request']); +} + +if (!file_put_contents($config['path_to_file'], "$url\n", FILE_APPEND)) { + respondAndExit([500 => 'Internal Server Error']); +} + +respondAndExit([201 => 'Created']); + +function respondAndExit(array $headers): void +{ + foreach ($headers as $responseCode => $header) { + if ($responseCode) { + header($header, false, $responseCode); + } else { + header($header); + } + } + + header('Content-type: text/plain; charset=UTF-8'); + + exit(); +} -- cgit v1.2.3-13-gbd6f