This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
#include "app/lidar_manager_app.hpp"
|
||||
|
||||
#include "auth/auth_service.hpp"
|
||||
#include "mission/mission_enqueue.hpp"
|
||||
#include "mission/mission_queue.hpp"
|
||||
#include "mission/mission_scheduler.hpp"
|
||||
@@ -41,9 +42,16 @@ int LidarManagerApp::run()
|
||||
ModbusTriggerService modbus(mission_store, enqueue_fn, 5502);
|
||||
MissionScheduler scheduler(mission_store, enqueue_fn);
|
||||
|
||||
AuthService auth(data_path_.parent_path() / "auth.json");
|
||||
|
||||
httplib::Server svr;
|
||||
svr.set_pre_routing_handler([&auth](const httplib::Request& req, httplib::Response& res) {
|
||||
return auth.preRoute(req, res);
|
||||
});
|
||||
|
||||
ApiServer api(repo, mission_queue, mission_store, modbus, scheduler);
|
||||
api.registerRoutes(svr);
|
||||
auth.registerRoutes(svr);
|
||||
StaticFileServer::mount(svr, www_root_);
|
||||
|
||||
std::fprintf(stderr,
|
||||
|
||||
776
src/auth/auth_service.cpp
Normal file
776
src/auth/auth_service.cpp
Normal file
@@ -0,0 +1,776 @@
|
||||
#include "auth/auth_service.hpp"
|
||||
|
||||
#include "util/crypto_util.hpp"
|
||||
#include "util/file_util.hpp"
|
||||
#include "util/http_util.hpp"
|
||||
#include "util/id_util.hpp"
|
||||
#include "util/string_util.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
|
||||
namespace lm {
|
||||
|
||||
thread_local const AuthSession* AuthService::tls_session_ = nullptr;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char* kSessionCookie = "lm_session";
|
||||
|
||||
nlohmann::json defaultPermissionsAllWrite()
|
||||
{
|
||||
return {{"dashboard", "write"},
|
||||
{"config", "write"},
|
||||
{"missions", "write"},
|
||||
{"integrations", "write"},
|
||||
{"users", "write"}};
|
||||
}
|
||||
|
||||
nlohmann::json defaultPermissionsUserGroup()
|
||||
{
|
||||
return {{"dashboard", "write"},
|
||||
{"config", "read"},
|
||||
{"missions", "read"},
|
||||
{"integrations", "read"},
|
||||
{"users", "none"}};
|
||||
}
|
||||
|
||||
nlohmann::json makeUser(const std::string& id,
|
||||
const std::string& username,
|
||||
const std::string& password,
|
||||
const std::string& group_id,
|
||||
const std::string& display_name)
|
||||
{
|
||||
const std::string salt = CryptoUtil::randomToken(16);
|
||||
return {{"id", id},
|
||||
{"username", username},
|
||||
{"display_name", display_name},
|
||||
{"group_id", group_id},
|
||||
{"password_salt", salt},
|
||||
{"password_hash", CryptoUtil::hashPassword(salt, password)},
|
||||
{"pin_salt", nullptr},
|
||||
{"pin_hash", nullptr},
|
||||
{"enabled", true}};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
AuthService::AuthService(std::filesystem::path store_path) : store_path_(std::move(store_path))
|
||||
{
|
||||
loadOrSeed();
|
||||
}
|
||||
|
||||
void AuthService::loadOrSeed()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
data_ = nlohmann::json::object();
|
||||
if (std::filesystem::exists(store_path_))
|
||||
{
|
||||
try
|
||||
{
|
||||
data_ = nlohmann::json::parse(FileUtil::readBinary(store_path_));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
data_ = nlohmann::json::object();
|
||||
}
|
||||
}
|
||||
|
||||
if (!data_.contains("version"))
|
||||
data_["version"] = 1;
|
||||
if (!data_.contains("groups") || !data_["groups"].is_array() || data_["groups"].empty())
|
||||
{
|
||||
data_["groups"] = nlohmann::json::array({
|
||||
{{"id", "group_distributors"},
|
||||
{"name", "Distributors"},
|
||||
{"allow_pin", false},
|
||||
{"permissions", defaultPermissionsAllWrite()}},
|
||||
{{"id", "group_administrators"},
|
||||
{"name", "Administrators"},
|
||||
{"allow_pin", false},
|
||||
{"permissions", defaultPermissionsAllWrite()}},
|
||||
{{"id", "group_users"},
|
||||
{"name", "Users"},
|
||||
{"allow_pin", true},
|
||||
{"permissions", defaultPermissionsUserGroup()}},
|
||||
});
|
||||
}
|
||||
if (!data_.contains("users") || !data_["users"].is_array() || data_["users"].empty())
|
||||
{
|
||||
data_["users"] = nlohmann::json::array({
|
||||
makeUser("user_distributor", "Distributor", "distributor", "group_distributors", "Distributor"),
|
||||
makeUser("user_admin", "Admin", "admin", "group_administrators", "Administrator"),
|
||||
makeUser("user_operator", "User", "user", "group_users", "Operator"),
|
||||
});
|
||||
}
|
||||
saveUnlocked();
|
||||
}
|
||||
|
||||
void AuthService::saveUnlocked()
|
||||
{
|
||||
const auto parent = store_path_.parent_path();
|
||||
if (!parent.empty())
|
||||
std::filesystem::create_directories(parent);
|
||||
FileUtil::writeBinaryAtomic(store_path_, data_.dump(2));
|
||||
}
|
||||
|
||||
const AuthSession* AuthService::currentSession() const
|
||||
{
|
||||
return tls_session_;
|
||||
}
|
||||
|
||||
std::string AuthService::extractToken(const httplib::Request& req) const
|
||||
{
|
||||
if (req.has_header("Cookie"))
|
||||
{
|
||||
const std::string cookie = req.get_header_value("Cookie");
|
||||
const std::string prefix = std::string(kSessionCookie) + "=";
|
||||
const auto pos = cookie.find(prefix);
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
const auto start = pos + prefix.size();
|
||||
const auto end = cookie.find(';', start);
|
||||
return cookie.substr(start, end == std::string::npos ? std::string::npos : end - start);
|
||||
}
|
||||
}
|
||||
if (req.has_header("Authorization"))
|
||||
{
|
||||
const std::string auth = req.get_header_value("Authorization");
|
||||
constexpr const char* kBearer = "Bearer ";
|
||||
if (auth.rfind(kBearer, 0) == 0)
|
||||
return auth.substr(std::strlen(kBearer));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool AuthService::isPublicApiPath(const std::string& path, const std::string& method)
|
||||
{
|
||||
if (method == "OPTIONS")
|
||||
return true;
|
||||
return path == "/api/health" || path == "/api/auth/login" || path == "/api/auth/logout";
|
||||
}
|
||||
|
||||
std::optional<std::string> AuthService::resourceForApiPath(const std::string& path)
|
||||
{
|
||||
if (path.rfind("/api/auth/", 0) == 0)
|
||||
return std::nullopt;
|
||||
if (path.rfind("/api/users", 0) == 0 || path.rfind("/api/user_groups", 0) == 0)
|
||||
return "users";
|
||||
if (path.rfind("/api/missions", 0) == 0 || path.rfind("/api/mission_queue", 0) == 0)
|
||||
return "missions";
|
||||
if (path.rfind("/api/triggers", 0) == 0 || path.rfind("/api/schedules", 0) == 0 ||
|
||||
path.rfind("/api/robots", 0) == 0 || path.rfind("/api/fleet", 0) == 0 ||
|
||||
path.rfind("/api/modbus", 0) == 0 || path.rfind("/api/v2.0.0/", 0) == 0)
|
||||
return "integrations";
|
||||
if (path.rfind("/api/", 0) == 0)
|
||||
return "config";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool AuthService::requiresWrite(const std::string& method)
|
||||
{
|
||||
return method != "GET" && method != "HEAD" && method != "OPTIONS";
|
||||
}
|
||||
|
||||
bool AuthService::permissionAllows(const nlohmann::json& perms,
|
||||
const std::string& resource,
|
||||
bool write) const
|
||||
{
|
||||
if (!perms.is_object() || !perms.contains(resource))
|
||||
return false;
|
||||
const std::string level = perms.value(resource, "none");
|
||||
if (level == "none")
|
||||
return false;
|
||||
if (write)
|
||||
return level == "write";
|
||||
return level == "read" || level == "write";
|
||||
}
|
||||
|
||||
const nlohmann::json* AuthService::findUserByIdUnlocked(const std::string& id) const
|
||||
{
|
||||
if (!data_.contains("users") || !data_["users"].is_array())
|
||||
return nullptr;
|
||||
for (const auto& u : data_["users"])
|
||||
{
|
||||
if (u.value("id", "") == id)
|
||||
return &u;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const nlohmann::json* AuthService::findUserByUsernameUnlocked(const std::string& username) const
|
||||
{
|
||||
if (!data_.contains("users") || !data_["users"].is_array())
|
||||
return nullptr;
|
||||
const std::string needle = StringUtil::toLower(StringUtil::trimCopy(username));
|
||||
for (const auto& u : data_["users"])
|
||||
{
|
||||
if (StringUtil::toLower(u.value("username", "")) == needle)
|
||||
return &u;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const nlohmann::json* AuthService::findGroupByIdUnlocked(const std::string& id) const
|
||||
{
|
||||
if (!data_.contains("groups") || !data_["groups"].is_array())
|
||||
return nullptr;
|
||||
for (const auto& g : data_["groups"])
|
||||
{
|
||||
if (g.value("id", "") == id)
|
||||
return &g;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool AuthService::verifyPasswordUnlocked(const nlohmann::json& user, const std::string& password) const
|
||||
{
|
||||
const std::string salt = user.value("password_salt", "");
|
||||
const std::string hash = user.value("password_hash", "");
|
||||
if (salt.empty() || hash.empty())
|
||||
return false;
|
||||
return CryptoUtil::hashPassword(salt, password) == hash;
|
||||
}
|
||||
|
||||
bool AuthService::verifyPinUnlocked(const nlohmann::json& user, const std::string& pin) const
|
||||
{
|
||||
if (pin.size() != 4 || !std::all_of(pin.begin(), pin.end(), ::isdigit))
|
||||
return false;
|
||||
if (user.value("pin_hash", nlohmann::json()).is_null())
|
||||
return false;
|
||||
const std::string salt = user.value("pin_salt", "");
|
||||
const std::string hash = user.value("pin_hash", "");
|
||||
if (salt.empty() || hash.empty())
|
||||
return false;
|
||||
return CryptoUtil::hashPin(salt, pin) == hash;
|
||||
}
|
||||
|
||||
bool AuthService::groupAllowsPinUnlocked(const std::string& group_id) const
|
||||
{
|
||||
const auto* group = findGroupByIdUnlocked(group_id);
|
||||
return group && group->value("allow_pin", false);
|
||||
}
|
||||
|
||||
std::optional<AuthSession> AuthService::buildSessionUnlocked(const nlohmann::json& user)
|
||||
{
|
||||
const auto* group = findGroupByIdUnlocked(user.value("group_id", ""));
|
||||
if (!group)
|
||||
return std::nullopt;
|
||||
|
||||
AuthSession session;
|
||||
session.token = CryptoUtil::randomToken(32);
|
||||
session.user_id = user.value("id", "");
|
||||
session.username = user.value("username", "");
|
||||
session.group_id = group->value("id", "");
|
||||
session.group_name = group->value("name", "");
|
||||
session.permissions = group->value("permissions", nlohmann::json::object());
|
||||
return session;
|
||||
}
|
||||
|
||||
nlohmann::json AuthService::userPublicView(const nlohmann::json& user, const nlohmann::json& group)
|
||||
{
|
||||
return {{"id", user.value("id", "")},
|
||||
{"username", user.value("username", "")},
|
||||
{"display_name", user.value("display_name", "")},
|
||||
{"group_id", user.value("group_id", "")},
|
||||
{"group_name", group.value("name", "")},
|
||||
{"permissions", group.value("permissions", nlohmann::json::object())},
|
||||
{"has_pin", !user.value("pin_hash", nlohmann::json()).is_null()}};
|
||||
}
|
||||
|
||||
std::optional<nlohmann::json> AuthService::loginPassword(const std::string& username,
|
||||
const std::string& password,
|
||||
std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
const auto* user = findUserByUsernameUnlocked(username);
|
||||
if (!user || !user->value("enabled", true))
|
||||
{
|
||||
err = "invalid credentials";
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!verifyPasswordUnlocked(*user, password))
|
||||
{
|
||||
err = "invalid credentials";
|
||||
return std::nullopt;
|
||||
}
|
||||
auto session = buildSessionUnlocked(*user);
|
||||
if (!session)
|
||||
{
|
||||
err = "invalid user group";
|
||||
return std::nullopt;
|
||||
}
|
||||
sessions_[session->token] = *session;
|
||||
const auto* group = findGroupByIdUnlocked(user->value("group_id", ""));
|
||||
return nlohmann::json{{"token", session->token},
|
||||
{"user", userPublicView(*user, group ? *group : nlohmann::json::object())}};
|
||||
}
|
||||
|
||||
std::optional<nlohmann::json> AuthService::loginPin(const std::string& pin, std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (pin.size() != 4 || !std::all_of(pin.begin(), pin.end(), ::isdigit))
|
||||
{
|
||||
err = "pin must be 4 digits";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const nlohmann::json* matched = nullptr;
|
||||
for (const auto& user : data_["users"])
|
||||
{
|
||||
if (!user.value("enabled", true))
|
||||
continue;
|
||||
if (!groupAllowsPinUnlocked(user.value("group_id", "")))
|
||||
continue;
|
||||
if (verifyPinUnlocked(user, pin))
|
||||
{
|
||||
matched = &user;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matched)
|
||||
{
|
||||
err = "invalid pin";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto session = buildSessionUnlocked(*matched);
|
||||
if (!session)
|
||||
{
|
||||
err = "invalid user group";
|
||||
return std::nullopt;
|
||||
}
|
||||
sessions_[session->token] = *session;
|
||||
const auto* group = findGroupByIdUnlocked(matched->value("group_id", ""));
|
||||
return nlohmann::json{{"token", session->token},
|
||||
{"user", userPublicView(*matched, group ? *group : nlohmann::json::object())}};
|
||||
}
|
||||
|
||||
bool AuthService::logout(const std::string& token)
|
||||
{
|
||||
if (token.empty())
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return sessions_.erase(token) > 0;
|
||||
}
|
||||
|
||||
std::optional<nlohmann::json> AuthService::sessionInfo(const std::string& token) const
|
||||
{
|
||||
if (token.empty())
|
||||
return std::nullopt;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
const auto it = sessions_.find(token);
|
||||
if (it == sessions_.end())
|
||||
return std::nullopt;
|
||||
const auto* user = findUserByIdUnlocked(it->second.user_id);
|
||||
if (!user)
|
||||
return std::nullopt;
|
||||
const auto* group = findGroupByIdUnlocked(user->value("group_id", ""));
|
||||
return userPublicView(*user, group ? *group : nlohmann::json::object());
|
||||
}
|
||||
|
||||
bool AuthService::changePassword(const std::string& token,
|
||||
const std::string& current_password,
|
||||
const std::string& new_password,
|
||||
std::string& err)
|
||||
{
|
||||
if (new_password.size() < 4)
|
||||
{
|
||||
err = "password too short";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
const auto it = sessions_.find(token);
|
||||
if (it == sessions_.end())
|
||||
{
|
||||
err = "not authenticated";
|
||||
return false;
|
||||
}
|
||||
|
||||
for (auto& user : data_["users"])
|
||||
{
|
||||
if (user.value("id", "") != it->second.user_id)
|
||||
continue;
|
||||
if (!verifyPasswordUnlocked(user, current_password))
|
||||
{
|
||||
err = "current password incorrect";
|
||||
return false;
|
||||
}
|
||||
const std::string salt = CryptoUtil::randomToken(16);
|
||||
user["password_salt"] = salt;
|
||||
user["password_hash"] = CryptoUtil::hashPassword(salt, new_password);
|
||||
saveUnlocked();
|
||||
return true;
|
||||
}
|
||||
|
||||
err = "user not found";
|
||||
return false;
|
||||
}
|
||||
|
||||
nlohmann::json AuthService::listGroups() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
nlohmann::json out = nlohmann::json::array();
|
||||
for (const auto& g : data_["groups"])
|
||||
{
|
||||
out.push_back({{"id", g.value("id", "")},
|
||||
{"name", g.value("name", "")},
|
||||
{"allow_pin", g.value("allow_pin", false)},
|
||||
{"permissions", g.value("permissions", nlohmann::json::object())}});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
nlohmann::json AuthService::listUsers() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
nlohmann::json out = nlohmann::json::array();
|
||||
for (const auto& u : data_["users"])
|
||||
{
|
||||
const auto* group = findGroupByIdUnlocked(u.value("group_id", ""));
|
||||
out.push_back(userPublicView(u, group ? *group : nlohmann::json::object()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<nlohmann::json> AuthService::createUser(const nlohmann::json& payload, std::string& err)
|
||||
{
|
||||
const std::string username = payload.value("username", "");
|
||||
const std::string password = payload.value("password", "");
|
||||
const std::string group_id = payload.value("group_id", "");
|
||||
if (username.empty() || password.empty() || group_id.empty())
|
||||
{
|
||||
err = "username, password and group_id required";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (findUserByUsernameUnlocked(username))
|
||||
{
|
||||
err = "username already exists";
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!findGroupByIdUnlocked(group_id))
|
||||
{
|
||||
err = "unknown group";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const std::string id = "user_" + IdUtil::newId();
|
||||
auto user = makeUser(id, username, password, group_id, payload.value("display_name", username));
|
||||
if (payload.contains("pin") && !payload["pin"].is_null())
|
||||
{
|
||||
const std::string pin = payload.value("pin", "");
|
||||
if (pin.size() != 4 || !std::all_of(pin.begin(), pin.end(), ::isdigit))
|
||||
{
|
||||
err = "pin must be 4 digits";
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!groupAllowsPinUnlocked(group_id))
|
||||
{
|
||||
err = "group does not allow pin";
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string pin_salt = CryptoUtil::randomToken(16);
|
||||
user["pin_salt"] = pin_salt;
|
||||
user["pin_hash"] = CryptoUtil::hashPin(pin_salt, pin);
|
||||
}
|
||||
|
||||
data_["users"].push_back(user);
|
||||
saveUnlocked();
|
||||
const auto* group = findGroupByIdUnlocked(group_id);
|
||||
return userPublicView(user, group ? *group : nlohmann::json::object());
|
||||
}
|
||||
|
||||
std::optional<nlohmann::json> AuthService::updateUser(const std::string& id,
|
||||
const nlohmann::json& payload,
|
||||
std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
for (auto& user : data_["users"])
|
||||
{
|
||||
if (user.value("id", "") != id)
|
||||
continue;
|
||||
|
||||
if (payload.contains("display_name"))
|
||||
user["display_name"] = payload["display_name"];
|
||||
if (payload.contains("enabled"))
|
||||
user["enabled"] = payload["enabled"];
|
||||
if (payload.contains("group_id"))
|
||||
{
|
||||
const std::string group_id = payload.value("group_id", "");
|
||||
if (!findGroupByIdUnlocked(group_id))
|
||||
{
|
||||
err = "unknown group";
|
||||
return std::nullopt;
|
||||
}
|
||||
user["group_id"] = group_id;
|
||||
}
|
||||
if (payload.contains("password") && payload["password"].is_string())
|
||||
{
|
||||
const std::string password = payload["password"];
|
||||
const std::string salt = CryptoUtil::randomToken(16);
|
||||
user["password_salt"] = salt;
|
||||
user["password_hash"] = CryptoUtil::hashPassword(salt, password);
|
||||
}
|
||||
if (payload.contains("pin"))
|
||||
{
|
||||
if (payload["pin"].is_null())
|
||||
{
|
||||
user["pin_salt"] = nullptr;
|
||||
user["pin_hash"] = nullptr;
|
||||
}
|
||||
else
|
||||
{
|
||||
const std::string pin = payload.value("pin", "");
|
||||
if (pin.size() != 4 || !std::all_of(pin.begin(), pin.end(), ::isdigit))
|
||||
{
|
||||
err = "pin must be 4 digits";
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!groupAllowsPinUnlocked(user.value("group_id", "")))
|
||||
{
|
||||
err = "group does not allow pin";
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string pin_salt = CryptoUtil::randomToken(16);
|
||||
user["pin_salt"] = pin_salt;
|
||||
user["pin_hash"] = CryptoUtil::hashPin(pin_salt, pin);
|
||||
}
|
||||
}
|
||||
|
||||
saveUnlocked();
|
||||
const auto* group = findGroupByIdUnlocked(user.value("group_id", ""));
|
||||
return userPublicView(user, group ? *group : nlohmann::json::object());
|
||||
}
|
||||
|
||||
err = "user not found";
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool AuthService::deleteUser(const std::string& id, std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto& users = data_["users"];
|
||||
const auto it = std::remove_if(users.begin(), users.end(), [&](const nlohmann::json& u) {
|
||||
return u.value("id", "") == id;
|
||||
});
|
||||
if (it == users.end())
|
||||
{
|
||||
err = "user not found";
|
||||
return false;
|
||||
}
|
||||
users.erase(it, users.end());
|
||||
saveUnlocked();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AuthService::authorizeApiRequest(const httplib::Request& req, httplib::Response& res)
|
||||
{
|
||||
if (const char* disabled = std::getenv("LM_AUTH_DISABLED"); disabled && std::string(disabled) == "1")
|
||||
return true;
|
||||
|
||||
const std::string token = extractToken(req);
|
||||
if (token.empty())
|
||||
{
|
||||
HttpUtil::jsonError(res, 401, "authentication required");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
const auto it = sessions_.find(token);
|
||||
if (it == sessions_.end())
|
||||
{
|
||||
HttpUtil::jsonError(res, 401, "invalid or expired session");
|
||||
return false;
|
||||
}
|
||||
|
||||
tls_session_ = &it->second;
|
||||
|
||||
const auto resource = resourceForApiPath(req.path);
|
||||
if (!resource)
|
||||
return true;
|
||||
|
||||
const bool write = requiresWrite(req.method);
|
||||
if (!permissionAllows(it->second.permissions, *resource, write))
|
||||
{
|
||||
HttpUtil::jsonError(res, 403, "insufficient permissions");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
httplib::Server::HandlerResponse AuthService::preRoute(const httplib::Request& req,
|
||||
httplib::Response& res)
|
||||
{
|
||||
tls_session_ = nullptr;
|
||||
|
||||
if (req.path.rfind("/api/", 0) != 0)
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
|
||||
if (isPublicApiPath(req.path, req.method))
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
|
||||
if (!authorizeApiRequest(req, res))
|
||||
{
|
||||
HttpUtil::addCors(res);
|
||||
return httplib::Server::HandlerResponse::Handled;
|
||||
}
|
||||
|
||||
return httplib::Server::HandlerResponse::Unhandled;
|
||||
}
|
||||
|
||||
void AuthService::registerRoutes(httplib::Server& svr)
|
||||
{
|
||||
svr.Post("/api/auth/login", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
nlohmann::json body;
|
||||
try
|
||||
{
|
||||
body = nlohmann::json::parse(req.body);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, "invalid json");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string err;
|
||||
std::optional<nlohmann::json> result;
|
||||
if (body.contains("pin"))
|
||||
result = loginPin(body.value("pin", ""), err);
|
||||
else
|
||||
result = loginPassword(body.value("username", ""), body.value("password", ""), err);
|
||||
|
||||
if (!result)
|
||||
{
|
||||
HttpUtil::jsonError(res, 401, err);
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string token = result->value("token", "");
|
||||
res.set_header("Set-Cookie",
|
||||
std::string(kSessionCookie) + "=" + token + "; Path=/; HttpOnly; SameSite=Lax");
|
||||
res.set_content(result->dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Post("/api/auth/logout", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
const std::string token = extractToken(req);
|
||||
logout(token);
|
||||
res.set_header("Set-Cookie", std::string(kSessionCookie) + "=; Path=/; HttpOnly; Max-Age=0");
|
||||
res.set_content(R"({"ok":true})", "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Get("/api/auth/me", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
const std::string token = extractToken(req);
|
||||
const auto info = sessionInfo(token);
|
||||
if (!info)
|
||||
{
|
||||
HttpUtil::jsonError(res, 401, "not authenticated");
|
||||
return;
|
||||
}
|
||||
nlohmann::json out = {{"user", *info}};
|
||||
res.set_content(out.dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Put("/api/auth/password", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
nlohmann::json body;
|
||||
try
|
||||
{
|
||||
body = nlohmann::json::parse(req.body);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, "invalid json");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string token = extractToken(req);
|
||||
std::string err;
|
||||
if (!changePassword(token,
|
||||
body.value("current_password", ""),
|
||||
body.value("new_password", ""),
|
||||
err))
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, err);
|
||||
return;
|
||||
}
|
||||
res.set_content(R"({"ok":true})", "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Get("/api/user_groups", [this](const httplib::Request&, httplib::Response& res) {
|
||||
nlohmann::json out = {{"groups", listGroups()}};
|
||||
res.set_content(out.dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Get("/api/users", [this](const httplib::Request&, httplib::Response& res) {
|
||||
nlohmann::json out = {{"users", listUsers()}};
|
||||
res.set_content(out.dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Post("/api/users", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
nlohmann::json body;
|
||||
try
|
||||
{
|
||||
body = nlohmann::json::parse(req.body);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, "invalid json");
|
||||
return;
|
||||
}
|
||||
std::string err;
|
||||
const auto user = createUser(body, err);
|
||||
if (!user)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, err);
|
||||
return;
|
||||
}
|
||||
res.status = 201;
|
||||
res.set_content(user->dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Put(R"(/api/users/([^/]+))", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
nlohmann::json body;
|
||||
try
|
||||
{
|
||||
body = nlohmann::json::parse(req.body);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, "invalid json");
|
||||
return;
|
||||
}
|
||||
std::string err;
|
||||
const auto user = updateUser(req.matches[1].str(), body, err);
|
||||
if (!user)
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, err);
|
||||
return;
|
||||
}
|
||||
res.set_content(user->dump(), "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
|
||||
svr.Delete(R"(/api/users/([^/]+))", [this](const httplib::Request& req, httplib::Response& res) {
|
||||
std::string err;
|
||||
if (!deleteUser(req.matches[1].str(), err))
|
||||
{
|
||||
HttpUtil::jsonError(res, 400, err);
|
||||
return;
|
||||
}
|
||||
res.set_content(R"({"ok":true})", "application/json; charset=utf-8");
|
||||
HttpUtil::addCors(res);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace lm
|
||||
79
src/auth/auth_service.hpp
Normal file
79
src/auth/auth_service.hpp
Normal file
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include <httplib.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace lm {
|
||||
|
||||
struct AuthSession
|
||||
{
|
||||
std::string token;
|
||||
std::string user_id;
|
||||
std::string username;
|
||||
std::string group_id;
|
||||
std::string group_name;
|
||||
nlohmann::json permissions;
|
||||
};
|
||||
|
||||
class AuthService
|
||||
{
|
||||
public:
|
||||
explicit AuthService(std::filesystem::path store_path);
|
||||
|
||||
httplib::Server::HandlerResponse preRoute(const httplib::Request& req, httplib::Response& res);
|
||||
|
||||
const AuthSession* currentSession() const;
|
||||
|
||||
std::optional<nlohmann::json> loginPassword(const std::string& username,
|
||||
const std::string& password,
|
||||
std::string& err);
|
||||
std::optional<nlohmann::json> loginPin(const std::string& pin, std::string& err);
|
||||
bool logout(const std::string& token);
|
||||
std::optional<nlohmann::json> sessionInfo(const std::string& token) const;
|
||||
bool changePassword(const std::string& token,
|
||||
const std::string& current_password,
|
||||
const std::string& new_password,
|
||||
std::string& err);
|
||||
|
||||
nlohmann::json listGroups() const;
|
||||
nlohmann::json listUsers() const;
|
||||
std::optional<nlohmann::json> createUser(const nlohmann::json& payload, std::string& err);
|
||||
std::optional<nlohmann::json> updateUser(const std::string& id,
|
||||
const nlohmann::json& payload,
|
||||
std::string& err);
|
||||
bool deleteUser(const std::string& id, std::string& err);
|
||||
|
||||
void registerRoutes(httplib::Server& svr);
|
||||
|
||||
private:
|
||||
std::filesystem::path store_path_;
|
||||
mutable std::mutex mu_;
|
||||
nlohmann::json data_;
|
||||
std::unordered_map<std::string, AuthSession> sessions_;
|
||||
thread_local static const AuthSession* tls_session_;
|
||||
|
||||
void loadOrSeed();
|
||||
void saveUnlocked();
|
||||
std::string extractToken(const httplib::Request& req) const;
|
||||
std::optional<AuthSession> buildSessionUnlocked(const nlohmann::json& user);
|
||||
bool permissionAllows(const nlohmann::json& perms, const std::string& resource, bool write) const;
|
||||
bool authorizeApiRequest(const httplib::Request& req, httplib::Response& res);
|
||||
static bool isPublicApiPath(const std::string& path, const std::string& method);
|
||||
static std::optional<std::string> resourceForApiPath(const std::string& path);
|
||||
static bool requiresWrite(const std::string& method);
|
||||
static nlohmann::json userPublicView(const nlohmann::json& user, const nlohmann::json& group);
|
||||
const nlohmann::json* findUserByIdUnlocked(const std::string& id) const;
|
||||
const nlohmann::json* findUserByUsernameUnlocked(const std::string& username) const;
|
||||
const nlohmann::json* findGroupByIdUnlocked(const std::string& id) const;
|
||||
bool verifyPasswordUnlocked(const nlohmann::json& user, const std::string& password) const;
|
||||
bool verifyPinUnlocked(const nlohmann::json& user, const std::string& pin) const;
|
||||
bool groupAllowsPinUnlocked(const std::string& group_id) const;
|
||||
};
|
||||
|
||||
} // namespace lm
|
||||
143
src/util/crypto_util.cpp
Normal file
143
src/util/crypto_util.cpp
Normal file
@@ -0,0 +1,143 @@
|
||||
#include "util/crypto_util.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace lm {
|
||||
namespace {
|
||||
|
||||
constexpr std::uint32_t rotr(std::uint32_t x, std::uint32_t n)
|
||||
{
|
||||
return (x >> n) | (x << (32 - n));
|
||||
}
|
||||
|
||||
void sha256Transform(std::array<std::uint32_t, 8>& state, const std::uint8_t block[64])
|
||||
{
|
||||
static const std::uint32_t k[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i)
|
||||
{
|
||||
w[i] = (static_cast<std::uint32_t>(block[i * 4]) << 24) |
|
||||
(static_cast<std::uint32_t>(block[i * 4 + 1]) << 16) |
|
||||
(static_cast<std::uint32_t>(block[i * 4 + 2]) << 8) |
|
||||
static_cast<std::uint32_t>(block[i * 4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 64; ++i)
|
||||
{
|
||||
const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
|
||||
std::uint32_t a = state[0];
|
||||
std::uint32_t b = state[1];
|
||||
std::uint32_t c = state[2];
|
||||
std::uint32_t d = state[3];
|
||||
std::uint32_t e = state[4];
|
||||
std::uint32_t f = state[5];
|
||||
std::uint32_t g = state[6];
|
||||
std::uint32_t h = state[7];
|
||||
|
||||
for (int i = 0; i < 64; ++i)
|
||||
{
|
||||
const std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
const std::uint32_t ch = (e & f) ^ ((~e) & g);
|
||||
const std::uint32_t temp1 = h + S1 + ch + k[i] + w[i];
|
||||
const std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
const std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
const std::uint32_t temp2 = S0 + maj;
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + temp1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1 + temp2;
|
||||
}
|
||||
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
state[5] += f;
|
||||
state[6] += g;
|
||||
state[7] += h;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string CryptoUtil::sha256Hex(const std::string& data)
|
||||
{
|
||||
std::array<std::uint32_t, 8> state = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
|
||||
const std::uint64_t bit_len = static_cast<std::uint64_t>(data.size()) * 8;
|
||||
std::vector<std::uint8_t> msg(data.begin(), data.end());
|
||||
msg.push_back(0x80);
|
||||
|
||||
while ((msg.size() % 64) != 56)
|
||||
msg.push_back(0x00);
|
||||
|
||||
for (int i = 7; i >= 0; --i)
|
||||
msg.push_back(static_cast<std::uint8_t>((bit_len >> (i * 8)) & 0xff));
|
||||
|
||||
for (std::size_t offset = 0; offset < msg.size(); offset += 64)
|
||||
sha256Transform(state, msg.data() + offset);
|
||||
|
||||
std::ostringstream oss;
|
||||
for (const auto v : state)
|
||||
oss << std::hex << std::setw(8) << std::setfill('0') << v;
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string CryptoUtil::randomToken(std::size_t bytes)
|
||||
{
|
||||
std::array<unsigned char, 64> buf{};
|
||||
const std::size_t n = bytes > buf.size() ? buf.size() : bytes;
|
||||
std::ifstream urandom("/dev/urandom", std::ios::binary);
|
||||
if (urandom)
|
||||
urandom.read(reinterpret_cast<char*>(buf.data()), static_cast<std::streamsize>(n));
|
||||
else
|
||||
{
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
std::uniform_int_distribution<int> dist(0, 255);
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
buf[i] = static_cast<unsigned char>(dist(gen));
|
||||
}
|
||||
|
||||
std::ostringstream oss;
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buf[i]);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string CryptoUtil::hashPassword(const std::string& salt, const std::string& password)
|
||||
{
|
||||
return sha256Hex(salt + ":" + password);
|
||||
}
|
||||
|
||||
std::string CryptoUtil::hashPin(const std::string& salt, const std::string& pin)
|
||||
{
|
||||
return sha256Hex(salt + ":pin:" + pin);
|
||||
}
|
||||
|
||||
} // namespace lm
|
||||
16
src/util/crypto_util.hpp
Normal file
16
src/util/crypto_util.hpp
Normal file
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lm {
|
||||
|
||||
class CryptoUtil
|
||||
{
|
||||
public:
|
||||
static std::string sha256Hex(const std::string& data);
|
||||
static std::string randomToken(std::size_t bytes = 32);
|
||||
static std::string hashPassword(const std::string& salt, const std::string& password);
|
||||
static std::string hashPin(const std::string& salt, const std::string& pin);
|
||||
};
|
||||
|
||||
} // namespace lm
|
||||
Reference in New Issue
Block a user