added more login logic

This commit is contained in:
2025-10-16 19:20:17 +02:00
parent 4b0a9bdd6d
commit bdd7a8e2e2
6 changed files with 51 additions and 32 deletions

View File

@@ -13,7 +13,7 @@ struct Session {
std::unordered_map<std::string, Session> sessions;
bool verifyHashWithPassword(std::string& const hash, std::string const& password)
bool verifyHashWithPassword(const std::string& hash, std::string const& password)
{
if (crypto_pwhash_str_verify(hash.c_str(), password.c_str(), password.size()) == 0) {
return true;
@@ -22,7 +22,7 @@ bool verifyHashWithPassword(std::string& const hash, std::string const& password
}
}
std::string hashPassword(std::string& const password)
std::string hashPassword(const std::string& password)
{
// Allocate storage for the hash
char hash[crypto_pwhash_STRBYTES];
@@ -103,21 +103,19 @@ auto login_required = [](auto handler){
bool loginUser(const std::string& username, const std::string& password)
{
auto sql = format("SELECT password_hash FROM users HERE username = '{}' LIMIT 1;", username);
auto sql = "SELECT id, password_hash FROM users WHERE username = '?' LIMIT 1;";
auto db = Database();
if (!db.open())
return false;
auto opt_str = db.getStr(sql.c_str());
if (opt_str.has_value()) {
return verifyHashWithPassword(opt_str.value(), password);
auto str = db.getStr(sql, {username});
if (!str.empty()) {
return verifyHashWithPassword(str, password);
} else {
return false;
}
}
}
bool initDB()
{
@@ -172,35 +170,27 @@ bool initLogin(crow::SimpleApp& app)
CROW_ROUTE(app, "/login").methods("POST"_method)
([](const crow::request& req){
auto cookie_it = req.get_header_value("Cookie").find("session_id=");
if (cookie_it == std::string::npos)
return crow::response(401, "No session");
// extract session_id
std::string session_id = req.get_header_value("Cookie").substr(cookie_it + 11, 32);
auto it = sessions.find(session_id);
if (it == sessions.end()) return crow::response(401, "Invalid session");
auto session = it->second;
// parse form
auto body = crow::query_string(req.body);
std::string csrf_token = body.get("csrf_token");
std::string username = body.get("username");
std::string password = body.get("password");
if (csrf_token != session.csrf_token) return crow::response(403, "CSRF failed");
if (csrf_token != csrf_token) return crow::response(403, "CSRF failed");
bool ok = loginUser();
bool ok = loginUser(username, password);
if (!ok) return crow::response(401, "Invalid credentials");
std::string session_id = generate_session_id();
// regenerate session, mark as logged in
sessions[session_id].user_id = generate_session_id(); // user ID
sessions[session_id].user_id; // user ID
crow::response res;
res.add_header("HX-Redirect", "/dashboard"); // htmx redirect
return res;
});
return true;
}
}