移除了登录后端库的Qt依赖

This commit is contained in:
jinchao 2025-05-18 09:54:59 +08:00
parent 53e2d5c24f
commit d92947628b
7 changed files with 298 additions and 431 deletions

View File

@ -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,13 +12,10 @@ 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
@ -30,15 +24,13 @@ add_library(Login SHARED
#
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)

View File

@ -1,12 +1,18 @@
#ifndef LOGIN_GLOBAL_H
#define LOGIN_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(_WIN32)
#if defined(LOGIN_LIBRARY)
# define LOGIN_EXPORT Q_DECL_EXPORT
#define LOGIN_EXPORT __declspec(dllexport)
#else
# define LOGIN_EXPORT Q_DECL_IMPORT
#define LOGIN_EXPORT __declspec(dllimport)
#endif
#else
#if defined(LOGIN_LIBRARY)
#define LOGIN_EXPORT __attribute__((visibility("default")))
#else
#define LOGIN_EXPORT
#endif
#endif
#endif // LOGIN_GLOBAL_H

View File

@ -1,128 +1,93 @@
#include "Login_global.h"
#include <QString>
#include <QCryptographicHash>
#include <QProcessEnvironment>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QJsonObject>
#include <QJsonDocument>
#include <QCoreApplication>
#include <string>
#include <memory>
#include <QDateTime>
#include <chrono>
#include <filesystem>
#include <sqlite3.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <nlohmann/json.hpp>
#include <cstring>
#include <stdexcept>
#include <sstream>
#include <iomanip>
// 全局变量用于跟踪是否已初始化
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<char *>("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<int>(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)
{
try {
initializeQt();
std::string username_str(static_cast<const char*>(username_buffer), username_length);
std::string password_str(static_cast<const char*>(password_buffer), password_length);
const char *username_data = static_cast<const char *>(username_buffer);
const char *password_data = static_cast<const char *>(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 (!db.open()) {
QSqlDatabase::removeDatabase(connectionName);
return -1;
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 (sqlite3_step(stmt) == SQLITE_ROW) {
userId = sqlite3_column_int(stmt, 0);
}
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();
}
QSqlDatabase::removeDatabase(connectionName);
sqlite3_finalize(stmt);
}
sqlite3_close(db);
return userId;
} catch (const std::exception&) {
@ -133,59 +98,45 @@ extern "C" LOGIN_EXPORT int validateUser(const void *username_buffer, size_t use
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";
sqlite3* db;
if (sqlite3_open(dbPath.string().c_str(), &db) != SQLITE_OK) {
return nullptr;
}
char* result = nullptr;
{
// 创建一个独立的作用域来管理数据库连接
QString connectionName =
QString("userinfo_%1").arg(QDateTime::currentMSecsSinceEpoch());
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
db.setDatabaseName(dbPath);
sqlite3_stmt* stmt;
const char* queryStr = "SELECT * FROM users WHERE id = ?";
if (!db.open()) {
QSqlDatabase::removeDatabase(connectionName);
return nullptr;
}
if (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, user_id);
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);
if (sqlite3_step(stmt) == SQLITE_ROW) {
json userInfo;
userInfo["id"] = sqlite3_column_int(stmt, 0);
userInfo["username"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
userInfo["access_level"] = sqlite3_column_int(stmt, 3);
userInfo["full_name"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4));
userInfo["phone"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 5));
userInfo["email"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 6));
userInfo["department"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 7));
userInfo["position"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 8));
std::string jsonData = userInfo.dump();
result = new char[jsonData.size() + 1];
std::strcpy(result, jsonData.constData());
std::strcpy(result, jsonData.c_str());
}
query.finish();
db.close();
}
QSqlDatabase::removeDatabase(connectionName);
sqlite3_finalize(stmt);
}
sqlite3_close(db);
return result;
} catch (const std::exception&) {
@ -200,58 +151,51 @@ extern "C" LOGIN_EXPORT void freeUserInfo(const char *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<const char *>(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::milliseconds>(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;
}
query.finish();
db.close();
sqlite3_finalize(stmt);
}
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<const char *>(username_buffer);
const char *password_data = static_cast<const char *>(password_buffer);
const char *userinfo_data = static_cast<const char *>(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::milliseconds>(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, "
sqlite3_stmt* stmt;
const char* queryStr = "INSERT INTO users (username, password, access_level, full_name, phone, "
"email, department, position) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
"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<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 5, userInfo["phone"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 6, userInfo["email"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 7, userInfo["department"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 8, userInfo["position"].get<std::string>().c_str(), -1, SQLITE_STATIC);
if (query.exec()) {
newUserId = query.lastInsertId().toInt();
if (sqlite3_step(stmt) == SQLITE_DONE) {
newUserId = sqlite3_last_insert_rowid(db);
}
query.finish();
db.close();
sqlite3_finalize(stmt);
}
sqlite3_close(db);
}
QSqlDatabase::removeDatabase(connectionName);
return newUserId;
} catch (const std::exception &) {
@ -362,84 +299,78 @@ 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<const char *>(old_password_buffer);
const char *new_password_data = static_cast<const char *>(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::milliseconds>(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);
QString username = query.value(0).toString();
QString storedPassword = query.value(1).toString();
if (sqlite3_step(stmt) == SQLITE_ROW) {
std::string username = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
std::string storedPassword = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
// 验证旧密码
QString salt = generateSalt(username);
QString encryptedOldPassword = encryptPassword(old_password_str, salt);
std::string salt = generateSalt(username);
std::string encryptedOldPassword = encryptPassword(old_password_str, salt);
if (encryptedOldPassword != storedPassword) {
db.close();
QSqlDatabase::removeDatabase(connectionName);
sqlite3_finalize(stmt);
sqlite3_close(db);
return -3; // 旧密码错误
}
// 生成新的加密密码
QString encryptedNewPassword = encryptPassword(new_password_str, salt);
std::string encryptedNewPassword = encryptPassword(new_password_str, salt);
// 更新密码
QSqlQuery updateQuery(db);
updateQuery.prepare("UPDATE users SET password = ? WHERE id = ?");
updateQuery.addBindValue(encryptedNewPassword);
updateQuery.addBindValue(user_id);
sqlite3_finalize(stmt);
stmt = nullptr;
queryStr = "UPDATE users SET password = ? WHERE id = ?";
if (!updateQuery.exec()) {
db.close();
QSqlDatabase::removeDatabase(connectionName);
return -1;
}
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);
db.close();
QSqlDatabase::removeDatabase(connectionName);
if (sqlite3_step(stmt) == SQLITE_DONE) {
sqlite3_finalize(stmt);
sqlite3_close(db);
return 1; // 密码修改成功
}
sqlite3_finalize(stmt);
}
}
}
sqlite3_close(db);
}
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<const char *>(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::milliseconds>(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);
if (sqlite3_prepare_v2(db, checkQueryStr, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, user_id);
if (sqlite3_step(stmt) == SQLITE_ROW) {
sqlite3_finalize(stmt);
sqlite3_close(db);
return -2; // 用户不存在
}
checkQuery.finish();
sqlite3_finalize(stmt);
}
QSqlQuery query(db);
query.prepare("UPDATE users SET full_name = ?, phone = ?, email = ?, department = ?, "
stmt = nullptr;
const char* queryStr = "UPDATE users SET full_name = ?, phone = ?, email = ?, department = ?, "
"position = ? "
"WHERE id = ?");
"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 (sqlite3_prepare_v2(db, queryStr, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, userInfo["full_name"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, userInfo["phone"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, userInfo["email"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, userInfo["department"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 5, userInfo["position"].get<std::string>().c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 6, user_id);
if (query.exec()) {
if (sqlite3_step(stmt) == SQLITE_DONE) {
result = 1; // 更新成功
}
query.finish();
db.close();
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::milliseconds>(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);
if (sqlite3_prepare_v2(db, checkQueryStr, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, user_id);
if (sqlite3_step(stmt) == SQLITE_ROW) {
sqlite3_finalize(stmt);
sqlite3_close(db);
return -2; // 用户不存在
}
checkQuery.finish();
sqlite3_finalize(stmt);
}
QSqlQuery query(db);
query.prepare("UPDATE users SET access_level = ? WHERE id = ?");
stmt = nullptr;
const char* queryStr = "UPDATE users SET access_level = ? WHERE id = ?";
query.addBindValue(access_level);
query.addBindValue(user_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 (query.exec()) {
if (sqlite3_step(stmt) == SQLITE_DONE) {
result = 1; // 更新成功
}
query.finish();
db.close();
sqlite3_finalize(stmt);
}
sqlite3_close(db);
}
QSqlDatabase::removeDatabase(connectionName);
return result;
} catch (const std::exception &) {

View File

@ -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
)

View File

@ -1,34 +0,0 @@
#include <QCoreApplication>
#include <QDebug>
#include <string>
#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;
}

Binary file not shown.

View File

@ -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)