Files
shadowrun-server/source/login/login.cpp

82 lines
2.4 KiB
C++

#include "login.hpp"
#include "databasepool.h"
#include "SessionHandler.hpp"
namespace login
{
SessionHandler sessionHandler;
static 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;
}
static std::optional<std::string> loginUser(const std::string& username, const std::string& password)
{
auto user = getVerifiedUser(username, password);
if (user) {
return sessionHandler.createSession(user->id);
}
return {};
}
std::optional<crow::response> 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 {};
}
void initLogin(crow::App<crow::CORSHandler>& 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.body = "Logged in";
return res;
});
}
}