#include "login.hpp" #include "crow/http_response.h" #include "databasepool.h" #include "SessionHandler.hpp" #include namespace login { SessionHandler sessionHandler; std::string getSessionId(const crow::request& req) { auto cookie_header = req.get_header_value("Cookie"); std::string prefix = "session_id="; auto pos = cookie_header.find(prefix); if (pos == std::string::npos) return ""; return cookie_header.substr(pos + prefix.size(), Session::SESSION_ID_SIZE); } static crow::response redirectToLogin(){ crow::response res(302); // 302 = temporary redirect res.set_header("Location", "/"); return res; } std::optional isLoggedIn(const crow::request& req) { std::string sessionId = getSessionId(req); if (sessionId.empty()) return std::move(redirectToLogin()); auto userId = sessionHandler.isSessionValid(sessionId); if(!userId.has_value()) return std::move(redirectToLogin()); return {}; } std::optional loginUser(const std::string& username, const std::string& password) { auto user = getVerifiedUser(username, password); if (user) { return sessionHandler.createSession(user->id); } return {}; } void initLogin(crow::App& app) { createUser("lukas", "Trollar4928"); CROW_ROUTE(app, "/login").methods("POST"_method) ([](const crow::request& req) { nlohmann::json body = nlohmann::json::parse(req.body); // parse JSON from HTTP body if (body.empty()) return crow::response(400, "Invalid JSON"); auto usenameIt = body.find("username"); auto passwordIt = body.find("password"); if(usenameIt == body.end() || passwordIt == body.end()) return crow::response(400, "No username or password in body"); const std::string& username = *usenameIt; const std::string& password = *passwordIt; // Validate credentials auto sessionId = loginUser(username, password); if(!sessionId.has_value()) return crow::response(401, "Invalid credentials"); // Set cookie crow::response res; res.code = 200; res.set_header( "Set-Cookie", "session_id=" + sessionId.value() + "; HttpOnly; Path=/; SameSite=Strict" // add "; Secure" when using HTTPS ); res.set_header("Access-Control-Allow-Credentials", "true"); res.set_header("Access-Control-Allow-Origin", "http://localhost:5173"); res.body = "Logged in"; return res; }); } }