From d92947628b30c63615e20d45fb801d4c8cdec724 Mon Sep 17 00:00:00 2001 From: jinchao <383321154@qq.com> Date: Sun, 18 May 2025 09:54:59 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E4=BA=86=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E5=90=8E=E7=AB=AF=E5=BA=93=E7=9A=84Qt=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Login/CMakeLists.txt | 30 +- Login/Login_global.h | 16 +- Login/login.cpp | 622 ++++++++++++--------------- Login/test_encrypt/CMakeLists.txt | 25 -- Login/test_encrypt/test_password.cpp | 34 -- Release/database/XNSim.db | Bin 1224704 -> 1224704 bytes XNMonitorServer/CMakeLists.txt | 2 +- 7 files changed, 298 insertions(+), 431 deletions(-) delete mode 100644 Login/test_encrypt/CMakeLists.txt delete mode 100644 Login/test_encrypt/test_password.cpp diff --git a/Login/CMakeLists.txt b/Login/CMakeLists.txt index 84da6ba..c026545 100644 --- a/Login/CMakeLists.txt +++ b/Login/CMakeLists.txt @@ -2,9 +2,6 @@ cmake_minimum_required(VERSION 3.16) project(Login LANGUAGES CXX) -set(CMAKE_AUTOUIC ON) -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -15,30 +12,25 @@ else() message(FATAL_ERROR "Environment variable XNCore is not set.") endif() -find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Sql) -find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Sql) - -# 添加测试程序 -add_executable(test_password - test_encrypt/test_password.cpp -) +# 查找依赖包 +find_package(SQLite3 REQUIRED) +find_package(OpenSSL REQUIRED) +find_package(nlohmann_json 3.9.1 REQUIRED) add_library(Login SHARED - Login_global.h - login.cpp + Login_global.h + login.cpp ) # 添加头文件搜索路径 target_include_directories(Login PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_include_directories(test_password PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +# 链接依赖库 target_link_libraries(Login PRIVATE - Qt${QT_VERSION_MAJOR}::Core - Qt${QT_VERSION_MAJOR}::Sql) -target_link_libraries(test_password PRIVATE - Qt${QT_VERSION_MAJOR}::Core - Qt${QT_VERSION_MAJOR}::Sql - Login + SQLite::SQLite3 + OpenSSL::SSL + OpenSSL::Crypto + nlohmann_json::nlohmann_json ) target_compile_definitions(Login PRIVATE LOGIN_LIBRARY) diff --git a/Login/Login_global.h b/Login/Login_global.h index b0e8602..6665c2f 100644 --- a/Login/Login_global.h +++ b/Login/Login_global.h @@ -1,12 +1,18 @@ #ifndef LOGIN_GLOBAL_H #define LOGIN_GLOBAL_H -#include - -#if defined(LOGIN_LIBRARY) -# define LOGIN_EXPORT Q_DECL_EXPORT +#if defined(_WIN32) + #if defined(LOGIN_LIBRARY) + #define LOGIN_EXPORT __declspec(dllexport) + #else + #define LOGIN_EXPORT __declspec(dllimport) + #endif #else -# define LOGIN_EXPORT Q_DECL_IMPORT + #if defined(LOGIN_LIBRARY) + #define LOGIN_EXPORT __attribute__((visibility("default"))) + #else + #define LOGIN_EXPORT + #endif #endif #endif // LOGIN_GLOBAL_H diff --git a/Login/login.cpp b/Login/login.cpp index 8f7695c..39bff6a 100644 --- a/Login/login.cpp +++ b/Login/login.cpp @@ -1,257 +1,201 @@ #include "Login_global.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -// 全局变量用于跟踪是否已初始化 -static bool g_isInitialized = false; -static QCoreApplication *g_app = nullptr; +using json = nlohmann::json; +namespace fs = std::filesystem; -// 初始化Qt环境 -void initializeQt() -{ - if (!g_isInitialized) { - static int argc = 1; - static char *argv[] = {const_cast("Login")}; - g_app = new QCoreApplication(argc, argv); - g_isInitialized = true; - } -} - -// 清理Qt环境 -void cleanupQt() -{ - if (g_isInitialized && g_app) { - delete g_app; - g_app = nullptr; - g_isInitialized = false; - } -} - -QString generateSalt(const QString &username) +std::string generateSalt(const std::string& username) { // 使用用户名生成盐值 - // 可以根据需要添加额外的静态字符串来增加复杂度 return username + "XNSim_Salt_Key"; } -QString encryptPassword(const QString &password, const QString &salt) +std::string encryptPassword(const std::string& password, const std::string& salt) { // 将密码和盐值组合 - QByteArray saltedPassword = password.toUtf8(); - - // 如果提供了盐值,则添加到密码中 - if (!salt.isEmpty()) { - saltedPassword.append(salt.toUtf8()); + std::string saltedPassword = password; + if (!salt.empty()) { + saltedPassword += salt; } // 使用SHA-256算法对加盐密码进行加密 - QByteArray hashedPassword = - QCryptographicHash::hash(saltedPassword, QCryptographicHash::Sha256); - return hashedPassword.toHex(); + unsigned char hash[SHA256_DIGEST_LENGTH]; + EVP_MD_CTX* ctx = EVP_MD_CTX_new(); + EVP_DigestInit_ex(ctx, EVP_sha256(), NULL); + EVP_DigestUpdate(ctx, saltedPassword.c_str(), saltedPassword.length()); + EVP_DigestFinal_ex(ctx, hash, NULL); + EVP_MD_CTX_free(ctx); + + // 转换为十六进制字符串 + std::stringstream ss; + for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) { + ss << std::hex << std::setw(2) << std::setfill('0') << static_cast(hash[i]); + } + return ss.str(); } -extern "C" LOGIN_EXPORT int validateUser(const void *username_buffer, size_t username_length, - const void *password_buffer, size_t password_length) +extern "C" LOGIN_EXPORT int validateUser(const void* username_buffer, size_t username_length, + const void* password_buffer, size_t password_length) { try { - initializeQt(); + std::string username_str(static_cast(username_buffer), username_length); + std::string password_str(static_cast(password_buffer), password_length); - const char *username_data = static_cast(username_buffer); - const char *password_data = static_cast(password_buffer); - - QByteArray username_bytes(username_data, username_length); - QByteArray password_bytes(password_data, password_length); - - QString username_str = QString::fromUtf8(username_bytes); - QString password_str = QString::fromUtf8(password_bytes); - - if (username_str.isEmpty() || password_str.isEmpty()) { + if (username_str.empty() || password_str.empty()) { return -1; } - QString salt = generateSalt(username_str); - QString encryptedPassword = encryptPassword(password_str, salt); + std::string salt = generateSalt(username_str); + std::string encryptedPassword = encryptPassword(password_str, salt); - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - - if (xnCorePath.isEmpty()) { + // 获取环境变量 + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { + return -1; + } int userId = -1; - { - // 创建一个独立的作用域来管理数据库连接 - QString connectionName = - QString("userauth_%1").arg(QDateTime::currentMSecsSinceEpoch()); - { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); + sqlite3_stmt* stmt; + const char* queryStr = "SELECT * FROM users WHERE username = ? AND password = ?"; + + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_text(stmt, 1, username_str.c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 2, encryptedPassword.c_str(), -1, SQLITE_STATIC); - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); - return -1; - } - - QSqlQuery query(db); - QString queryStr = "SELECT * FROM users WHERE username = ? AND password = ?"; - query.prepare(queryStr); - query.addBindValue(username_str); - query.addBindValue(encryptedPassword); - - if (query.exec() && query.next()) { - userId = query.value(0).toInt(); - } - - query.finish(); - db.close(); + if (sqlite3_step(stmt) == SQLITE_ROW) { + userId = sqlite3_column_int(stmt, 0); } - QSqlDatabase::removeDatabase(connectionName); + + sqlite3_finalize(stmt); } + sqlite3_close(db); return userId; - } catch (const std::exception &) { + } catch (const std::exception&) { return -1; } } -extern "C" LOGIN_EXPORT const char *getUserInfo(int user_id) +extern "C" LOGIN_EXPORT const char* getUserInfo(int user_id) { try { - initializeQt(); - - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return nullptr; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; - char *result = nullptr; - { - // 创建一个独立的作用域来管理数据库连接 - QString connectionName = - QString("userinfo_%1").arg(QDateTime::currentMSecsSinceEpoch()); - { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); - return nullptr; - } - - QSqlQuery query(db); - query.prepare("SELECT * FROM users WHERE id = ?"); - query.addBindValue(user_id); - - if (query.exec() && query.next()) { - QJsonObject userInfo; - userInfo["id"] = query.value(0).toInt(); - userInfo["username"] = query.value(1).toString(); - userInfo["access_level"] = query.value(3).toInt(); - userInfo["full_name"] = query.value(4).toString(); - userInfo["phone"] = query.value(5).toString(); - userInfo["email"] = query.value(6).toString(); - userInfo["department"] = query.value(7).toString(); - userInfo["position"] = query.value(8).toString(); - - QJsonDocument doc(userInfo); - QByteArray jsonData = doc.toJson(QJsonDocument::Compact); - - result = new char[jsonData.size() + 1]; - std::strcpy(result, jsonData.constData()); - } - - query.finish(); - db.close(); - } - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { + return nullptr; } + char* result = nullptr; + sqlite3_stmt* stmt; + const char* queryStr = "SELECT * FROM users WHERE id = ?"; + + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_int(stmt, 1, user_id); + + if (sqlite3_step(stmt) == SQLITE_ROW) { + json userInfo; + userInfo["id"] = sqlite3_column_int(stmt, 0); + userInfo["username"] = reinterpret_cast(sqlite3_column_text(stmt, 1)); + userInfo["access_level"] = sqlite3_column_int(stmt, 3); + userInfo["full_name"] = reinterpret_cast(sqlite3_column_text(stmt, 4)); + userInfo["phone"] = reinterpret_cast(sqlite3_column_text(stmt, 5)); + userInfo["email"] = reinterpret_cast(sqlite3_column_text(stmt, 6)); + userInfo["department"] = reinterpret_cast(sqlite3_column_text(stmt, 7)); + userInfo["position"] = reinterpret_cast(sqlite3_column_text(stmt, 8)); + + std::string jsonData = userInfo.dump(); + result = new char[jsonData.size() + 1]; + std::strcpy(result, jsonData.c_str()); + } + + sqlite3_finalize(stmt); + } + + sqlite3_close(db); return result; - } catch (const std::exception &) { + } catch (const std::exception&) { return nullptr; } } -extern "C" LOGIN_EXPORT void freeUserInfo(const char *ptr) +extern "C" LOGIN_EXPORT void freeUserInfo(const char* ptr) { if (ptr) { delete[] ptr; } } -// 导出清理函数 extern "C" LOGIN_EXPORT void cleanup() { - cleanupQt(); } // 检查用户名是否已存在 int checkUsernameExists(const void *username_buffer, size_t username_length) { try { - initializeQt(); - const char *username_data = static_cast(username_buffer); - QByteArray username_bytes(username_data, username_length); - QString username_str = QString::fromUtf8(username_bytes); + std::string username_str(username_data, username_length); - if (username_str.isEmpty()) { + if (username_str.empty()) { return -1; } - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); - QString connectionName = QString("usercheck_%1").arg(QDateTime::currentMSecsSinceEpoch()); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + std::string connectionName = "usercheck_" + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); int result = -1; { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { return -1; } - QSqlQuery query(db); - query.prepare("SELECT COUNT(*) FROM users WHERE username = ?"); - query.addBindValue(username_str); + sqlite3_stmt* stmt; + const char* queryStr = "SELECT COUNT(*) FROM users WHERE username = ?"; - if (query.exec() && query.next()) { - result = query.value(0).toInt() > 0 ? 1 : 0; + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_text(stmt, 1, username_str.c_str(), -1, SQLITE_STATIC); + + if (sqlite3_step(stmt) == SQLITE_ROW) { + result = sqlite3_column_int(stmt, 0) > 0 ? 1 : 0; + } + + sqlite3_finalize(stmt); } - query.finish(); - db.close(); + sqlite3_close(db); } - QSqlDatabase::removeDatabase(connectionName); return result; } catch (const std::exception &) { @@ -265,25 +209,19 @@ extern "C" LOGIN_EXPORT int registerUser(const void *username_buffer, size_t use const void *userinfo_buffer, size_t userinfo_length) { try { - initializeQt(); - // 转换输入参数 const char *username_data = static_cast(username_buffer); const char *password_data = static_cast(password_buffer); const char *userinfo_data = static_cast(userinfo_buffer); - QByteArray username_bytes(username_data, username_length); - QByteArray password_bytes(password_data, password_length); - QByteArray userinfo_bytes(userinfo_data, userinfo_length); - - QString username_str = QString::fromUtf8(username_bytes); - QString password_str = QString::fromUtf8(password_bytes); + std::string username_str(username_data, username_length); + std::string password_str(password_data, password_length); // 验证用户名和密码非空 - if (username_str.isEmpty()) { + if (username_str.empty()) { return -4; // 用户名为空 } - if (password_str.isEmpty()) { + if (password_str.empty()) { return -5; // 密码为空 } @@ -293,61 +231,60 @@ extern "C" LOGIN_EXPORT int registerUser(const void *username_buffer, size_t use } // 解析用户信息JSON - QJsonDocument userInfoDoc = QJsonDocument::fromJson(userinfo_bytes); - if (!userInfoDoc.isObject()) { - return -3; // 无效的用户信息格式 + json userInfo; + try { + userInfo = json::parse(std::string(userinfo_data, userinfo_length)); + } catch (const json::parse_error&) { + return -3; // Invalid user info format } - QJsonObject userInfo = userInfoDoc.object(); // 验证权限级别 int accessLevel = 0; // 生成加密密码 - QString salt = generateSalt(username_str); - QString encryptedPassword = encryptPassword(password_str, salt); + std::string salt = generateSalt(username_str); + std::string encryptedPassword = encryptPassword(password_str, salt); // 连接数据库 - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); - QString connectionName = QString("userreg_%1").arg(QDateTime::currentMSecsSinceEpoch()); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + std::string connectionName = "userreg_" + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); int newUserId = -1; { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { return -1; } - QSqlQuery query(db); - query.prepare("INSERT INTO users (username, password, access_level, full_name, phone, " - "email, department, position) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); + sqlite3_stmt* stmt; + const char* queryStr = "INSERT INTO users (username, password, access_level, full_name, phone, " + "email, department, position) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; - query.addBindValue(username_str); - query.addBindValue(encryptedPassword); - query.addBindValue(accessLevel); - query.addBindValue(userInfo["full_name"].toString()); - query.addBindValue(userInfo["phone"].toString()); - query.addBindValue(userInfo["email"].toString()); - query.addBindValue(userInfo["department"].toString()); - query.addBindValue(userInfo["position"].toString()); + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_text(stmt, 1, username_str.c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 2, encryptedPassword.c_str(), -1, SQLITE_STATIC); + sqlite3_bind_int(stmt, 3, accessLevel); + sqlite3_bind_text(stmt, 4, userInfo["full_name"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 5, userInfo["phone"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 6, userInfo["email"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 7, userInfo["department"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 8, userInfo["position"].get().c_str(), -1, SQLITE_STATIC); - if (query.exec()) { - newUserId = query.lastInsertId().toInt(); + if (sqlite3_step(stmt) == SQLITE_DONE) { + newUserId = sqlite3_last_insert_rowid(db); + } + + sqlite3_finalize(stmt); } - query.finish(); - db.close(); + sqlite3_close(db); } - QSqlDatabase::removeDatabase(connectionName); return newUserId; } catch (const std::exception &) { @@ -362,85 +299,79 @@ extern "C" LOGIN_EXPORT int changePassword(int user_id, const void *old_password size_t new_password_length) { try { - initializeQt(); - const char *old_password_data = static_cast(old_password_buffer); const char *new_password_data = static_cast(new_password_buffer); - QByteArray old_password_bytes(old_password_data, old_password_length); - QByteArray new_password_bytes(new_password_data, new_password_length); + std::string old_password_str(old_password_data, old_password_length); + std::string new_password_str(new_password_data, new_password_length); - QString old_password_str = QString::fromUtf8(old_password_bytes); - QString new_password_str = QString::fromUtf8(new_password_bytes); - - if (old_password_str.isEmpty() || new_password_str.isEmpty()) { + if (old_password_str.empty() || new_password_str.empty()) { return -1; } - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); - QString connectionName = QString("changepwd_%1").arg(QDateTime::currentMSecsSinceEpoch()); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + std::string connectionName = "changepwd_" + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { return -1; } // 首先验证旧密码 - QSqlQuery query(db); - query.prepare("SELECT username, password FROM users WHERE id = ?"); - query.addBindValue(user_id); + sqlite3_stmt* stmt; + const char* queryStr = "SELECT username, password FROM users WHERE id = ?"; - if (!query.exec() || !query.next()) { - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return -2; // 用户不存在 + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_int(stmt, 1, user_id); + + if (sqlite3_step(stmt) == SQLITE_ROW) { + std::string username = reinterpret_cast(sqlite3_column_text(stmt, 0)); + std::string storedPassword = reinterpret_cast(sqlite3_column_text(stmt, 1)); + + // 验证旧密码 + std::string salt = generateSalt(username); + std::string encryptedOldPassword = encryptPassword(old_password_str, salt); + + if (encryptedOldPassword != storedPassword) { + sqlite3_finalize(stmt); + sqlite3_close(db); + return -3; // 旧密码错误 + } + + // 生成新的加密密码 + std::string encryptedNewPassword = encryptPassword(new_password_str, salt); + + // 更新密码 + sqlite3_finalize(stmt); + stmt = nullptr; + queryStr = "UPDATE users SET password = ? WHERE id = ?"; + + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_text(stmt, 1, encryptedNewPassword.c_str(), -1, SQLITE_STATIC); + sqlite3_bind_int(stmt, 2, user_id); + + if (sqlite3_step(stmt) == SQLITE_DONE) { + sqlite3_finalize(stmt); + sqlite3_close(db); + return 1; // 密码修改成功 + } + + sqlite3_finalize(stmt); + } + } } - QString username = query.value(0).toString(); - QString storedPassword = query.value(1).toString(); - - // 验证旧密码 - QString salt = generateSalt(username); - QString encryptedOldPassword = encryptPassword(old_password_str, salt); - - if (encryptedOldPassword != storedPassword) { - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return -3; // 旧密码错误 - } - - // 生成新的加密密码 - QString encryptedNewPassword = encryptPassword(new_password_str, salt); - - // 更新密码 - QSqlQuery updateQuery(db); - updateQuery.prepare("UPDATE users SET password = ? WHERE id = ?"); - updateQuery.addBindValue(encryptedNewPassword); - updateQuery.addBindValue(user_id); - - if (!updateQuery.exec()) { - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return -1; - } - - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return 1; // 密码修改成功 + sqlite3_close(db); } - } catch (const std::exception &) { + return -1; // Default error return + } catch (const std::exception&) { return -1; } } @@ -450,71 +381,70 @@ extern "C" LOGIN_EXPORT int updateUserInfo(int user_id, const void *userinfo_buf size_t userinfo_length) { try { - initializeQt(); - const char *userinfo_data = static_cast(userinfo_buffer); - QByteArray userinfo_bytes(userinfo_data, userinfo_length); + std::string userinfo_str(userinfo_data, userinfo_length); // 解析用户信息JSON - QJsonDocument userInfoDoc = QJsonDocument::fromJson(userinfo_bytes); - if (!userInfoDoc.isObject()) { - return -1; // 无效的用户信息格式 + json userInfo; + try { + userInfo = json::parse(userinfo_str); + } catch (const json::parse_error&) { + return -1; // Invalid user info format } - QJsonObject userInfo = userInfoDoc.object(); // 连接数据库 - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); - QString connectionName = QString("userupdate_%1").arg(QDateTime::currentMSecsSinceEpoch()); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + std::string connectionName = "userupdate_" + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); int result = -1; { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { return -1; } // 首先检查用户是否存在 - QSqlQuery checkQuery(db); - checkQuery.prepare("SELECT id FROM users WHERE id = ?"); - checkQuery.addBindValue(user_id); + sqlite3_stmt* stmt; + const char* checkQueryStr = "SELECT id FROM users WHERE id = ?"; - if (!checkQuery.exec() || !checkQuery.next()) { - checkQuery.finish(); - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return -2; // 用户不存在 - } - checkQuery.finish(); + if (sqlite3_prepare_v2(db, checkQueryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_int(stmt, 1, user_id); - QSqlQuery query(db); - query.prepare("UPDATE users SET full_name = ?, phone = ?, email = ?, department = ?, " - "position = ? " - "WHERE id = ?"); - - query.addBindValue(userInfo["full_name"].toString()); - query.addBindValue(userInfo["phone"].toString()); - query.addBindValue(userInfo["email"].toString()); - query.addBindValue(userInfo["department"].toString()); - query.addBindValue(userInfo["position"].toString()); - query.addBindValue(user_id); - - if (query.exec()) { - result = 1; // 更新成功 + if (sqlite3_step(stmt) == SQLITE_ROW) { + sqlite3_finalize(stmt); + sqlite3_close(db); + return -2; // 用户不存在 + } + sqlite3_finalize(stmt); } - query.finish(); - db.close(); + stmt = nullptr; + const char* queryStr = "UPDATE users SET full_name = ?, phone = ?, email = ?, department = ?, " + "position = ? " + "WHERE id = ?"; + + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_text(stmt, 1, userInfo["full_name"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 2, userInfo["phone"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 3, userInfo["email"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 4, userInfo["department"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 5, userInfo["position"].get().c_str(), -1, SQLITE_STATIC); + sqlite3_bind_int(stmt, 6, user_id); + + if (sqlite3_step(stmt) == SQLITE_DONE) { + result = 1; // 更新成功 + } + + sqlite3_finalize(stmt); + } + + sqlite3_close(db); } - QSqlDatabase::removeDatabase(connectionName); return result; } catch (const std::exception &) { @@ -526,60 +456,58 @@ extern "C" LOGIN_EXPORT int updateUserInfo(int user_id, const void *userinfo_buf extern "C" LOGIN_EXPORT int updateUserAccessLevel(int user_id, int access_level) { try { - initializeQt(); - // 验证权限级别 if (access_level < 0 || access_level >= 3) { return -3; // 无效的权限级别 } // 连接数据库 - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString xnCorePath = env.value("XNCore", ""); - if (xnCorePath.isEmpty()) { + const char* xnCorePath = std::getenv("XNCore"); + if (!xnCorePath) { return -1; } - QString dbPath = QDir(xnCorePath).filePath("database/XNSim.db"); - QString connectionName = QString("useraccess_%1").arg(QDateTime::currentMSecsSinceEpoch()); + fs::path dbPath = fs::path(xnCorePath) / "database" / "XNSim.db"; + std::string connectionName = "useraccess_" + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()); int result = -1; { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName); - db.setDatabaseName(dbPath); - - if (!db.open()) { - QSqlDatabase::removeDatabase(connectionName); + sqlite3* db; + if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) { return -1; } // 首先检查用户是否存在 - QSqlQuery checkQuery(db); - checkQuery.prepare("SELECT id FROM users WHERE id = ?"); - checkQuery.addBindValue(user_id); + sqlite3_stmt* stmt; + const char* checkQueryStr = "SELECT id FROM users WHERE id = ?"; - if (!checkQuery.exec() || !checkQuery.next()) { - checkQuery.finish(); - db.close(); - QSqlDatabase::removeDatabase(connectionName); - return -2; // 用户不存在 - } - checkQuery.finish(); + if (sqlite3_prepare_v2(db, checkQueryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_int(stmt, 1, user_id); - QSqlQuery query(db); - query.prepare("UPDATE users SET access_level = ? WHERE id = ?"); - - query.addBindValue(access_level); - query.addBindValue(user_id); - - if (query.exec()) { - result = 1; // 更新成功 + if (sqlite3_step(stmt) == SQLITE_ROW) { + sqlite3_finalize(stmt); + sqlite3_close(db); + return -2; // 用户不存在 + } + sqlite3_finalize(stmt); } - query.finish(); - db.close(); + stmt = nullptr; + const char* queryStr = "UPDATE users SET access_level = ? WHERE id = ?"; + + if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) { + sqlite3_bind_int(stmt, 1, access_level); + sqlite3_bind_int(stmt, 2, user_id); + + if (sqlite3_step(stmt) == SQLITE_DONE) { + result = 1; // 更新成功 + } + + sqlite3_finalize(stmt); + } + + sqlite3_close(db); } - QSqlDatabase::removeDatabase(connectionName); return result; } catch (const std::exception &) { diff --git a/Login/test_encrypt/CMakeLists.txt b/Login/test_encrypt/CMakeLists.txt deleted file mode 100644 index 4fddab4..0000000 --- a/Login/test_encrypt/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 3.10) -project(TestPasswordEncryption) - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -# 查找Qt包 -find_package(Qt6 COMPONENTS Core REQUIRED) - -# 设置Login库的路径 -link_directories(${CMAKE_SOURCE_DIR}/../build) - -# 添加头文件路径 -include_directories( - ${CMAKE_SOURCE_DIR}/.. - ${Qt6Core_INCLUDE_DIRS} -) - -add_executable(test_password test_password.cpp) -target_link_libraries(test_password - Qt6::Core - Login -) \ No newline at end of file diff --git a/Login/test_encrypt/test_password.cpp b/Login/test_encrypt/test_password.cpp deleted file mode 100644 index 687c173..0000000 --- a/Login/test_encrypt/test_password.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include -#include -#include "Login_global.h" - -// 声明login库中的验证函数 -extern "C" LOGIN_EXPORT int validateUser(const void *username_buffer, size_t username_length, - const void *password_buffer, size_t password_length); - -int main(int argc, char *argv[]) -{ - QCoreApplication a(argc, argv); - - // 测试用户名和密码 - QString username_qstr = QString("admin"); - QString password_qstr = QString("123456"); - - QByteArray username_utf8 = username_qstr.toUtf8(); - QByteArray password_utf8 = password_qstr.toUtf8(); - - qDebug() << "开始验证登录..."; - qDebug() << "用户名:" << username_qstr; - qDebug() << "密码:" << password_qstr; - - int accessLevel = validateUser(username_utf8.constData(), username_utf8.size(), - password_utf8.constData(), password_utf8.size()); - - if (accessLevel >= 0) { - qDebug() << "登录成功!用户权限级别:" << accessLevel; - } else { - qDebug() << "登录失败!" << accessLevel; - } - return 0; -} \ No newline at end of file diff --git a/Release/database/XNSim.db b/Release/database/XNSim.db index 6b4b3a74db2da8a92c647fbb68807112da24a6dd..a053ee37bbb30afdea3a11de4c9d398e811df774 100644 GIT binary patch delta 274 zcmZp8;MMTJYl1Xm$V3@u)({50vhIy33+$QY85T@tcd%nzFj-L`syw(J3i%Omgn0wnLWUkiEr0tMS~JP zE>31~MzDM2n~%h`ABkfGVkRJF24WT} delta 130 zcmZp8;MMTJYl1Xm@I)DB)?fxb?}-~z7T7b(F>+64cd(nRByemqx8qMfW;wnili34o zH!B)6@HHQaYd;dl2*gZ4%nZaVK+FonY(UHo#2i4(3B+7L%nigmK+Frod_c?(!~#Gp Lxcx|+kWC-}FZD7D diff --git a/XNMonitorServer/CMakeLists.txt b/XNMonitorServer/CMakeLists.txt index c5dae28..6fb1877 100644 --- a/XNMonitorServer/CMakeLists.txt +++ b/XNMonitorServer/CMakeLists.txt @@ -51,7 +51,7 @@ target_link_libraries(XNMonitorServer PRIVATE OpenSSL::Crypto ) -target_compile_definitions(XNMonitorServer PRIVATE LOGIN_LIBRARY) +target_compile_definitions(XNMonitorServer PRIVATE XNMONITOR_SERVER_LIBRARY) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${XNCore_PATH}" CACHE PATH "Install path prefix" FORCE)