-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathdatabase.js
More file actions
3984 lines (3409 loc) · 127 KB
/
Copy pathdatabase.js
File metadata and controls
3984 lines (3409 loc) · 127 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
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
const Database = require('better-sqlite3');
const path = require('path');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const DatabaseSecurityLayer = require('./utils/database-security');
class AuctionDatabase {
constructor(dbPath = './auctions.db') {
this.dbPath = path.resolve(__dirname, dbPath);
this.db = new Database(this.dbPath);
this.securityLayer = new DatabaseSecurityLayer(this.db);
this.initializeSchema();
}
initializeSchema() {
// Enable foreign keys
this.db.pragma('foreign_keys = ON');
// Create users table
this.db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE,
hashed_password TEXT NOT NULL,
role TEXT DEFAULT 'user' CHECK(role IN ('user', 'admin', 'moderator')),
failed_login_attempts INTEGER DEFAULT 0,
last_failed_login DATETIME,
locked_until DATETIME,
is_active INTEGER DEFAULT 1,
email_verified INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// Create password reset tokens table
this.db.exec(`
CREATE TABLE IF NOT EXISTS password_reset_tokens (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token TEXT UNIQUE NOT NULL,
expires_at DATETIME NOT NULL,
used INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Create refresh tokens table for token rotation
this.db.exec(`
CREATE TABLE IF NOT EXISTS refresh_tokens (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token_hash TEXT NOT NULL,
device_info TEXT,
ip_address TEXT,
user_agent TEXT,
is_revoked INTEGER DEFAULT 0,
expires_at DATETIME NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_used_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Create user sessions table for multi-device support
this.db.exec(`
CREATE TABLE IF NOT EXISTS user_sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
refresh_token_id TEXT NOT NULL,
device_fingerprint TEXT,
is_active INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_activity_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (refresh_token_id) REFERENCES refresh_tokens(id) ON DELETE CASCADE
)
`);
// Create auctions table
this.db.exec(`
CREATE TABLE IF NOT EXISTS auctions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
starting_bid REAL NOT NULL,
current_highest_bid REAL DEFAULT 0,
end_time DATETIME NOT NULL,
creator_id TEXT NOT NULL,
status TEXT DEFAULT 'active' CHECK(status IN ('active', 'closed', 'cancelled')),
winner_id TEXT,
winning_bid_id TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (creator_id) REFERENCES users(id),
FOREIGN KEY (winner_id) REFERENCES users(id)
)
`);
// Create bids table
this.db.exec(`
CREATE TABLE IF NOT EXISTS bids (
id TEXT PRIMARY KEY,
auction_id TEXT NOT NULL,
bidder_id TEXT NOT NULL,
amount REAL NOT NULL,
encrypted_bid TEXT NOT NULL,
encrypted_iv TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
revealed INTEGER DEFAULT 0,
FOREIGN KEY (auction_id) REFERENCES auctions(id) ON DELETE CASCADE,
FOREIGN KEY (bidder_id) REFERENCES users(id)
)
`);
// Create auction views tracking table
this.db.exec(`
CREATE TABLE IF NOT EXISTS auction_views (
id TEXT PRIMARY KEY,
auction_id TEXT NOT NULL,
user_id TEXT,
ip_address TEXT,
user_agent TEXT,
viewed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (auction_id) REFERENCES auctions(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
)
`);
// Create admin-related tables
this.db.exec(`
CREATE TABLE IF NOT EXISTS system_logs (
id TEXT PRIMARY KEY,
level TEXT NOT NULL CHECK(level IN ('info', 'warning', 'error', 'critical')),
message TEXT NOT NULL,
user_id TEXT,
ip_address TEXT,
user_agent TEXT,
endpoint TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS revenue_tracking (
id TEXT PRIMARY KEY,
auction_id TEXT NOT NULL,
transaction_type TEXT NOT NULL CHECK(transaction_type IN ('auction_fee', 'commission', 'refund')),
amount REAL NOT NULL,
currency TEXT DEFAULT 'USD',
status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'completed', 'failed')),
transaction_hash TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (auction_id) REFERENCES auctions(id)
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS system_config (
id TEXT PRIMARY KEY,
key TEXT UNIQUE NOT NULL,
value TEXT NOT NULL,
description TEXT,
category TEXT DEFAULT 'general',
is_public INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS audit_logs (
id TEXT PRIMARY KEY,
admin_id TEXT NOT NULL,
action TEXT NOT NULL,
target_type TEXT NOT NULL CHECK(target_type IN ('user', 'auction', 'config', 'system')),
target_id TEXT,
old_values TEXT,
new_values TEXT,
ip_address TEXT,
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (admin_id) REFERENCES users(id)
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS security_alerts (
id TEXT PRIMARY KEY,
alert_type TEXT NOT NULL CHECK(alert_type IN ('suspicious_login', 'failed_attempts', 'unusual_activity', 'security_breach')),
severity TEXT NOT NULL CHECK(severity IN ('low', 'medium', 'high', 'critical')),
message TEXT NOT NULL,
user_id TEXT,
ip_address TEXT,
details TEXT,
status TEXT DEFAULT 'open' CHECK(status IN ('open', 'investigating', 'resolved', 'false_positive')),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
resolved_at DATETIME,
resolved_by TEXT,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (resolved_by) REFERENCES users(id)
)
`);
// Create social sharing analytics table
this.db.exec(`
CREATE TABLE IF NOT EXISTS social_shares (
id TEXT PRIMARY KEY,
auction_id TEXT NOT NULL,
platform TEXT NOT NULL CHECK(platform IN ('twitter', 'facebook', 'linkedin', 'whatsapp', 'telegram', 'email', 'copy_link')),
share_url TEXT NOT NULL,
custom_message TEXT,
image_generated INTEGER DEFAULT 0,
user_id TEXT,
ip_address TEXT,
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (auction_id) REFERENCES auctions(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
`);
// Create bookmark folders table
this.db.exec(`
CREATE TABLE IF NOT EXISTS bookmark_folders (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
user_id TEXT NOT NULL,
parent_folder_id TEXT,
color TEXT DEFAULT '#3b82f6',
icon TEXT DEFAULT 'folder',
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (parent_folder_id) REFERENCES bookmark_folders(id) ON DELETE CASCADE
)
`);
// Create bookmark tags table
this.db.exec(`
CREATE TABLE IF NOT EXISTS bookmark_tags (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
color TEXT DEFAULT '#10b981',
user_id TEXT NOT NULL,
usage_count INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(user_id, name)
)
`);
// Create bookmarks table
this.db.exec(`
CREATE TABLE IF NOT EXISTS bookmarks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
url TEXT NOT NULL,
type TEXT NOT NULL CHECK(type IN ('auction', 'user', 'search', 'custom')),
target_id TEXT,
user_id TEXT NOT NULL,
folder_id TEXT,
favicon TEXT,
thumbnail TEXT,
is_favorite INTEGER DEFAULT 0,
is_private INTEGER DEFAULT 0,
sort_order INTEGER DEFAULT 0,
metadata TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (folder_id) REFERENCES bookmark_folders(id) ON DELETE SET NULL
)
`);
// Create bookmark-tag relationship table
this.db.exec(`
CREATE TABLE IF NOT EXISTS bookmark_tag_relations (
bookmark_id TEXT NOT NULL,
tag_id TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (bookmark_id, tag_id),
FOREIGN KEY (bookmark_id) REFERENCES bookmarks(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES bookmark_tags(id) ON DELETE CASCADE
)
`);
// Create bookmark sync table for cross-device synchronization
this.db.exec(`
CREATE TABLE IF NOT EXISTS bookmark_sync (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
device_id TEXT NOT NULL,
bookmark_id TEXT NOT NULL,
action TEXT NOT NULL CHECK(action IN ('create', 'update', 'delete')),
sync_data TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
synced INTEGER DEFAULT 0,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (bookmark_id) REFERENCES bookmarks(id) ON DELETE CASCADE
)
`);
// Create share engagement tracking table
this.db.exec(`
CREATE TABLE IF NOT EXISTS share_engagement (
id TEXT PRIMARY KEY,
share_id TEXT NOT NULL,
engagement_type TEXT NOT NULL CHECK(engagement_type IN ('click', 'view', 'conversion')),
referrer_url TEXT,
ip_address TEXT,
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (share_id) REFERENCES social_shares(id)
)
`);
// Create watchlist table
this.db.exec(`
CREATE TABLE IF NOT EXISTS watchlist (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
auction_id TEXT NOT NULL,
notification_preferences TEXT DEFAULT '{"price_change": true, "ending_soon": true, "new_bid": true}',
price_threshold REAL,
notes TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (auction_id) REFERENCES auctions(id) ON DELETE CASCADE,
UNIQUE(user_id, auction_id)
)
`);
// Create watchlist notifications table
this.db.exec(`
CREATE TABLE IF NOT EXISTS watchlist_notifications (
id TEXT PRIMARY KEY,
watchlist_id TEXT NOT NULL,
notification_type TEXT NOT NULL CHECK(notification_type IN ('price_change', 'ending_soon', 'auction_ended', 'new_bid', 'outbid')),
title TEXT NOT NULL,
message TEXT NOT NULL,
is_read INTEGER DEFAULT 0,
is_sent INTEGER DEFAULT 0,
sent_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (watchlist_id) REFERENCES watchlist(id) ON DELETE CASCADE
)
`);
// Create watchlist sharing table
this.db.exec(`
CREATE TABLE IF NOT EXISTS watchlist_shares (
id TEXT PRIMARY KEY,
watchlist_owner_id TEXT NOT NULL,
share_token TEXT UNIQUE NOT NULL,
share_url TEXT NOT NULL,
is_public INTEGER DEFAULT 0,
expires_at DATETIME,
view_count INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (watchlist_owner_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Create watchlist activity log
this.db.exec(`
CREATE TABLE IF NOT EXISTS watchlist_activity (
id TEXT PRIMARY KEY,
watchlist_id TEXT NOT NULL,
activity_type TEXT NOT NULL CHECK(activity_type IN ('added', 'removed', 'price_alert_triggered', 'ending_soon_alert', 'notification_sent')),
details TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (watchlist_id) REFERENCES watchlist(id) ON DELETE CASCADE
)
`);
// Create indexes for better performance
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_auctions_status ON auctions(status);
CREATE INDEX IF NOT EXISTS idx_auctions_end_time ON auctions(end_time);
CREATE INDEX IF NOT EXISTS idx_bids_auction_id ON bids(auction_id);
CREATE INDEX IF NOT EXISTS idx_bids_bidder_id ON bids(bidder_id);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_token ON password_reset_tokens(token);
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user_id ON password_reset_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_system_logs_level ON system_logs(level);
CREATE INDEX IF NOT EXISTS idx_system_logs_created_at ON system_logs(created_at);
CREATE INDEX IF NOT EXISTS idx_revenue_tracking_status ON revenue_tracking(status);
CREATE INDEX IF NOT EXISTS idx_revenue_tracking_created_at ON revenue_tracking(created_at);
CREATE INDEX IF NOT EXISTS idx_audit_logs_admin_id ON audit_logs(admin_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON audit_logs(created_at);
CREATE INDEX IF NOT EXISTS idx_security_alerts_status ON security_alerts(status);
CREATE INDEX IF NOT EXISTS idx_security_alerts_severity ON security_alerts(severity);
CREATE INDEX IF NOT EXISTS idx_social_shares_auction_id ON social_shares(auction_id);
CREATE INDEX IF NOT EXISTS idx_social_shares_platform ON social_shares(platform);
CREATE INDEX IF NOT EXISTS idx_social_shares_created_at ON social_shares(created_at);
CREATE INDEX IF NOT EXISTS idx_share_engagement_share_id ON share_engagement(share_id);
CREATE INDEX IF NOT EXISTS idx_share_engagement_type ON share_engagement(engagement_type);
-- Bookmark-related indexes
CREATE INDEX IF NOT EXISTS idx_bookmark_folders_user_id ON bookmark_folders(user_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_folders_parent_id ON bookmark_folders(parent_folder_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_tags_user_id ON bookmark_tags(user_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_tags_name ON bookmark_tags(name);
CREATE INDEX IF NOT EXISTS idx_bookmarks_user_id ON bookmarks(user_id);
CREATE INDEX IF NOT EXISTS idx_bookmarks_folder_id ON bookmarks(folder_id);
CREATE INDEX IF NOT EXISTS idx_bookmarks_type ON bookmarks(type);
CREATE INDEX IF NOT EXISTS idx_bookmarks_target_id ON bookmarks(target_id);
CREATE INDEX IF NOT EXISTS idx_bookmarks_favorite ON bookmarks(is_favorite);
CREATE INDEX IF NOT EXISTS idx_bookmark_tag_relations_bookmark_id ON bookmark_tag_relations(bookmark_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_tag_relations_tag_id ON bookmark_tag_relations(tag_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_sync_user_id ON bookmark_sync(user_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_sync_device_id ON bookmark_sync(device_id);
CREATE INDEX IF NOT EXISTS idx_bookmark_sync_synced ON bookmark_sync(synced);
-- Watchlist-related indexes
CREATE INDEX IF NOT EXISTS idx_watchlist_user_id ON watchlist(user_id);
CREATE INDEX IF NOT EXISTS idx_watchlist_auction_id ON watchlist(auction_id);
CREATE INDEX IF NOT EXISTS idx_watchlist_created_at ON watchlist(created_at);
CREATE INDEX IF NOT EXISTS idx_watchlist_notifications_watchlist_id ON watchlist_notifications(watchlist_id);
CREATE INDEX IF NOT EXISTS idx_watchlist_notifications_type ON watchlist_notifications(notification_type);
CREATE INDEX IF NOT EXISTS idx_watchlist_notifications_is_read ON watchlist_notifications(is_read);
CREATE INDEX IF NOT EXISTS idx_watchlist_shares_owner_id ON watchlist_shares(watchlist_owner_id);
CREATE INDEX IF NOT EXISTS idx_watchlist_shares_token ON watchlist_shares(share_token);
CREATE INDEX IF NOT EXISTS idx_watchlist_activity_watchlist_id ON watchlist_activity(watchlist_id);
CREATE INDEX IF NOT EXISTS idx_watchlist_activity_type ON watchlist_activity(activity_type);
`);
// Create chat-related tables
this.db.exec(`
CREATE TABLE IF NOT EXISTS chat_rooms (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK(type IN ('auction', 'global', 'private')),
auction_id TEXT,
created_by TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (created_by) REFERENCES users(id),
FOREIGN KEY (auction_id) REFERENCES auctions(id) ON DELETE CASCADE
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS chat_participants (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT DEFAULT 'participant' CHECK(role IN ('admin', 'moderator', 'participant')),
joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_read_at DATETIME,
is_online INTEGER DEFAULT 0,
FOREIGN KEY (room_id) REFERENCES chat_rooms(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(room_id, user_id)
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS chat_messages (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL,
user_id TEXT NOT NULL,
content TEXT NOT NULL,
message_type TEXT DEFAULT 'text' CHECK(message_type IN ('text', 'file', 'emoji', 'system')),
file_url TEXT,
file_name TEXT,
file_size INTEGER,
reply_to_id TEXT,
is_edited INTEGER DEFAULT 0,
edited_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (room_id) REFERENCES chat_rooms(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (reply_to_id) REFERENCES chat_messages(id) ON DELETE SET NULL
)
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS chat_typing_indicators (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL,
user_id TEXT NOT NULL,
is_typing INTEGER DEFAULT 1,
started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME DEFAULT (datetime('now', '+10 seconds')),
FOREIGN KEY (room_id) REFERENCES chat_rooms(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Create chat-related indexes
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_chat_rooms_type ON chat_rooms(type);
CREATE INDEX IF NOT EXISTS idx_chat_rooms_auction_id ON chat_rooms(auction_id);
CREATE INDEX IF NOT EXISTS idx_chat_rooms_created_by ON chat_rooms(created_by);
CREATE INDEX IF NOT EXISTS idx_chat_participants_room_id ON chat_participants(room_id);
CREATE INDEX IF NOT EXISTS idx_chat_participants_user_id ON chat_participants(user_id);
CREATE INDEX IF NOT EXISTS idx_chat_participants_is_online ON chat_participants(is_online);
CREATE INDEX IF NOT EXISTS idx_chat_messages_room_id ON chat_messages(room_id);
CREATE INDEX IF NOT EXISTS idx_chat_messages_user_id ON chat_messages(user_id);
CREATE INDEX IF NOT EXISTS idx_chat_messages_created_at ON chat_messages(created_at);
CREATE INDEX IF NOT EXISTS idx_chat_messages_reply_to_id ON chat_messages(reply_to_id);
CREATE INDEX IF NOT EXISTS idx_chat_typing_room_id ON chat_typing_indicators(room_id);
CREATE INDEX IF NOT EXISTS idx_chat_typing_user_id ON chat_typing_indicators(user_id);
CREATE INDEX IF NOT EXISTS idx_chat_typing_expires_at ON chat_typing_indicators(expires_at);
`);
}
// User operations
createUser(id, username, password, email = null) {
// Validate inputs
const validation = this.securityLayer.validateInputs({ id, username, password, email });
if (!validation.valid) {
throw new Error(validation.errors.join(', '));
}
const hashedPassword = bcrypt.hashSync(password, 10);
const stmt = this.securityLayer.prepare(`
INSERT INTO users (id, username, email, hashed_password)
VALUES (?, ?, ?, ?)
`);
return stmt.run(id, username, email, hashedPassword);
}
getUserByUsername(username) {
const validation = this.securityLayer.validateInput(username);
if (!validation.valid) {
console.warn('[SECURITY] Invalid username format:', username);
return null;
}
const stmt = this.securityLayer.prepare('SELECT * FROM users WHERE username = ?');
return stmt.get(validation.sanitized);
}
getUserById(id) {
const validation = this.securityLayer.validateInput(id);
if (!validation.valid) {
console.warn('[SECURITY] Invalid user ID format:', id);
return null;
}
const stmt = this.securityLayer.prepare('SELECT * FROM users WHERE id = ?');
return stmt.get(validation.sanitized);
}
// Account lockout methods
incrementFailedLoginAttempts(username) {
const validation = this.securityLayer.validateInput(username);
if (!validation.valid) {
console.warn('[SECURITY] Invalid username format:', username);
return null;
}
const now = new Date().toISOString();
const stmt = this.securityLayer.prepare(`
UPDATE users
SET failed_login_attempts = failed_login_attempts + 1,
last_failed_login = ?,
updated_at = CURRENT_TIMESTAMP
WHERE username = ?
`);
return stmt.run(now, validation.sanitized);
}
lockAccount(username, lockDurationMinutes = 30) {
const validation = this.securityLayer.validateInput(username);
if (!validation.valid) {
console.warn('[SECURITY] Invalid username format:', username);
return null;
}
const lockedUntil = new Date();
lockedUntil.setMinutes(lockedUntil.getMinutes() + lockDurationMinutes);
const stmt = this.securityLayer.prepare(`
UPDATE users
SET locked_until = ?,
updated_at = CURRENT_TIMESTAMP
WHERE username = ?
`);
return stmt.run(lockedUntil.toISOString(), validation.sanitized);
}
resetFailedLoginAttempts(username) {
const validation = this.securityLayer.validateInput(username);
if (!validation.valid) {
console.warn('[SECURITY] Invalid username format:', username);
return null;
}
const stmt = this.securityLayer.prepare(`
UPDATE users
SET failed_login_attempts = 0,
locked_until = NULL,
updated_at = CURRENT_TIMESTAMP
WHERE username = ?
`);
return stmt.run(validation.sanitized);
}
isAccountLocked(username) {
const validation = this.securityLayer.validateInput(username);
if (!validation.valid) {
console.warn('[SECURITY] Invalid username format:', username);
return false;
}
const stmt = this.securityLayer.prepare(`
SELECT locked_until FROM users WHERE username = ?
`);
const result = stmt.get(validation.sanitized);
if (!result || !result.locked_until) {
return false;
}
const lockedUntil = new Date(result.locked_until);
const now = new Date();
// If lock has expired, reset it
if (lockedUntil <= now) {
this.resetFailedLoginAttempts(username);
return false;
}
return true;
}
resetExpiredLockouts() {
const now = new Date().toISOString();
const stmt = this.securityLayer.prepare(`
UPDATE users
SET failed_login_attempts = 0,
locked_until = NULL,
updated_at = CURRENT_TIMESTAMP
WHERE locked_until IS NOT NULL AND locked_until <= ?
`);
return stmt.run(now);
}
// Auction operations
createAuction(auction) {
// Validate auction data
const validation = this.securityLayer.validateInputs({
id: auction.id,
title: auction.title,
description: auction.description,
startingBid: auction.startingBid,
endTime: auction.endTime,
creator: auction.creator
});
if (!validation.valid) {
throw new Error(validation.errors.join(', '));
}
const stmt = this.securityLayer.prepare(`
INSERT INTO auctions (id, title, description, starting_bid, current_highest_bid, end_time, creator_id, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`);
return stmt.run(
validation.sanitized.id,
validation.sanitized.title,
validation.sanitized.description || null,
validation.sanitized.startingBid,
validation.sanitized.startingBid,
validation.sanitized.endTime,
validation.sanitized.creator,
auction.status
);
}
getAuction(id) {
const validation = this.securityLayer.validateInput(id);
if (!validation.valid) {
console.warn('[SECURITY] Invalid auction ID format:', id);
return null;
}
const stmt = this.securityLayer.prepare('SELECT * FROM auctions WHERE id = ?');
return stmt.get(validation.sanitized);
}
getAllAuctions() {
const stmt = this.securityLayer.prepare('SELECT * FROM auctions ORDER BY created_at DESC');
return stmt.all();
}
getActiveAuctions() {
const stmt = this.securityLayer.prepare("SELECT * FROM auctions WHERE status = 'active' ORDER BY created_at DESC");
return stmt.all();
}
getPaginatedAuctions(page = 1, limit = 10, status = null) {
// Validate pagination parameters
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
if (isNaN(pageNum) || pageNum < 1) {
throw new Error('Invalid page number');
}
if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
throw new Error('Limit must be between 1 and 100');
}
const offset = (pageNum - 1) * limitNum;
let query = 'SELECT * FROM auctions';
let countQuery = 'SELECT COUNT(*) as total FROM auctions';
if (status) {
const statusValidation = this.securityLayer.validateInput(status);
if (!statusValidation.valid) {
throw new Error('Invalid status value');
}
query += " WHERE status = ?";
countQuery += " WHERE status = ?";
}
query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
const countStmt = this.securityLayer.prepare(countQuery);
const auctionsStmt = this.securityLayer.prepare(query);
const totalResult = status
? countStmt.get(status)
: countStmt.get();
const auctions = status
? auctionsStmt.all(status, limitNum, offset)
: auctionsStmt.all(limitNum, offset);
return {
auctions,
pagination: {
page: pageNum,
limit: limitNum,
total: totalResult.total,
totalPages: Math.ceil(totalResult.total / limitNum),
hasMore: offset + auctions.length < totalResult.total
}
};
}
getFilteredAuctions(page = 1, limit = 10, filters = {}) {
// Validate pagination parameters
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
if (isNaN(pageNum) || pageNum < 1) {
throw new Error('Invalid page number');
}
if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
throw new Error('Limit must be between 1 and 100');
}
const offset = (pageNum - 1) * limitNum;
const params = [];
const countParams = [];
let query = `
SELECT a.*,
COUNT(DISTINCT b.id) as bid_count,
(SELECT COUNT(*) FROM auction_views WHERE auction_id = a.id) as view_count
FROM auctions a
LEFT JOIN bids b ON a.id = b.auction_id
WHERE 1=1
`;
let countQuery = `
SELECT COUNT(DISTINCT a.id) as total
FROM auctions a
LEFT JOIN bids b ON a.id = b.auction_id
WHERE 1=1
`;
// Status filter
if (filters.status && filters.status !== 'all') {
const statusValidation = this.securityLayer.validateInput(filters.status);
if (!statusValidation.valid) {
throw new Error('Invalid status value');
}
query += ' AND a.status = ?';
countQuery += ' AND a.status = ?';
params.push(filters.status);
countParams.push(filters.status);
}
// Category filter
if (filters.category && filters.category !== 'all') {
const categoryValidation = this.securityLayer.validateInput(filters.category);
if (!categoryValidation.valid) {
throw new Error('Invalid category value');
}
query += ' AND a.category = ?';
countQuery += ' AND a.category = ?';
params.push(filters.category);
countParams.push(filters.category);
}
// Price range filter
if (filters.minPrice !== undefined && filters.minPrice !== null) {
const minPrice = parseFloat(filters.minPrice);
if (isNaN(minPrice)) {
throw new Error('Invalid minimum price');
}
query += ' AND a.current_highest_bid >= ?';
countQuery += ' AND a.current_highest_bid >= ?';
params.push(minPrice);
countParams.push(minPrice);
}
if (filters.maxPrice !== undefined && filters.maxPrice !== null) {
const maxPrice = parseFloat(filters.maxPrice);
if (isNaN(maxPrice)) {
throw new Error('Invalid maximum price');
}
query += ' AND a.current_highest_bid <= ?';
countQuery += ' AND a.current_highest_bid <= ?';
params.push(maxPrice);
countParams.push(maxPrice);
}
// Ending soon filter (within 24 hours)
if (filters.endingSoon === true) {
const oneDayFromNow = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
const now = new Date().toISOString();
query += ' AND a.end_time BETWEEN ? AND ? AND a.status = "active"';
countQuery += ' AND a.end_time BETWEEN ? AND ? AND a.status = "active"';
params.push(now, oneDayFromNow);
countParams.push(now, oneDayFromNow);
}
// Search query filter
if (filters.search && filters.search.trim() !== '') {
const searchValidation = this.securityLayer.validateInput(filters.search);
if (!searchValidation.valid) {
throw new Error('Invalid search query');
}
const searchTerm = `%${filters.search.trim()}%`;
query += ' AND (a.title LIKE ? OR a.description LIKE ?)';
countQuery += ' AND (a.title LIKE ? OR a.description LIKE ?)';
params.push(searchTerm, searchTerm);
countParams.push(searchTerm, searchTerm);
}
// Add GROUP BY clause for counting distinct auctions
query += ' GROUP BY a.id';
// Sorting
const validSortOptions = ['price_asc', 'price_desc', 'time_asc', 'time_desc', 'popularity_desc', 'newest'];
const sortBy = filters.sortBy && validSortOptions.includes(filters.sortBy) ? filters.sortBy : 'newest';
switch (sortBy) {
case 'price_asc':
query += ' ORDER BY a.current_highest_bid ASC';
break;
case 'price_desc':
query += ' ORDER BY a.current_highest_bid DESC';
break;
case 'time_asc':
query += ' ORDER BY a.end_time ASC';
break;
case 'time_desc':
query += ' ORDER BY a.end_time DESC';
break;
case 'popularity_desc':
query += ' ORDER BY bid_count DESC';
break;
case 'newest':
default:
query += ' ORDER BY a.created_at DESC';
break;
}
query += ' LIMIT ? OFFSET ?';
params.push(limitNum, offset);
const countStmt = this.securityLayer.prepare(countQuery);
const auctionsStmt = this.securityLayer.prepare(query);
const totalResult = countStmt.get(...countParams);
const auctions = auctionsStmt.all(...params);
return {
auctions,
pagination: {
page: pageNum,
limit: limitNum,
total: totalResult.total,
totalPages: Math.ceil(totalResult.total / limitNum),
hasMore: offset + auctions.length < totalResult.total
}
};
}
getAuctionCategories() {
const stmt = this.securityLayer.prepare('SELECT DISTINCT category FROM auctions WHERE category IS NOT NULL ORDER BY category');
return stmt.all();
}
searchAuctions(query, limit = 20) {
const queryValidation = this.securityLayer.validateInput(query);
if (!queryValidation.valid) {
throw new Error('Invalid search query');
}
const searchTerm = `%${query.trim()}%`;
const stmt = this.securityLayer.prepare(`
SELECT id, title, description, current_highest_bid, category, status
FROM auctions
WHERE (title LIKE ? OR description LIKE ?)
AND status = 'active'
ORDER BY created_at DESC
LIMIT ?
`);
return stmt.all(searchTerm, searchTerm, limit);
}
recordAuctionView(auctionId, userId = null, ipAddress = null, userAgent = null) {
try {
const idValidation = this.securityLayer.validateInput(auctionId);
if (!idValidation.valid) {
throw new Error('Invalid auction ID');
}
const viewId = require('uuid').v4();
const stmt = this.securityLayer.prepare(`
INSERT INTO auction_views (id, auction_id, user_id, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?)
`);
stmt.run(viewId, auctionId, userId || null, ipAddress || null, userAgent || null);
return { id: viewId, success: true };
} catch (error) {
// View recording failure should not break the app
console.warn('Failed to record auction view:', error);
return { success: false };
}
}
getAuctionViewCount(auctionId) {
try {
const idValidation = this.securityLayer.validateInput(auctionId);
if (!idValidation.valid) {
throw new Error('Invalid auction ID');
}
const stmt = this.securityLayer.prepare(`
SELECT COUNT(*) as view_count FROM auction_views WHERE auction_id = ?
`);
const result = stmt.get(auctionId);
return result.view_count || 0;
} catch (error) {
console.warn('Failed to get auction view count:', error);
return 0;
}
}
getUserAuctions(userId, filters = {}) {
const { limit = 50, offset = 0, status, sortBy = 'created_at', sortOrder = 'DESC' } = filters;
// Validate user ID
const userValidation = this.securityLayer.validateInput(userId);
if (!userValidation.valid) {
throw new Error('Invalid user ID');
}
let query = `
SELECT a.*,
COUNT(b.id) as bid_count,
MAX(b.amount) as highest_bid,
u.username as creator_username
FROM auctions a
LEFT JOIN bids b ON a.id = b.auction_id
LEFT JOIN users u ON a.creator_id = u.id
WHERE a.creator_id = ?
`;
const params = [userValidation.sanitized];
if (status && status !== 'all') {
query += ` AND a.status = ?`;
params.push(status);
}