Compare commits
2 Commits
e13de7c786
...
4b0a9bdd6d
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b0a9bdd6d | |||
| 0ab7c52cfc |
@ -32,7 +32,7 @@ foreach(file IN LISTS TEMPLATE_FILES)
|
||||
endforeach()
|
||||
|
||||
# Use Crow from system include (installed via yay -S crow + asio)
|
||||
include_directories(/usr/include src src/htmx src/shadowrun src/database)
|
||||
include_directories(/usr/include src src/htmx src/shadowrun src/database src/login)
|
||||
|
||||
add_executable(${TARGET_NAME}
|
||||
src/main.cpp
|
||||
@ -70,6 +70,10 @@ add_executable(${TARGET_NAME}
|
||||
src/shadowrun/ShadowrunDb.cpp
|
||||
src/shadowrun/ShadowrunDb.hpp
|
||||
|
||||
# login
|
||||
src/login/login.cpp
|
||||
src/login/login.hpp
|
||||
|
||||
)
|
||||
|
||||
target_compile_definitions(${TARGET_NAME} PRIVATE APPLICATION_NAME="${TARGET_NAME}")
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
## Setup
|
||||
|
||||
pacman -S crow asio gdb gcc cmake make sqlite3
|
||||
pacman -S crow asio gdb gcc cmake make sqlite3 libsodium
|
||||
|
||||
## Build
|
||||
|
||||
@ -9,6 +9,12 @@ pacman -S crow asio gdb gcc cmake make sqlite3
|
||||
build : Ctrl+Shift+P → "CMake: Configure"
|
||||
run : F5 or Run → Start Debugging
|
||||
|
||||
### CompileDB
|
||||
|
||||
```
|
||||
cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
||||
```
|
||||
|
||||
## Make Package
|
||||
1. tar the source files to make it cleaner
|
||||
|
||||
|
||||
@ -52,6 +52,18 @@ map<string, string> Database::getStrMap(const string& sql){
|
||||
return map;
|
||||
}
|
||||
|
||||
string Database::getStr(const string& sql){
|
||||
sqlite3_stmt* stmt = prepareStmt(sql);
|
||||
string str;
|
||||
if (stmt == nullptr)
|
||||
return str;
|
||||
|
||||
str = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return str;
|
||||
}
|
||||
|
||||
set<string> Database::getStrSet(const string& sql){
|
||||
sqlite3_stmt* stmt = prepareStmt(sql);
|
||||
set<string> vec;
|
||||
|
||||
@ -24,6 +24,8 @@ public:
|
||||
|
||||
std::set<std::string> getStrSet(const std::string& sql);
|
||||
|
||||
string getStr(const string& sql)
|
||||
|
||||
std::map<std::string, std::string> getStrMap(const std::string& sql);
|
||||
|
||||
private:
|
||||
|
||||
206
src/login/login.cpp
Normal file
206
src/login/login.cpp
Normal file
@ -0,0 +1,206 @@
|
||||
#include "login.hpp"
|
||||
#include "string.h"
|
||||
#include "sodium.h"
|
||||
#include "unordered_map"
|
||||
#include "database.hpp"
|
||||
|
||||
namespace login
|
||||
{
|
||||
struct Session {
|
||||
std::string user_id;
|
||||
std::string csrf_token;
|
||||
};
|
||||
|
||||
std::unordered_map<std::string, Session> sessions;
|
||||
|
||||
bool verifyHashWithPassword(std::string& const hash, std::string const& password)
|
||||
{
|
||||
if (crypto_pwhash_str_verify(hash.c_str(), password.c_str(), password.size()) == 0) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string hashPassword(std::string& const password)
|
||||
{
|
||||
// Allocate storage for the hash
|
||||
char hash[crypto_pwhash_STRBYTES];
|
||||
|
||||
// Hash the password using Argon2id
|
||||
if (crypto_pwhash_str(
|
||||
hash,
|
||||
password.c_str(),
|
||||
password.size(),
|
||||
crypto_pwhash_OPSLIMIT_INTERACTIVE,
|
||||
crypto_pwhash_MEMLIMIT_INTERACTIVE
|
||||
) != 0) {
|
||||
std::cerr << "Out of memory while hashing password!" << std::endl;
|
||||
return "";
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::string generate_session_id(size_t bytes = 32) {
|
||||
std::vector<unsigned char> buf(bytes);
|
||||
randombytes_buf(buf.data(), buf.size());
|
||||
|
||||
// Convert to hex
|
||||
std::string hex;
|
||||
hex.reserve(bytes * 2);
|
||||
static const char *hexmap = "0123456789abcdef";
|
||||
for (unsigned char b : buf) {
|
||||
hex.push_back(hexmap[b >> 4]);
|
||||
hex.push_back(hexmap[b & 0xF]);
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
std::string get_session_id(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(), 32);
|
||||
}
|
||||
|
||||
// Utility: generate random string
|
||||
std::string random_string(size_t length) {
|
||||
static const char charset[] =
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
std::string result;
|
||||
result.resize(length);
|
||||
std::mt19937 rng(std::random_device{}());
|
||||
std::uniform_int_distribution<> dist(0, sizeof(charset)-2);
|
||||
for (size_t i = 0; i < length; ++i) result[i] = charset[dist(rng)];
|
||||
return result;
|
||||
}
|
||||
|
||||
bool is_logged_in(const crow::request& req) {
|
||||
std::string session_id = get_session_id(req);
|
||||
if (session_id.empty()) return false;
|
||||
auto it = sessions.find(session_id);
|
||||
if (it == sessions.end()) return false;
|
||||
return !it->second.user_id.empty();
|
||||
}
|
||||
|
||||
// lambda to be used by endpoint that requiere login
|
||||
auto login_required = [](auto handler){
|
||||
return [handler](const crow::request& req){
|
||||
if (!is_logged_in(req)) {
|
||||
crow::response res;
|
||||
if (req.get_header_value("HX-Request") == "true")
|
||||
res = crow::response(401, "Login required");
|
||||
else {
|
||||
res = crow::response(302);
|
||||
res.add_header("Location", "/login");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
return handler(req);
|
||||
};
|
||||
};
|
||||
|
||||
bool loginUser(const std::string& username, const std::string& password)
|
||||
{
|
||||
auto sql = format("SELECT password_hash FROM users HERE username = '{}' LIMIT 1;", username);
|
||||
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);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool initDB()
|
||||
{
|
||||
auto db = Database();
|
||||
|
||||
if (!db.open()){
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a tables
|
||||
const char* create_sql_chars = "CREATE TABLE IF NOT EXISTS users ("
|
||||
"id INTEGER PRIMARY KEY,"
|
||||
"username TEXT NOT NULL,"
|
||||
"password_hash TEXT NOT NULL,"
|
||||
"created_at DATETIME DEFAULT CURRENT_TIMESTAMP);";
|
||||
|
||||
if (!db.exec(create_sql_chars)){
|
||||
CROW_LOG_ERROR << "Failed to create users table";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool initLogin(crow::SimpleApp& app)
|
||||
{
|
||||
if (sodium_init() < 0) {
|
||||
CROW_LOG_ERROR << "Failed to Init Sodium";
|
||||
return false;
|
||||
}
|
||||
if(!initDB())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
CROW_ROUTE(app, "/login").methods("GET"_method)
|
||||
([](const crow::request& req){
|
||||
std::string csrf = random_string(32);
|
||||
// store CSRF in a temporary session cookie
|
||||
std::string session_id = random_string(32);
|
||||
sessions[session_id] = Session{"", csrf};
|
||||
|
||||
crow::response res;
|
||||
res.body = "<form hx-post='/login' hx-swap='none'>"
|
||||
"<input type='hidden' name='csrf_token' value='" + csrf + "'>"
|
||||
"<input name='username'>"
|
||||
"<input name='password' type='password'>"
|
||||
"<button>Login</button></form>";
|
||||
res.add_header("Set-Cookie", "session_id=" + session_id + "; HttpOnly; Secure; SameSite=Strict");
|
||||
return res;
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
bool ok = loginUser();
|
||||
|
||||
if (!ok) return crow::response(401, "Invalid credentials");
|
||||
|
||||
// regenerate session, mark as logged in
|
||||
sessions[session_id].user_id = generate_session_id(); // user ID
|
||||
|
||||
crow::response res;
|
||||
res.add_header("HX-Redirect", "/dashboard"); // htmx redirect
|
||||
return res;
|
||||
});
|
||||
}
|
||||
}
|
||||
11
src/login/login.hpp
Normal file
11
src/login/login.hpp
Normal file
@ -0,0 +1,11 @@
|
||||
#ifndef __LOGIN_H__
|
||||
#define __LOGIN_H__
|
||||
|
||||
#include <crow.h>
|
||||
|
||||
namespace login {
|
||||
|
||||
bool initLogin(crow::SimpleApp& app);
|
||||
|
||||
}
|
||||
#endif // __LOGIN_H__
|
||||
@ -7,6 +7,7 @@
|
||||
#include "htmx_helper.h"
|
||||
#include "systemd.h"
|
||||
#include "utils.hpp"
|
||||
#include "login.hpp"
|
||||
#include "ShadowrunApi.hpp"
|
||||
|
||||
using namespace std;
|
||||
@ -38,7 +39,7 @@ int main() {
|
||||
return crow::response(utils::loadFile("templates/" + file));
|
||||
});
|
||||
|
||||
// Static file redirector
|
||||
// Static file redirector
|
||||
CROW_ROUTE(app, "/redirect")
|
||||
([](const crow::request& req) {
|
||||
auto file_param = req.url_params.get("file");
|
||||
@ -64,7 +65,7 @@ int main() {
|
||||
auto body = get_body_name(req.body);
|
||||
if (!body.has_value())
|
||||
return crow::response(400);
|
||||
|
||||
|
||||
const string& serviceName = body.value();
|
||||
|
||||
auto opt_settings = AppSettings::loadAppSettings();
|
||||
@ -107,6 +108,7 @@ int main() {
|
||||
}
|
||||
|
||||
shadowrun::initApi(app);
|
||||
login::initLogin(app);
|
||||
|
||||
app.loglevel(crow::LogLevel::INFO);
|
||||
app.port(httpPort).multithreaded().run();
|
||||
|
||||
@ -5,19 +5,20 @@
|
||||
using namespace std;
|
||||
|
||||
HtmxShAttributeList::HtmxShAttributeList(const std::string& id, const vector<string>& itemList, std::map<std::string, std::string>& data){
|
||||
html += "<div class='section'>";
|
||||
html += format("<h2>{}</h2>", id);
|
||||
html += "<div class='grid'>";
|
||||
html += "<div class='grid_at'>";
|
||||
for (auto& item : itemList){
|
||||
string item_id = utils::to_id_format(format("{}_{}", id, item));
|
||||
auto value = data.contains(item_id) ? data[item_id] : "";
|
||||
html += format("<label>{}:<input type='text' name='{}' value='{}'></label>", item, item_id, value);
|
||||
html += format("<label>{}<input type='text' name='{}' value='{}'></label>", item, item_id, value);
|
||||
}
|
||||
html += "</div>";
|
||||
html += "</div></div>";
|
||||
}
|
||||
|
||||
HtmxShAttributeList::HtmxShAttributeList(const std::string& id, const std::vector<std::pair<std::string, std::string>>& itemValueList){
|
||||
html += format("<h2>{}</h2>", id);
|
||||
html += "<div class='grid'>";
|
||||
html += "<div class='grid_at'>";
|
||||
for (auto& item : itemValueList){
|
||||
string item_id = utils::to_id_format(format("{}_{}", id, item));
|
||||
html += format("<label>{}:<input type='text' name='{}' value='{}'></label>", item, item_id, item.second);
|
||||
|
||||
@ -16,10 +16,10 @@ static const vector<string> cCharacterInfo = {
|
||||
"Nuyen",
|
||||
"Lifestyle",
|
||||
"Total Karma",
|
||||
"Current Karma",
|
||||
"C. Karma",
|
||||
"Street Cred",
|
||||
"Notoriety",
|
||||
"Public Awareness"
|
||||
"Fame"
|
||||
};
|
||||
|
||||
static const vector<string> cAttributes = {
|
||||
@ -104,9 +104,10 @@ static const vector<string> genFormIds(){
|
||||
HtmxShCondition::genIds(vec, "Stun Condition", 12);
|
||||
HtmxShItemList::genIds(vec, "Contacts", cContactsParameters, 6);
|
||||
HtmxShItemList::genIds(vec, "Ranged Weapons", cRangedWeaponsParameters, 7);
|
||||
HtmxShItemList::genIds(vec, "Cyberware and Bioware", cImplantParameters, 9);
|
||||
HtmxShItemList::genIds(vec, "Cyberware and Bioware", cImplantParameters, 18);
|
||||
HtmxShItemList::genIds(vec, "Melee Weapons", cMeleeWeaponParameters, 7);
|
||||
HtmxShItemList::genIds(vec, "Armor", cArmorParamters , 3);
|
||||
vec.push_back("notes");
|
||||
|
||||
return vec;
|
||||
}
|
||||
@ -116,12 +117,11 @@ const std::vector<std::string> ShadowrunCharacterForm::m_checkboxIds = genCheckb
|
||||
|
||||
ShadowrunCharacterForm::ShadowrunCharacterForm(std::map<std::string, std::string>& data) {
|
||||
html.reserve(30000);
|
||||
|
||||
html += "<form hx-post='/api/shadowrun/submit-character' hx-target='#form-response' hx-swap='innerHTML'>";
|
||||
html += "<div style='display: grid; grid-template-columns: 1fr 1fr; gap: 2em;'>";
|
||||
|
||||
html += HtmxShAttributeList("Character Info", cCharacterInfo, data).htmx();
|
||||
html += HtmxShAttributeList("Attributes", cAttributes, data).htmx();
|
||||
|
||||
html += "<div style='display: grid; grid-template-columns: 1fr 1fr; gap: 2em;'>";
|
||||
html += HtmxShItemList("Active Skills", cSkillParameters, 8, data).htmx();
|
||||
html += HtmxShItemList("Knowledge Skills", cSkillParameters, 8, data).htmx();
|
||||
|
||||
@ -152,11 +152,16 @@ ShadowrunCharacterForm::ShadowrunCharacterForm(std::map<std::string, std::string
|
||||
html += HtmxShCondition("Stun Condition", 12, data).htmx();
|
||||
html += HtmxShItemList("Contacts", cContactsParameters, 6, data).htmx();
|
||||
html += HtmxShItemList("Ranged Weapons", cRangedWeaponsParameters, 7, data).htmx();
|
||||
html += HtmxShItemList("Cyberware and Bioware", cImplantParameters, 9, data).htmx();
|
||||
html += HtmxShItemList("Cyberware and Bioware", cImplantParameters, 18, data).htmx();
|
||||
html += HtmxShItemList("Melee Weapons", cMeleeWeaponParameters, 7, data).htmx();
|
||||
html += HtmxShItemList("Armor", cArmorParamters , 3, data).htmx();
|
||||
html += "</div>";
|
||||
|
||||
valueNotes = data.contains("notes") ? data["notes"] : "";
|
||||
html += format("<div style='margin-top: 1em;'><label for='notes'>Notes:</label>"
|
||||
"<textarea id='notes' name='notes' rows='100' style='width:100%; resize:vertical; overflow:auto;'>{}</textarea></div>", valueNotes);
|
||||
|
||||
|
||||
html += "<div style='text-align:center'>"
|
||||
"<button type='submit'>Submit</button>"
|
||||
"</div>"
|
||||
|
||||
@ -56,6 +56,13 @@
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<form hx-post="/login" hx-swap="none">
|
||||
<input type="hidden" name="csrf_token" value="{{csrf_token}}">
|
||||
<input name="email">
|
||||
<input name="password" type="password">
|
||||
<button>Login</button>
|
||||
</form>
|
||||
|
||||
<div class="app-panel"
|
||||
hx-get="/redirect?file=shadowrun.html"
|
||||
hx-trigger="click"
|
||||
|
||||
@ -27,26 +27,31 @@
|
||||
padding-bottom: 0.5em;
|
||||
}
|
||||
|
||||
.grid {
|
||||
.grid_at {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 1em;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
|
||||
.grid-2 {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
.grid-3 {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
}
|
||||
|
||||
.grid-4 {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: 2fr 1fr 1fr 1fr;
|
||||
}
|
||||
|
||||
.grid-6 {
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr;
|
||||
}
|
||||
|
||||
.skill-row {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user