-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrowdb.cpp
1850 lines (1535 loc) · 72.8 KB
/
crowdb.cpp
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <sqlite_modern_cpp.h>
#include <crow_all.h>
#include <expected>
#include <filesystem>
#include <random>
#include <expected>
#include <string>
#include <bitset>
namespace fs = std::filesystem;
const std::string IP = "";
const std::string PORT = "";
const std::string SMPT_EMAIL = "";
const std::string SMPT_URL = "";
const std::string SMPT_AND_PASS = "";
struct image_format {
std::string_view jpg = "\xFF\xD8\xFF";
std::string_view png = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
std::string_view gif = "\x47\x49\x46\x38";
std::string_view bmp = "\x42\x4D";
}image;
struct current_user {
bool logged_in;
uint32_t id;
std::string session_token;
std::string name;
bool verified;
std::string error_message;
};
std::string escape_string_decode(const std::string& str) {
std::string decoded_string;
for (size_t i = 0; i < str.length(); ++i) {
char c = str.at(i);
switch (c) {
case '%': {
if (i + 2 < str.length()) {
std::istringstream hex_stream(str.substr(i + 1, 2));
int32_t hex_value;
if (hex_stream >> std::hex >> hex_value) {
decoded_string += static_cast<char>(hex_value);
i += 2;
} else {
decoded_string += c;
}
}
break;
}
case '+':
decoded_string += ' ';
break;
default:
decoded_string += c;
break;
}
}
return decoded_string;
}
std::string escape_string_encode(const std::string& str) {
std::ostringstream encoded_string;
for (unsigned char c : str) {
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded_string << c;
} else if (c == ' ') {
encoded_string << '+';
} else {
encoded_string << '%' << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << (int)c;
}
}
return encoded_string.str();
}
bool is_symbol(const uint32_t codepoint) {
return
(codepoint >= 0x0021 && codepoint <= 0x002F) || // ! " # $ % & ' ( ) * + , - . /
(codepoint >= 0x003A && codepoint <= 0x0040) || // : ; < = > ? @
(codepoint >= 0x005B && codepoint <= 0x0060) || // [ \ ] ^ _ `
(codepoint >= 0x007B && codepoint <= 0x007E) || // { | } ~
(codepoint == 0x20AC) || // €
(codepoint >= 0x2000 && codepoint <= 0x206F) || // General Punctuation
(codepoint >= 0x2100 && codepoint <= 0x214F) || // Letterlike Symbols
(codepoint >= 0x2200 && codepoint <= 0x22FF) || // Mathematical Operators
(codepoint >= 0x2300 && codepoint <= 0x23FF) || // Miscellaneous Technical
(codepoint >= 0x2400 && codepoint <= 0x243F) || // Control Pictures
(codepoint >= 0x2440 && codepoint <= 0x245F) || // Optical Character Recognition
(codepoint >= 0x2500 && codepoint <= 0x257F) || // Box Drawing
(codepoint >= 0x2580 && codepoint <= 0x259F) || // Block Elements
(codepoint >= 0x25A0 && codepoint <= 0x25FF) || // Geometric Shapes
(codepoint >= 0x2600 && codepoint <= 0x26FF) || // Miscellaneous Symbols
(codepoint >= 0x2700 && codepoint <= 0x27BF) || // Dingbats
(codepoint >= 0x2B50 && codepoint <= 0x2B59) || // Miscellaneous Symbols and Pictographs
(codepoint >= 0x1F300 && codepoint <= 0x1F5FF) || // Miscellaneous Symbols and Pictographs
(codepoint >= 0x1F600 && codepoint <= 0x1F64F) || // Emoticons
(codepoint >= 0x1F680 && codepoint <= 0x1F6FF) || // Transport and Map Symbols
(codepoint >= 0x1F700 && codepoint <= 0x1F77F); // Alchemical Symbols
}
bool is_uppercase(const uint32_t codepoint) {
return
(codepoint >= 0x0041 && codepoint <= 0x005A) || // Basic Latin A-Z
(codepoint >= 0x00C0 && codepoint <= 0x00D6) || // Latin-1 Supplement À-Ö
(codepoint >= 0x00D8 && codepoint <= 0x00DE) || // Latin-1 Supplement Ø-Þ
(codepoint >= 0x0100 && codepoint <= 0x017F) || // Latin Extended-A
(codepoint >= 0x0180 && codepoint <= 0x024F) || // Latin Extended-B
(codepoint >= 0x0410 && codepoint <= 0x042F) || // Cyrillic А-Я
(codepoint >= 0x0391 && codepoint <= 0x03A9) || // Greek and Coptic Α-Ω
(codepoint >= 0x0531 && codepoint <= 0x0556) || // Armenian
(codepoint >= 0x05D0 && codepoint <= 0x05EA) || // Hebrew
(codepoint >= 0x0600 && codepoint <= 0x06C0) || // Arabic (some uppercase)
(codepoint >= 0x0780 && codepoint <= 0x07A5) || // Thaana
(codepoint >= 0x0905 && codepoint <= 0x0939) || // Devanagari
(codepoint >= 0x0985 && codepoint <= 0x0995) || // Bengali
(codepoint >= 0x0A05 && codepoint <= 0x0A0A) || // Gurmukhi
(codepoint >= 0x0A85 && codepoint <= 0x0A8D) || // Gujarati
(codepoint >= 0x0B05 && codepoint <= 0x0B0C) || // Oriya
(codepoint >= 0x0B85 && codepoint <= 0x0B9A) || // Tamil
(codepoint >= 0x0C05 && codepoint <= 0x0C0C) || // Telugu
(codepoint >= 0x0C85 && codepoint <= 0x0C8C) || // Kannada
(codepoint >= 0x0D05 && codepoint <= 0x0D0C) || // Malayalam
(codepoint >= 0x1000 && codepoint <= 0x102A) || // Myanmar
(codepoint >= 0x10A0 && codepoint <= 0x10C5) || // Georgian
(codepoint >= 0x1100 && codepoint <= 0x1159) || // Hangul Jamo
(codepoint >= 0xAC00 && codepoint <= 0xD7A3); // Hangul Syllables
}
bool is_pass_ok(const std::string& str) {
bool has_upper = false;
bool has_symbols = false;
bool has_num = false;
for (size_t i = 0; i < str.length(); ) {
uint32_t codepoint = 0;
if ((str.at(i) & 0x80) == 0x00) { // 1-byte UTF-8
codepoint = str.at(i);
++i;
} else if ((str.at(i) & 0xE0) == 0xC0) { // 2-byte UTF-8
codepoint = ((str.at(i) & 0x1F) << 6) | (str.at(i + 1) & 0x3F);
i += 2;
} else if ((str.at(i) & 0xF0) == 0xE0) { // 3-byte UTF-8
codepoint = ((str.at(i) & 0x0F) << 12) | ((str.at(i + 1) & 0x3F) << 6) | (str.at(i + 2) & 0x3F);
i += 3;
} else if ((str.at(i) & 0xF8) == 0xF0) { // 4-byte UTF-8
codepoint = ((str.at(i) & 0x07) << 18) | ((str.at(i + 1) & 0x3F) << 12) | ((str.at(i + 2) & 0x3F) << 6) | (str.at(i + 3) & 0x3F);
i += 4;
} else {
return false;
}
if (is_uppercase(codepoint)) {
has_upper = true;
} else if (is_symbol(codepoint)) {
has_symbols = true;
} else if (codepoint >= 0x0030 && codepoint <= 0x0039) {
has_num = true;
}
if (has_upper && has_num && has_symbols) {
return true;
}
}
return has_upper && has_num && has_symbols;
}
std::bitset<32> get_codepoint(const std::string& str, size_t& i) {
char32_t codepoint = 0;
unsigned char c = str.at(i);
if (c <= 0x7F) { // 1-byte UTF-8
codepoint = c;
++i;
} else if (c <= 0xDF) { // 2-byte UTF-8
codepoint = ((c & 0x1F) << 6) | (str.at(i + 1) & 0x3F);
i += 2;
} else if (c <= 0xEF) { // 3-byte UTF-8
codepoint = ((c & 0x0F) << 12) | ((str.at(i + 1) & 0x3F) << 6) | (str.at(i + 2) & 0x3F);
i += 3;
} else { // 4-byte UTF-8
codepoint = ((c & 0x07) << 18) | ((str.at(i + 1) & 0x3F) << 12) | ((str.at(i + 2) & 0x3F) << 6) | (str.at(i + 3) & 0x3F);
i += 4;
}
return std::bitset<32>(codepoint);
}
std::string codepoint_to_utf8(char32_t codepoint) {
std::string result;
if (codepoint <= 0x7F) {
result += static_cast<char>(codepoint);
} else if (codepoint <= 0x7FF) {
result += static_cast<char>(0xC0 | (codepoint >> 6));
result += static_cast<char>(0x80 | (codepoint & 0x3F));
} else if (codepoint <= 0xFFFF) {
result += static_cast<char>(0xE0 | (codepoint >> 12));
result += static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F));
result += static_cast<char>(0x80 | (codepoint & 0x3F));
} else {
result += static_cast<char>(0xF0 | (codepoint >> 18));
result += static_cast<char>(0x80 | ((codepoint >> 12) & 0x3F));
result += static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F));
result += static_cast<char>(0x80 | (codepoint & 0x3F));
}
return result;
}
std::string encrypt(const std::string& message, const std::string& key) {
size_t key_length = key.length();
std::string output;
size_t message_index = 0;
size_t key_index = 0;
while (message_index < message.length()) {
std::bitset<32> message_cp = get_codepoint(message, message_index);
std::bitset<32> key_cp = get_codepoint(key, key_index);
std::bitset<32> encrypted_cp = message_cp ^ key_cp;
char32_t encrypted_codepoint = static_cast<char32_t>(encrypted_cp.to_ulong());
output += codepoint_to_utf8(encrypted_codepoint);
key_index = (key_index + 1) % key_length;
}
return key + output;
}
std::string decrypt(const std::string& password) {
std::string key = password.substr(0, 20);
std::string encrypted_part = password.substr(20);
size_t key_length = key.length();
std::string output;
size_t message_index = 0;
size_t key_index = 0;
while (message_index < encrypted_part.length()) {
std::bitset<32> encrypted_cp = get_codepoint(encrypted_part, message_index);
std::bitset<32> key_cp = get_codepoint(key, key_index);
std::bitset<32> decrypted_cp = encrypted_cp ^ key_cp;
char32_t decrypted_codepoint = static_cast<char32_t>(decrypted_cp.to_ulong());
output += codepoint_to_utf8(decrypted_codepoint);
key_index = (key_index + 1) % key_length;
}
return output;
}
std::expected<uint32_t, std::string> u32_validator(const std::string& is_num) {
try {
uintmax_t num = std::stoul(is_num);
if (num <= UINT32_MAX) {
return static_cast<uint32_t>(num);
}
} catch (std::invalid_argument const& ex) {
return std::unexpected("NOT VALID U32");
}
return std::unexpected("NOT VALID U32");
}
current_user is_authorized(const crow::request& request, sqlite::database& db) {
std::string cookie = request.get_header_value("Cookie");
if (cookie.empty()) {
return {false, 0, "", "", false, "ERROR: Missing ID or NOT auth"};
}
std::string cookie_name = "user_id=";
size_t start = cookie.find(cookie_name);
if (start == std::string::npos) {
return {false, 0, "", "", false, "ERROR: Missing id in cookie"};
}
std::string id_from_cookie{cookie, start + cookie_name.size(), 4};
std::expected<uint8_t, std::string> id = u32_validator(id_from_cookie);
std::string retrieved_session_token;
std::string retrieved_user_name;
bool retrieved_verified;
uint32_t user_id;
if (id) {
user_id = id.value();
} else {
return {false, 0, "", "", false, "ERROR: Wrong ID format"};
}
cookie_name = "session_token=";
start = cookie.find(cookie_name);
if (start == std::string::npos) {
return {false, 0, "", "", false, "ERROR: Missing session token in cookie"};
}
std::string session_token{cookie, start + cookie_name.size(), 20};
db << "SELECT session_token FROM sessions WHERE session_token = ? AND user_id = ?;"
<< session_token << user_id
>> [&retrieved_session_token](const std::string& token) { retrieved_session_token = token; };
db << "SELECT name, verified FROM user WHERE _id = ?;"
<< user_id
>> [&](const std::string& name, bool verified) { retrieved_user_name = name; retrieved_verified = verified; };
if ((retrieved_session_token != session_token) || retrieved_session_token.empty()) {
return {false, 0, "", "", false, "ERROR: Not authorized"};
}
return {true, user_id, retrieved_session_token, retrieved_user_name, retrieved_verified, ""};
}
std::string session_token(size_t size) {
const std::string chars_range =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
"!@#$%^&*()-_=+[]{}|:,.<>?/";
std::random_device random_device;
std::mt19937 generator(random_device());
std::uniform_int_distribution<> distribution(0, chars_range.size() - 1);
std::string random_string;
for (uint32_t i = 0; i < size; ++i) {
random_string += chars_range[distribution(generator)];
}
return random_string;
}
int32_t send_verification_email(const std::string& email_to, const std::string& key) {
std::string link = "http://" + IP + ":" + PORT + "/verify/" + email_to + "/" + escape_string_encode(key);
std::ostringstream email_content;
email_content << "from: " << SMPT_EMAIL << "\n"
<< "To: " << email_to << "\n"
<< "Subject: Verify your email\n"
<< "Content-Type: text/html; charset=UTF-8\n"
<< "<html>\n"
<< "<body>\n"
<< "<h2><a href=\"" << link << "\">Click here to verify your email</a></h2>\n"
<< "</body>\n"
<< "</html>";
std::string command = R"(curl --url ")" + SMPT_URL + R"(" --ssl-reqd )"
R"(--mail-from ")" + SMPT_EMAIL + R"(" )"
R"(--mail-rcpt ")" + email_to + R"(" )"
R"(--upload-file - )" // Upload content from stdin
R"(--user ")" + SMPT_AND_PASS + R"(" )";
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command.data(), "w"), pclose);
if (!pipe) {
throw std::runtime_error("Failed to open pipe to curl.");
}
std::string content = email_content.str();
size_t written = fwrite(content.data(), sizeof(char), content.size(), pipe.get());
if (written != content.size()) {
throw std::runtime_error("Failed to write entire email content.");
}
int32_t result = pclose(pipe.release());
return result;
}
int32_t send_reset_email(const std::string& email_to, const std::string& key) {
std::string link = "http://" + IP + ":" + PORT + "/reset_password/" + email_to + "/" + escape_string_encode(key);
std::ostringstream email_content;
email_content << "from: " << SMPT_EMAIL << "\n"
<< "To: " << email_to << "\n"
<< "Subject: Reset password email\n"
<< "Content-Type: text/html; charset=UTF-8\n"
<< "<html>\n"
<< "<body>\n"
<< "<h2><a href=\"" << link << "\">Click here to reset</a></h2>\n"
<< "<p>Click the link to set your new password.</p>\n"
<< "</body>\n"
<< "</html>";
std::string command = R"(curl --url ")" + SMPT_URL + R"(" --ssl-reqd )"
R"(--mail-from ")" + SMPT_EMAIL + R"(" )"
R"(--mail-rcpt ")" + email_to + R"(" )"
R"(--upload-file - )" // Upload content from stdin
R"(--user ")" + SMPT_AND_PASS + R"(" )";
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command.data(), "w"), pclose);
if (!pipe) {
throw std::runtime_error("Failed to open pipe to curl.");
}
std::string content = email_content.str();
size_t written = fwrite(content.data(), sizeof(char), content.size(), pipe.get());
if (written != content.size()) {
throw std::runtime_error("Failed to write entire email content.");
}
int32_t result = pclose(pipe.release());
return result;
}
void create_database(sqlite::database& db) {
db << R"(CREATE TABLE IF NOT EXISTS user (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(25) NOT NULL,
email VARCHAR(25) UNIQUE NOT NULL,
password TEXT NOT NULL,
profile_picture TEXT,
verified BOOLEAN DEFAULT FALSE
);)";
db << R"(CREATE TABLE IF NOT EXISTS to_verify (
email VARCHAR(25) PRIMARY KEY NOT NULL,
key VARCHAR(25) NOT NULL
);)";
db << R"(
CREATE TABLE IF NOT EXISTS password_resets (
email TEXT PRIMARY KEY NOT NULL,
token TEXT NOT NULL,
expires_at DATETIME
);)";
db << R"(CREATE TABLE IF NOT EXISTS sessions (
user_id INTEGER NOT NULL,
session_token CHAR(20) NOT NULL,
PRIMARY KEY (user_id, session_token),
FOREIGN KEY(user_id) REFERENCES user(_id)
);)";
db << R"(CREATE TABLE IF NOT EXISTS posts (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
post_pic_url TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
time_edited DATETIME,
FOREIGN KEY(user_id) REFERENCES user(_id)
);)";
db << R"(CREATE TABLE IF NOT EXISTS replies (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
post_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
author TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
time_edited DATETIME,
parent_reply_id INTEGER,
FOREIGN KEY(post_id) REFERENCES posts(_id),
FOREIGN KEY(user_id) REFERENCES user(_id),
FOREIGN KEY(parent_reply_id) REFERENCES replies(_id)
);)";
db << R"(CREATE TABLE IF NOT EXISTS post_likes (
post_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (post_id, user_id),
FOREIGN KEY(post_id) REFERENCES posts(_id),
FOREIGN KEY(user_id) REFERENCES user(_id)
);)";
db << R"(CREATE TABLE IF NOT EXISTS reply_likes (
reply_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (reply_id, user_id),
FOREIGN KEY(reply_id) REFERENCES replies(_id),
FOREIGN KEY(user_id) REFERENCES user(_id)
);)";
}
int32_t main() {
crow::SimpleApp app;
sqlite::database db("dbfile.db");
create_database(db);
//email/token
CROW_ROUTE(app, "/reset_password/<string>/<string>")([&db](std::string email, const std::string& token) {
email = escape_string_decode(email);
uint32_t db_token = 0;
db << "SELECT COUNT(*) FROM password_resets WHERE (email = ? AND token = ?);"
<< email << token
>> db_token;
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue json_data;
std::vector<crow::json::wvalue> details;
if (db_token <= 0) {
json_data["error"] = "ERROR: Invalid details.";
return page.render(json_data);
}
page = crow::mustache::load("reset_password.html");
json_data["email"] = email;
json_data["token"] = token;
return page.render(json_data);
});
//email/token/new_password
CROW_ROUTE(app, "/reset_password/<string>/<string>/<string>").methods(crow::HTTPMethod::Post)([&db](std::string email, const std::string& token, std::string new_password) {
email = escape_string_decode(email);
new_password = escape_string_decode(new_password);
uint32_t db_token = 0;
db << "SELECT COUNT(*) FROM password_resets WHERE (email = ? AND token = ?);"
<< email << token
>> db_token;
if (db_token <= 0) {
return crow::response(400, "Invalid token");
}
if (!is_pass_ok(new_password) || new_password.size() < 8 || new_password.size() > 25) {
return crow::response(400, "ERROR: Password needs to be >= 8 <= 25 chars with a symbol, number, capital letter");
}
std::string key = session_token(20);
std::string sanitized_password;
std::ranges::for_each(new_password, [&sanitized_password](const char ch){ ((ch >= 0 && ch <= 31) || ch == 127)? "" : sanitized_password += ch ; });
std::string password = encrypt(sanitized_password, key);
db << "UPDATE user SET password = ? WHERE email = ?;"
<< password << email;
db << "DELETE FROM password_resets WHERE email = ?;"
<< email;
crow::response response(302, "/");
response.add_header("Location", "/");
return response;
});
CROW_ROUTE(app, "/forgot_password/<string>").methods(crow::HTTPMethod::Post)([&db](std::string email) {
email = escape_string_decode(email);
uint32_t user_email = 0;
db << "SELECT COUNT(*) FROM user WHERE email = ?;"
<< email
>> user_email;
if (user_email <= 0) {
return crow::response(400, "Email not found");
}
std::string reset_token = session_token(20);
db << "INSERT OR REPLACE INTO password_resets (email, token, expires_at) VALUES (?, ?, datetime('now', 'localtime'));"
<< email << escape_string_encode(reset_token);
send_reset_email(email, reset_token);
return crow::response(200, "Password reset email sent");
});
CROW_ROUTE(app, "/like").methods(crow::HTTPMethod::Post)([&db](const crow::request& request) {
crow::json::rvalue body = crow::json::load(request.body);
if (!body || !body.has("post_id")) {
return crow::response(400, "ERROR: Invalid JSON");
}
std::string post_id = body["post_id"].s();
if(post_id.empty()) {
return crow::response(400, "ERROR: Missing post_id");
}
current_user user = is_authorized(request, db);
if (!user.logged_in || !user.verified) {
return crow::response(400, "ERROR: Not authorized");
}
bool post_exists = false;
db << "SELECT 1 FROM posts WHERE _id = ?;"
<< post_id
>> [&post_exists]() { post_exists = true; };
if (post_id.empty() || !post_exists) {
return crow::response(400, "ERROR: Invalid post ID");
}
bool like_exists = false;
db << "SELECT 1 FROM post_likes WHERE post_id = ? AND user_id = ?;"
<< post_id << user.id
>> [&like_exists]() { like_exists = true; };
if (like_exists) {
db << "DELETE FROM post_likes WHERE post_id = ? AND user_id = ?;"
<< post_id << user.id;
return crow::response(200, "Like removed successfully");
} else {
db << "INSERT INTO post_likes (post_id, user_id) VALUES (?, ?);"
<< post_id << user.id;
return crow::response(200, "Like added successfully");
}
});
CROW_ROUTE(app, "/like_reply/<int>").methods(crow::HTTPMethod::Post)([&db](const crow::request& request, const int32_t reply_id) {
current_user user = is_authorized(request, db);
if (!user.logged_in || !user.verified) {
return crow::response(400, "ERROR: Not authorized");
}
bool reply_exists = false;
db << "SELECT 1 FROM replies WHERE _id = ?;"
<< reply_id
>> [&reply_exists]() { reply_exists = true; };
if (!reply_exists) {
return crow::response(400, "ERROR: Invalid reply ID");
}
bool like_exists = false;
db << "SELECT 1 FROM reply_likes WHERE reply_id = ? AND user_id = ?;"
<< reply_id << user.id
>> [&like_exists]() { like_exists = true; };
if (like_exists) {
db << "DELETE FROM reply_likes WHERE reply_id = ? AND user_id = ?;"
<< reply_id << user.id;
return crow::response(200, "Like removed successfully");
} else {
db << "INSERT INTO reply_likes (reply_id, user_id) VALUES (?, ?);"
<< reply_id << user.id;
return crow::response(200, "Like added successfully");
}
});
CROW_ROUTE(app, "/load_my_posts").methods(crow::HTTPMethod::Get)([&db](const crow::request& request) {
std::string page_param = (request.url_params.get("page"))? request.url_params.get("page") : "";
current_user user = is_authorized(request, db);
if (page_param.empty() || !user.logged_in) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
context["error"] = "Please log in!";
return page.render(context);
} else if (!user.verified) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
context["error"] = "Please verify your email first!";
return page.render(context);
}
std::expected<uint32_t, std::string> page_num_exp = u32_validator(page_param);
uint32_t page_num = 0;
if (page_num_exp) {
page_num = page_num_exp.value();
} else {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
return page.render(context);
}
crow::mustache::template_t page = crow::mustache::load("posts.html");
crow::json::wvalue json_data;
std::vector<crow::json::wvalue> posts;
db << R"(
SELECT
posts._id AS post_id,
posts.user_id AS author_id,
user.name AS author_name,
posts.content,
posts.post_pic_url,
posts.timestamp,
posts.time_edited,
COUNT(post_likes.user_id) AS like_count
FROM posts
LEFT JOIN post_likes ON posts._id = post_likes.post_id
LEFT JOIN user ON posts.user_id = user._id
WHERE user._id = ?
GROUP BY posts._id
ORDER BY posts.timestamp DESC
LIMIT 10 OFFSET ?;
)" << user.id << page_num * 10
>>[&](const uint32_t post_id, uint32_t user_id,
const std::string &author_name, const std::string &content,
const std::string &post_pic_url, const std::string ×tamp,
const std::string &time_edited, const uint32_t like_count) {
crow::json::wvalue post;
post["post_id"] = post_id;
post["user_id"] = user_id;
if (user_id == user.id) {
post["editable"] = post_id;
}
post["author_name"] = author_name;
post["content"] = content;
if (!post_pic_url.empty()) {
post["post_pic_url"] = post_pic_url;
}
post["timestamp"] = timestamp;
if (!time_edited.empty()) {
post["edited"] = time_edited;
}
post["like_count"] = like_count;
posts.emplace_back(post);
};
json_data["posts"] = std::move(posts);
return page.render(json_data);
});
CROW_ROUTE(app, "/load_users_posts/<int>").methods(crow::HTTPMethod::Get)([&db](const crow::request& request, const int32_t user_id) {
std::string page_param = (request.url_params.get("page"))? request.url_params.get("page") : "";
if (page_param.empty()) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
return page.render(context);
}
std::expected<uint32_t, std::string> page_num_exp = u32_validator(page_param);
uint32_t page_num = 0;
if (page_num_exp) {
page_num = page_num_exp.value();
} else {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
return page.render(context);
}
if (user_id < 0) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
return page.render(context);
}
crow::mustache::template_t page = crow::mustache::load("posts.html");
crow::json::wvalue json_data;
std::vector<crow::json::wvalue> posts;
current_user user = is_authorized(request, db);
db << R"(
SELECT
posts._id AS post_id,
posts.user_id AS author_id,
user.name AS author_name,
posts.content,
posts.post_pic_url,
posts.timestamp,
posts.time_edited,
COUNT(post_likes.user_id) AS like_count
FROM posts
LEFT JOIN post_likes ON posts._id = post_likes.post_id
LEFT JOIN user ON posts.user_id = user._id
WHERE author_id = ?
GROUP BY posts._id
ORDER BY posts.timestamp DESC
LIMIT 10 OFFSET ?;
)" << user_id << page_num * 10
>> [&](const uint32_t post_id, uint32_t user_id,
const std::string &author_name, const std::string &content,
const std::string &post_pic_url, const std::string ×tamp,
const std::string &time_edited, const uint32_t like_count) {
crow::json::wvalue post;
post["post_id"] = post_id;
post["user_id"] = user_id;
if (user_id == user.id) {
post["editable"] = post_id;
}
post["author_name"] = author_name;
post["content"] = content;
if (!post_pic_url.empty()) {
post["post_pic_url"] = post_pic_url;
}
post["timestamp"] = timestamp;
if (!time_edited.empty()) {
post["edited"] = time_edited;
}
post["like_count"] = like_count;
posts.emplace_back(post);
};
json_data["posts"] = std::move(posts);
return page.render(json_data);
});
CROW_ROUTE(app, "/home").methods(crow::HTTPMethod::Get)([&db](const crow::request& request) {
std::string page_param = (request.url_params.get("page"))? request.url_params.get("page") : "";
current_user user = is_authorized(request, db);
if (page_param.empty() || !user.logged_in) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
context["error"] = "Please log in!";
return page.render(context);
} else if (!user.verified) {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
context["error"] = "Please verify your email first!";
return page.render(context);
}
std::expected<uint32_t, std::string> page_num_exp = u32_validator(page_param);
uint32_t page_num = 0;
if (page_num_exp) {
page_num = page_num_exp.value();
} else {
crow::mustache::template_t page = crow::mustache::load("error.html");
crow::json::wvalue context;
return page.render(context);
}
crow::mustache::template_t page = crow::mustache::load("posts.html");
crow::json::wvalue json_data;
std::vector<crow::json::wvalue> posts;
db << R"(
SELECT
posts._id AS post_id,
posts.user_id AS author_id,
user.name AS author_name,
posts.content,
posts.post_pic_url,
posts.timestamp,
posts.time_edited,
COUNT(post_likes.user_id) AS like_count
FROM posts
LEFT JOIN post_likes ON posts._id = post_likes.post_id
LEFT JOIN user ON posts.user_id = user._id
GROUP BY posts._id
ORDER BY posts.timestamp DESC
LIMIT 10 OFFSET ?;
)" << page_num * 10 >>
[&](const uint32_t post_id, uint32_t user_id,
const std::string &author_name, const std::string &content,
const std::string &post_pic_url, const std::string ×tamp,
const std::string &time_edited, const uint32_t like_count) {
crow::json::wvalue post;
post["post_id"] = post_id;
post["user_id"] = user_id;
if (user_id == user.id) {
post["editable"] = post_id;
}
post["author_name"] = author_name;
post["content"] = content;
if (!post_pic_url.empty()) {
post["post_pic_url"] = post_pic_url;
}
post["timestamp"] = timestamp;
if (!time_edited.empty()) {
post["edited"] = time_edited;
}
post["like_count"] = like_count;
posts.emplace_back(post);
};
json_data["posts"] = std::move(posts);
return page.render(json_data);
});
CROW_ROUTE(app, "/submit_post").methods(crow::HTTPMethod::Post)([&db](const crow::request& request) {
current_user user = is_authorized(request, db);
if (!user.logged_in || !user.verified) {
return crow::response(400, "Not authorized");
}
crow::multipart::message file_message(request);
fs::path profile_picture_path;
std::string content = file_message.get_part_by_name("content").body;
std::string post_pic = file_message.get_part_by_name("post_pic").body;
if (!post_pic.empty()) {
const crow::multipart::part &part_value = file_message.get_part_by_name("post_pic");
if (part_value.body.empty()) {
return crow::response(400, "No file part found");
}
const crow::multipart::header &header = part_value.get_header_object("Content-Disposition");
if (header.value.empty()) {
return crow::response(400, "UPLOAD FAILED");
}
std::string prof_name = header.params.at("filename");
if (prof_name.empty()) {
return crow::response(400, "Missing filename");
}
fs::path upload_dir = fs::path("user_data") / fs::path(std::to_string(user.id)) / fs::path("post_pic");
std::error_code error;
if (!fs::exists(upload_dir, error)) {
fs::create_directories(upload_dir, error);
}
if (error) {
return crow::response(500, "Error creating user directory");
}
bool starts_img = false;
if (post_pic.starts_with(image.jpg)) {
starts_img = true;
if (!prof_name.ends_with(".jpg"))
prof_name += ".jpg";
} else if (post_pic.starts_with(image.png)) {
starts_img = true;
if (!prof_name.ends_with(".png"))
prof_name += ".png";
} else if (post_pic.starts_with(image.gif)) {
starts_img = true;
if (!prof_name.ends_with(".gif"))
prof_name += ".gif";
} else if (post_pic.starts_with(image.bmp)) {
starts_img = true;
if (!prof_name.ends_with(".bmp"))
prof_name += ".bmp";
}
if (starts_img) {
std::ofstream out_file(upload_dir / prof_name, std::ofstream::out | std::ios::binary);
out_file.write(post_pic.data(), post_pic.length());
profile_picture_path = upload_dir / prof_name;
} else {
return crow::response(400, "UPLOAD FAILED: Not an image file");
}
}
if (content.empty() && post_pic.empty()) {
return crow::response(400, "Post cannot be empty");
}
if (!post_pic.empty()) {
db << "INSERT INTO posts (user_id, content, post_pic_url) VALUES (?, ?, ?);"
<< user.id << content << profile_picture_path.string();
} else {
db << "INSERT INTO posts (user_id, content) VALUES (?, ?);"
<< user.id << content;
}
uint32_t post_id = 0;
db << "SELECT last_insert_rowid();"
>> [&post_id](const uint32_t id) {
post_id = id;
};
crow::json::wvalue response;
response["post_id"] = post_id;
response["user_id"] = user.id;
if(!post_pic.empty()) {
response["post_pic_url"] = profile_picture_path.string();
}
response["user_name"] = user.name;
return crow::response{response};
});
CROW_ROUTE(app, "/edit_post/<int>").methods(crow::HTTPMethod::Post)([&db](const crow::request& request, const int32_t post_id) {
current_user user = is_authorized(request, db);
if (!user.logged_in || !user.verified) {
return crow::response(400, "ERROR: Not authorized");
}
// Check if the post exists and if the user is the owner
bool is_owner = false;
db << "SELECT COUNT(*) FROM posts WHERE _id = ? AND user_id = ?;"
<< post_id << user.id
>> [&is_owner](const int32_t count) {
is_owner = (count > 0);
};
if (!is_owner) {
return crow::response(403, "ERROR: You are not allowed to edit this post");
}
crow::multipart::message file_message(request);
fs::path profile_picture_path;
std::string content = file_message.get_part_by_name("content").body;
std::string post_pic = file_message.get_part_by_name("post_pic").body;
std::string remove_pic = file_message.get_part_by_name("remove_picture").body;
if (!post_pic.empty()) {
const crow::multipart::part &part_value = file_message.get_part_by_name("post_pic");
std::error_code error;
std::string old_post_pic;
db << "SELECT post_pic_url FROM posts WHERE _id = ? AND user_id = ?;"
<< post_id << user.id
>> old_post_pic;
if (!old_post_pic.empty() && !post_pic.empty()) {
fs::remove(fs::path(old_post_pic), error);
}
if (error) {
return crow::response(500, "Error removing old post pic");
}