coyote/routes/user_settings.cpp

65 lines
2.3 KiB
C++

#include "routes.h"
#include "../servehelper.h"
#include "../settings.h"
#include "../timeutils.h"
#include "../curlu_wrapper.h"
static void set_cookie(const httplib::Request& req, httplib::Response& res, const char* key, std::string_view value);
void user_settings_route(const httplib::Request& req, httplib::Response& res) {
UserSettings settings;
if (req.method == "POST") {
for (const auto& i : req.params) {
settings.set(i.first, i.second);
}
set_cookie(req, res, "auto-open-cw", settings.auto_open_cw ? "true" : "false");
} else {
settings.load_from_cookies(req);
}
Element auto_open_cw_checkbox("input", {{"type", "checkbox"}, {"name", "auto-open-cw"}, {"value", "true"}}, {});
if (settings.auto_open_cw) {
auto_open_cw_checkbox.attributes.push_back({"checked", ""});
}
Element body("body", {
Element("form", {{"class", "user_settings_page-form"}, {"method", "post"}}, {
Element("label", {
std::move(auto_open_cw_checkbox),
" Automatically open Content Warnings",
}),
Element("br"),
Element("input", {{"type", "submit"}, {"value", "Save"}}, {}),
}),
Element("form", {{"class", "user_settings_page-form"}, {"method", "get"}, {"action", get_origin(req)}}, {
Element("input", {{"class", "cancel"}, {"type", "submit"}, {"value", "Cancel"}}, {}),
}),
});
if (req.method == "POST") {
body.nodes.insert(body.nodes.begin(), Element("div", {{"class", "success"}}, {
Element("h3", {"Settings saved!"}),
}));
}
serve(req, res, "User settings", std::move(body));
}
static void set_cookie(const httplib::Request& req, httplib::Response& res, const char* key, std::string_view value) {
CurlUrl origin;
origin.set(CURLUPART_URL, get_origin(req));
std::string header = std::string(key) + '=' + std::string(value)
+ "; HttpOnly; SameSite=Strict; Domain=" + origin.get(CURLUPART_HOST).get() + "; Path=" + origin.get(CURLUPART_PATH).get()
+ "; Expires=" + to_web_date(current_time() + 365 * 24 * 60 * 60);
if (strcmp(origin.get(CURLUPART_SCHEME).get(), "https") == 0) {
header += "; Secure";
}
res.set_header("Set-Cookie", header);
}