-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.cpp
More file actions
executable file
·444 lines (384 loc) · 11.8 KB
/
db.cpp
File metadata and controls
executable file
·444 lines (384 loc) · 11.8 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#include "db.hpp"
#include <openssl/sha.h>
#include "config.hpp"
#define CATCHLOG(x) ERRLOG("Error: pgdb {}", x)
pgdb::pgdb() : conn(std::make_unique<pqxx::connection>(g_config->getDBConnString()))
{
try
{
if (!this->conn->is_open())
{
ERRLOG("Failed to connect to PostgreSQL.");
}
// if (this->conn->is_open()) {
// Connected to PostgreSQL successfully.
// } else {
// Failed to connect to PostgreSQL.
// }
}
catch (const std::exception &e)
{
CATCHLOG(e.what());
}
}
pgdb::~pgdb()
{
conn->disconnect();
}
std::string pgdb::hashPassword(const std::string &username, const std::string &password)
{
std::string saltedPassword = username + password;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, saltedPassword.c_str(), saltedPassword.length());
SHA256_Final(hash, &sha256);
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();
}
bool pgdb::createUser(const std::string &username, const std::string &pwd)
{
std::string token = "uzbek";
// if()
if(this->usernameExists(username) != req_state::not_found)
return false;
try
{
this->conn->prepare("create_user", R"(
INSERT INTO "users" (username, password)
VALUES ($1, $2)
)");
// Hash the password using the salt
std::string hashedPassword = hashPassword(username, pwd);
pqxx::work txn(*this->conn);
txn.exec_prepared("create_user", username, hashedPassword);
txn.commit();
LOG("User created successfully!");
return true;
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return false;
}
pgdb::req_state pgdb::usernameExists(const std::string &username)
{
try
{
pqxx::work txn(*this->conn);
conn->prepare("check_username", "SELECT COUNT(*) FROM \"users\" WHERE username = $1");
pqxx::result res = txn.exec_prepared("check_username", username);
return (res[0][0].as<int>() > 0) ? req_state::found : req_state::not_found;
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return req_state::error;
}
bool pgdb::auth(const std::string &username, const std::string &password)
{
try
{
pqxx::work txn(*conn);
std::string hashedPassword = hashPassword(username, password);
conn->prepare("authenticate_user", "SELECT COUNT(*) FROM \"users\" WHERE username = $1 AND password = $2");
pqxx::result res = txn.exec_prepared("authenticate_user", username, hashedPassword);
return res[0][0].as<int>() > 0;
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return false;
}
}
bool pgdb::auth(const std::string &token)
{
try
{
pqxx::work txn(*conn);
conn->prepare("check_token", "SELECT COUNT(*) FROM \"tokens\" WHERE token = $1");
pqxx::result res = txn.exec_prepared("check_token", token);
return (res[0][0].as<int>() > 0);
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return false;
}
}
int pgdb::userIDFromToken(const std::string &token)
{
try
{
pqxx::work txn(*conn);
conn->prepare("userid_token", "SELECT user_id FROM \"tokens\" WHERE token = $1");
pqxx::result res = txn.exec_prepared("userid_token", token);
return res[0][0].as<int>();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return -1;
}
}
std::string pgdb::usernameFromToken(const std::string &token)
{
int userID = userIDFromToken(token);
try
{
pqxx::work txn(*conn);
conn->prepare("username_token", "SELECT username FROM \"users\" WHERE id = $1");
pqxx::result res = txn.exec_prepared("username_token", userID);
return res[0][0].as<std::string>();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return {};
}
}
void pgdb::saveToken(const std::string &username, const std::string &token)
{
try
{
pqxx::work txn(*conn);
conn->prepare("find_user_id", "SELECT id FROM users WHERE username = $1");
pqxx::result res = txn.exec_prepared("find_user_id", username);
if (res.empty()) {
ERRLOG("Error: User not found.");
return;
}
int user_id = res[0][0].as<int>();
conn->prepare("insert_token", "INSERT INTO tokens (token, user_id, created_at) VALUES ($1, $2, CURRENT_TIMESTAMP)");
txn.exec_prepared("insert_token", token, user_id);
txn.commit();
LOG("Token saved successfully!");
} catch (const std::exception& e) {
CATCHLOG(e.what());
return;
}
}
int pgdb::createChat(int user1Id, int user2Id)
{
try
{
pqxx::work txn(*conn);
conn->prepare("create_chat", "INSERT INTO chats (user1_id, user2_id) VALUES ($1, $2)");
txn.exec_prepared("create_chat", user1Id, user2Id);
conn->prepare("get_last_chat_id", "SELECT id FROM chats ORDER BY id DESC LIMIT 1");
pqxx::result res = txn.exec_prepared("get_last_chat_id");
txn.commit();
return res[0][0].as<int>();
} catch (const std::exception& e) {
ERRLOG("Error: pgdb {}", e.what());
return -1;
}
}
void pgdb::storeMessage(int chatId, int senderId, const std::string &message, const std::string& filename)
{
try
{
pqxx::work txn(*conn);
conn->prepare("store_message", "INSERT INTO messages (chat_id, sender_id, message, imgfile) VALUES ($1, $2, $3, $4)");
txn.exec_prepared("store_message", chatId, senderId, message, filename);
txn.commit();
LOG("Message stored successfully!");
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}
std::vector<std::pair<std::string, bool>> pgdb::getChatMessages(int chatId, int userId)
{
std::vector<std::pair<std::string, bool>> messages = {};
try
{
pqxx::work txn(*conn);
conn->prepare("retrieve_messages", "SELECT message, sender_id FROM messages WHERE chat_id = $1 ORDER BY timestamp");
pqxx::result res = txn.exec_prepared("retrieve_messages", chatId);
for (const pqxx::row& row : res)
{
std::string message = row[0].as<std::string>();
int senderId = row[1].as<int>();
bool isLocal = (senderId == userId);
messages.emplace_back(message, isLocal);
}
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return messages;
}
std::vector<pgdb::messageBody> pgdb::getChatMessagesWithImgs(int chatId, int userId)
{
std::vector<pgdb::messageBody> messages = {};
try
{
pqxx::work txn(*conn);
conn->prepare("retrieve_messages", "SELECT message, sender_id, imgfile FROM messages WHERE chat_id = $1 ORDER BY timestamp");
pqxx::result res = txn.exec_prepared("retrieve_messages", chatId);
for (const pqxx::row& row : res)
{
std::string message = row[0].as<std::string>();
int senderId = row[1].as<int>();
std::string img = row[2].as<std::string>();
bool isLocal = (senderId == userId);
messages.emplace_back(pgdb::messageBody{message, isLocal, img});
}
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return messages;
}
std::vector<int> pgdb::getChatIdsForUser(int userId)
{
std::vector<int> chatIds = {};
try
{
pqxx::work txn(*conn);
conn->prepare("get_chat_ids_for_user", "SELECT id FROM chats WHERE user1_id = $1 OR user2_id = $1");
pqxx::result res = txn.exec_prepared("get_chat_ids_for_user", userId);
for (const pqxx::row& row : res)
{
chatIds.push_back(row[0].as<int>());
}
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return chatIds;
}
std::string pgdb::getFirstMessageOfChat(int chatId)
{
std::string message;
try
{
pqxx::work txn(*conn);
conn->prepare("get_first_message", "SELECT message FROM messages WHERE chat_id = $1 ORDER BY timestamp LIMIT 1");
pqxx::result res = txn.exec_prepared("get_first_message", chatId);
if (!res.empty())
{
message = res[0][0].as<std::string>();
}
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
return message;
}
void pgdb::removeChatsForUser(int userId)
{
try
{
pqxx::work txn(*conn);
conn->prepare("remove_chats_for_user", "DELETE FROM chats WHERE user1_id = $1 OR user2_id = $1");
txn.exec_prepared("remove_chats_for_user", userId);
txn.commit();
LOG("Chats removed successfully for user {}", userId);
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}
void pgdb::removeChatById(int chatId)
{
try
{
pqxx::work txn(*conn);
conn->prepare("remove_messages_by_chat_id", "DELETE FROM messages WHERE chat_id = $1");
txn.exec_prepared("remove_messages_by_chat_id", chatId);
conn->prepare("remove_chat_by_id", "DELETE FROM chats WHERE id = $1");
txn.exec_prepared("remove_chat_by_id", chatId);
txn.commit();
LOG("Chat and associated messages removed successfully with ID: {}", chatId);
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}
void pgdb::saveDoc(int userId, const std::string& docName, const std::string& docContent) {
try
{
pqxx::work txn(*conn);
conn->prepare("insert_doc", "INSERT INTO docs (user_id, doc_name, doc_content) VALUES ($1, $2, $3)");
txn.exec_prepared("insert_doc", userId, docName, docContent);
txn.commit();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}
std::string pgdb::getDoc(int userId, const std::string& docName) {
try
{
pqxx::work txn(*conn);
conn->prepare("get_doc", "SELECT doc_content FROM docs WHERE user_id = $1 AND doc_name = $2");
pqxx::result res = txn.exec_prepared("get_doc", userId, docName);
return res.empty() ? "" : res[0]["doc_content"].as<std::string>();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return "";
}
}
std::vector<std::string> pgdb::getUserDocs(int userId) {
try
{
pqxx::work txn(*conn);
conn->prepare("get_user_docs", "SELECT doc_name FROM docs WHERE user_id = $1");
pqxx::result res = txn.exec_prepared("get_user_docs", userId);
std::vector<std::string> docNames;
for (const auto& row : res)
{
docNames.push_back(row["doc_name"].as<std::string>());
}
return docNames;
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
return {};
}
}
void pgdb::deleteDoc(int userId, const std::string& docName) {
try
{
pqxx::work txn(*conn);
conn->prepare("delete_doc", "DELETE FROM docs WHERE user_id = $1 AND doc_name = $2");
txn.exec_prepared("delete_doc", userId, docName);
txn.commit();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}
void pgdb::deleteAllUserDocs(int userId) {
try
{
pqxx::work txn(*conn);
conn->prepare("delete_all_user_docs", "DELETE FROM docs WHERE user_id = $1");
txn.exec_prepared("delete_all_user_docs", userId);
txn.commit();
}
catch (const std::exception& e)
{
CATCHLOG(e.what());
}
}