From 62448b759a3a94a3adaa08e07ff98c56e1f2fb9e Mon Sep 17 00:00:00 2001 From: tastytea Date: Sun, 17 Jan 2021 18:50:32 +0100 Subject: [PATCH] Implement captcha check, don't reject entries yet. Report if captcha check failed but accept entry anyway. --- src/cgi.cpp | 23 +++++++++++++++++++++++ src/cgi.hpp | 11 +++++++++++ src/main.cpp | 6 ++++++ 3 files changed, 40 insertions(+) diff --git a/src/cgi.cpp b/src/cgi.cpp index b58abab..fe1a2eb 100644 --- a/src/cgi.cpp +++ b/src/cgi.cpp @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -68,6 +69,13 @@ entry_type parse_formdata() throw SpamException{}; } + if (!captcha_valid(static_cast(std::stoul(cgi("captcha_id"))), + cgi("captcha_answer"))) + { + // throw CaptchaException{}; + std::cout << "DEBUG: Captcha invalid. You can ignore this line.\r\n"; + } + entry.instance = cgi("instance"); entry.tags = string_to_vector(cgi("tags")); transform(entry.tags.begin(), entry.tags.end(), entry.tags.begin(), @@ -184,9 +192,24 @@ string text2html(string text) return text; } +bool captcha_valid(std::uint8_t id, const string_view answer) +{ + std::array answers{"2", "6", "17", "12", "4", "1"}; + if (answers.at(id) == answer) + { + return true; + } + return false; +} + } // namespace FediBlock::cgi const char *SpamException::what() const noexcept { return "Spam detected."; } + +const char *CaptchaException::what() const noexcept +{ + return "The solution to the captcha is not correct."; +} diff --git a/src/cgi.hpp b/src/cgi.hpp index 28b81c1..2151bb2 100644 --- a/src/cgi.hpp +++ b/src/cgi.hpp @@ -19,6 +19,7 @@ #include "types.hpp" +#include #include #include #include @@ -52,6 +53,9 @@ using std::vector; // Replace certain characters with HTML tags or entities. string text2html(string text); +// Check if the answer matches the solution we have for the id. +bool captcha_valid(std::uint8_t id, string_view answer); + } // namespace FediBlock::cgi class SpamException : public std::exception @@ -61,4 +65,11 @@ public: const char *what() const noexcept override; }; +class CaptchaException : public std::exception +{ +public: + // NOLINTNEXTLINE(modernize-use-nodiscard) + const char *what() const noexcept override; +}; + #endif // FEDIBLOCK_BACKEND_CGI_HPP diff --git a/src/main.cpp b/src/main.cpp index e78e8ff..cd18be0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -84,6 +84,12 @@ int main() cerr << e.what() << '\n'; cout << e.what() << "\r\n"; } + catch (const CaptchaException &e) + { + cerr << e.what() << '\n'; + cout << e.what() << "\r\n" + << "Use the back button of your browser to try again.\r\n"; + } catch (const exception &e) { cerr << e.what() << '\n';