crow_single_page_app_desktop/source/main.cpp
#include <crow/http_response.h>
#include <fmt/base.h>
#include <crow.h>
#include <fmt/core.h>
#include <thread>
bool is_port_ready(const char* host, int port) {
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd < 0)
return false;
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_port = htons(port);
if (inet_pton(AF_INET, host, &address.sin_addr) != 1) {
close(socket_fd);
return false;
}
bool is_ready = connect(
socket_fd,
reinterpret_cast<sockaddr*>(&address),
sizeof(address)
) == 0;
close(socket_fd);
return is_ready;
}
std::string genPassword(const unsigned int len) {
const std::string caratteri = "abcdefghijklmnopqrstuvwxyz";
std::string password;
std::srand(static_cast<unsigned int>(std::time(0)));
for (unsigned int i = 0; i < len; ++i) {
int indice = std::rand() % caratteri.length();
password += caratteri[indice];
}
return password;
}
int main()
{
crow::SimpleApp app;
auto pin = genPassword(15);
// fmt::println("Il pin รจ {}",pin);
CROW_ROUTE(app, "/")
([](){
crow::response res;
res.code = 302;
res.set_header("Location", "/home");
return res;
});
CROW_ROUTE(app, "/home/<string>")([&](std::string npin){
crow::response res;
if (npin != pin)
{
res.code = 403;
auto t = crow::mustache::load_text("pin_error.html");
auto page = crow::mustache::compile(t);
crow::mustache::context ctx;
return page.render(ctx);
app.stop();
}
res.code = 200;
res.set_header("Content-Type", "text/html");
auto t = crow::mustache::load_text("home.html");
auto page = crow::mustache::compile(t);
crow::mustache::context ctx;
ctx["pin"] = pin;
return page.render(ctx);
});
CROW_ROUTE(app, "/square")
.methods(crow::HTTPMethod::POST)([&](const crow::request& req){
auto json = crow::json::load(req.body);
if (!json)
return crow::response(400, "JSON not valid");
int mynumber = json["mynumber"].i();
std::string npin= json["pin"].s();
//response
crow::json::wvalue res;
if (npin==pin){
res["square"] = mynumber*mynumber;
return crow::response(200,res);
}else{
res["square"]="forbidden!";
return crow::response(403,res);
}
});
std::thread server([&]{
app.bindaddr("127.0.0.1").port(8080).multithreaded().run();
});
while (!is_port_ready("127.0.0.1", 8080)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
auto cmd=fmt::format("xdg-open http://127.0.0.1:8080/home/{}",pin);
std::system(cmd.c_str());
server.join();
}