From 8b930c7480622f7179011459d312340fda2ce86b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B8rgen=20Sverre=20Lien=20Sell=C3=A6g?= Date: Sun, 23 May 2021 17:10:01 +0200 Subject: [PATCH] send back 403 with validation errors --- include/data.hpp | 2 +- src/data.cpp | 32 ++++++++++++++++++++------------ src/store.cpp | 10 ++++++---- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/include/data.hpp b/include/data.hpp index 77e9ff4..e0bec4c 100644 --- a/include/data.hpp +++ b/include/data.hpp @@ -8,9 +8,9 @@ class data : public json { fs::path &get_data_path(); void create_data_directory(); fs::path get_store_path(); - json validate(const json &); public: data(); json process(const json &); + json validate(const json &); }; diff --git a/src/data.cpp b/src/data.cpp index eb139fa..31c1aec 100644 --- a/src/data.cpp +++ b/src/data.cpp @@ -42,14 +42,7 @@ void data::create_data_directory() { fs::path data::get_store_path() { return get_data_path() / "store.json"; } -json data::process(const json &input) { - const auto errors = validate(input); - if (errors.size() != 0) { - return errors; - } - - return input; -} +json data::process(const json &input) { return input; } json data::validate(const json &input) { const std::string name = input.value("name", ""); @@ -60,16 +53,31 @@ json data::validate(const json &input) { const std::unordered_map strings{ {"name", name}, {"address", address}, {"phone", phone}, {"email", email}}; - json errors = json::array(); + json errors = json::object({ + {"name", json::array()}, + {"address", json::array()}, + {"phone", json::array()}, + {"email", json::array()}, + }); + + + int count = 0; + + const auto add_error = [&](json &field, const std::string &str) { + count++; + field.push_back(str); + }; for (const auto &f : strings) { + auto &field = errors[f.first]; + if (f.second.size() == 0) { - errors.push_back({{f.first, "Missing name."}}); + add_error(field, "is missing from form."); } if (f.second.size() >= 255) { - errors.push_back({{f.first, "Name is to long."}}); + add_error(field, "to long to process. 254+"); } } - return errors; + return json{{"errors", errors}, {"count", count}}; } diff --git a/src/store.cpp b/src/store.cpp index f5a8ebc..c9d9aeb 100644 --- a/src/store.cpp +++ b/src/store.cpp @@ -78,12 +78,14 @@ int Application::run() { return response::not_found(response); } - const auto json_response = dat.process(data); - - if (json_response.is_array()) { - return response::bad_request(response, json_response); + const auto errors = dat.validate(data); + int error_count = errors["count"]; + if (error_count != 0) { + return response::bad_request(response, errors["errors"]); } + const auto json_response = dat.process(data); + response->write(Status::success_created, json_response.dump(), {header_access_control, header_application_data}); };