-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.cpp
More file actions
192 lines (152 loc) · 6.18 KB
/
database.cpp
File metadata and controls
192 lines (152 loc) · 6.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include "database.h"
#include "CryptoUtil.h"
#include <spdlog/spdlog.h>
#include <filesystem>
Database::Database(const std::string& db_path) : db_path_(db_path), db_(nullptr) {
}
Database::~Database() {
if (db_) {
sqlite3_close(db_);
db_ = nullptr;
}
}
bool Database::Initialize() {
// 1. 确保数据库目录存在
std::filesystem::create_directories(std::filesystem::path(db_path_).parent_path());
// 2. 打开或创建数据库文件
int rc = sqlite3_open(db_path_.c_str(), &db_);
if (rc != SQLITE_OK) {
spdlog::error("[DB] 无法打开数据库 '{}': {}", db_path_, sqlite3_errmsg(db_));
// 尝试关闭句柄,防止资源泄漏
sqlite3_close(db_);
db_ = nullptr;
return false;
}
// 3. 启用WAL模式,高性能日志模式
ExecSQL("PRAGMA journal_mode=WAL;");
// 4. 设置同步级别,写WAL时,数据写入操作系统的页缓存后即返回
ExecSQL("PRAGMA synchronous=NORMAL;");
// 5. 创建用户表
const char* create_users_sql = R"SQL(
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
is_admin INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT (datetime('now','localtime'))
);
)SQL";
if (!ExecSQL(create_users_sql)) {
spdlog::error("[DB] 创建 users 表失败");
return false;
}
// 创建默认 root 管理员账户
if (!UserExists("root")) {
if (RegisterUser("root", "admin123", true)) {
spdlog::warn("[DB] 已创建默认 root 管理员账户,密码: admin123,请尽快修改!");
} else {
spdlog::error("[DB] 创建默认 root 账户失败");
return false;
}
}
spdlog::info("[DB] 数据库初始化完成: {}", db_path_);
return true;
}
// 用户注册
bool Database::RegisterUser(const std::string& username, const std::string& password, bool is_admin) {
// 1. 用户名唯一性
if (UserExists(username)) {
spdlog::warn("[DB] 注册失败:用户名 '{}' 已存在", username);
return false;
}
// 2. 向 users 表中插入包含 username(用户名)、password(密码)和 is_admin(管理员标识)三个字段的新数据
const char* sql = "INSERT INTO users (username, password, is_admin) VALUES (?, ?, ?);";
//定义的sql字符串只是一串普通文本,必须被编译并装载到这个stmt容器里,数据库引擎才能看懂并执行它
sqlite3_stmt* stmt = nullptr;
// 3. 编译SQL语句
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK) {
spdlog::error("[DB] 预处理语句失败 (RegisterUser): {}", sqlite3_errmsg(db_));
return false;
}
// 4. 传入的是原始密码,由CryptoUtil::HashPassword进行加盐哈希
std::string pwd_hash = CryptoUtil::HashPassword(username, password);
// 5. 参数绑定
sqlite3_bind_text(stmt, 1, username.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, pwd_hash.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int (stmt, 3, is_admin ? 1 : 0);
// 6. 释放预处理语句
rc = sqlite3_step(stmt);
// 7. 检查执行结果
if (rc != SQLITE_DONE) {
spdlog::error("[DB] 插入用户 '{}' 失败: {}", username, sqlite3_errmsg(db_));
return false;
}
spdlog::info("[DB] 用户注册成功: {} (admin={})", username, is_admin);
return true;
}
// 用户认证
bool Database::AuthenticateUser(const std::string& username, const std::string& password, UserInfo& out_user) {
// 1. 查询
const char* sql = "SELECT id, username, is_admin FROM users WHERE username=? AND password=? LIMIT 1;";
sqlite3_stmt* stmt = nullptr;
// 2. 编译SQL语句
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK) {
spdlog::error("[DB] 预处理语句失败 (AuthenticateUser): {}", sqlite3_errmsg(db_));
return false;
}
// 3. 计算密码哈希
std::string pwd_hash = CryptoUtil::HashPassword(username, password);
// 4. 绑定查询参数
sqlite3_bind_text(stmt, 1, username.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, pwd_hash.c_str(), -1, SQLITE_STATIC);
// 5. 执行查询
rc = sqlite3_step(stmt);
//sqlite3_column_int(col_index): col_index 从0开始,对应SELECT中的字段顺序
if (rc == SQLITE_ROW) {
out_user.id = sqlite3_column_int (stmt, 0);
out_user.username = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
//把当前行里某个特定列的整数值读取到变量中
out_user.is_admin = sqlite3_column_int(stmt, 2) != 0;
// 释放资源
sqlite3_finalize(stmt);
return true;
}
sqlite3_finalize(stmt);
return false;
}
// 检查用户是否存在
bool Database::UserExists(const std::string& username) {
// 1. 编写查询语句
const char* sql = "SELECT COUNT(*) FROM users WHERE username=?;";
sqlite3_stmt* stmt = nullptr;
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK) {
spdlog::error("[DB] 预处理语句失败 (UserExists): {}", sqlite3_errmsg(db_));
return false;
}
sqlite3_bind_text(stmt, 1, username.c_str(), -1, SQLITE_STATIC);
int count = 0;
// 执行查询
if (sqlite3_step(stmt) == SQLITE_ROW) {
//把当前行里某个特定列的整数值读取到变量中
count = sqlite3_column_int(stmt, 0);
}
sqlite3_finalize(stmt);
// count > 0 → 用户存在;count == 0 → 用户不存在
return count > 0;
}
// 执行无参数固定SQL
bool Database::ExecSQL(const char* sql) {
// errmsg 是 sqlite3_exec 的输出参数,接收错误消息指针
char* errmsg = nullptr;
// 自动执行(编译 -> 执行 -> 销毁)
int rc = sqlite3_exec(db_, sql, nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK) {
spdlog::error("[DB] SQL 执行失败: {}", errmsg ? errmsg : "未知错误");
sqlite3_free(errmsg);
return false;
}
return true;
}