added more login logic

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

View File

@ -78,7 +78,7 @@ add_executable(${TARGET_NAME}
target_compile_definitions(${TARGET_NAME} PRIVATE APPLICATION_NAME="${TARGET_NAME}")
target_link_libraries(${TARGET_NAME} pthread sqlite3)
target_link_libraries(${TARGET_NAME} pthread sqlite3 sodium)
# Optional: Print build type at configuration time
message(STATUS "Configuring build type: ${CMAKE_BUILD_TYPE}")

View File

@ -36,9 +36,29 @@ bool Database::exec(const std::string& sqlQuery){
return exec(sqlQuery.c_str());
}
map<string, string> Database::getStrMap(const string& sql){
sqlite3_stmt* stmt = prepareStmt(sql);
sqlite3_stmt* Database::bind(const std::string sql, const Database::QueryData& data) {
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(m_db, sql.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
CROW_LOG_ERROR << "Failed to prepare statement: " << sqlite3_errmsg(m_db);
return nullptr;
}
for (int i = 0; i < data.size(); i++) {
std::visit([stmt, i](auto&& val) {
using T = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<T, int64_t>)
sqlite3_bind_int64(stmt, i + 1, val);
else if constexpr (std::is_same_v<T, double>)
sqlite3_bind_double(stmt, i + 1, val);
else if constexpr (std::is_same_v<T, std::string>)
sqlite3_bind_text(stmt, i + 1, val.c_str(), -1, SQLITE_TRANSIENT);
}, data[i]);
}
return stmt;
}
map<string, string> Database::getStrMap(const std::string sql, const Database::QueryData& data){
map<string, string> map;
sqlite3_stmt* stmt = bind(sql, data);
if (stmt == nullptr)
return map;
@ -52,8 +72,8 @@ map<string, string> Database::getStrMap(const string& sql){
return map;
}
string Database::getStr(const string& sql){
sqlite3_stmt* stmt = prepareStmt(sql);
string Database::getStr(const std::string sql, const Database::QueryData& data){
sqlite3_stmt* stmt = bind(sql, data);
string str;
if (stmt == nullptr)
return str;

View File

@ -3,12 +3,16 @@
#include "sqlite3.h"
#include <string>
#include <vector>
#include <variant>
#include <optional>
#include <set>
#include <map>
class Database {
typedef std::vector<std::variant<int64_t, std::string>> QueryData;
public:
Database();
~Database();
@ -24,9 +28,11 @@ public:
std::set<std::string> getStrSet(const std::string& sql);
string getStr(const string& sql)
std::string getStr(const std::string sql, const QueryData& data);
std::map<std::string, std::string> getStrMap(const std::string& sql);
sqlite3_stmt* bind(const std::string sql, const QueryData& data);
std::map<std::string, std::string> getStrMap(const std::string sql, const QueryData& data);
private:
sqlite3_stmt* prepareStmt(const std::string& sql);

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;
}
}

View File

@ -108,7 +108,10 @@ int main() {
}
shadowrun::initApi(app);
login::initLogin(app);
if(!login::initLogin(app))
{
CROW_LOG_ERROR << "Failed to init Login API";
}
app.loglevel(crow::LogLevel::INFO);
app.port(httpPort).multithreaded().run();

View File

@ -99,12 +99,12 @@ std::set<std::string> getCharacters(){
}
std::map<std::string, std::string> getCharacterData(int64_t characterKey) {
auto sql = format("SELECT name, value FROM shadowrun_data WHERE character_id = {};", characterKey);
std::string sql = "SELECT name, value FROM shadowrun_data WHERE character_id = ?;";
auto db = Database();
if (!db.open())
return std::map<std::string, std::string>();
return db.getStrMap(sql);
return db.getStrMap(sql, {characterKey});
}
}