-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1432 lines (1217 loc) · 48.1 KB
/
Copy pathserver.ts
File metadata and controls
1432 lines (1217 loc) · 48.1 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
import express, { Request, Response } from 'express';
import path from 'path';
import fs from 'fs';
import dotenv from 'dotenv';
import { createServer as createViteServer } from 'vite';
// Load environment variables
dotenv.config();
import { db } from './src/server/db';
import { matchesSearch } from './src/server/utils';
import { COUNTRIES, CURRENCIES, LANGUAGES, TIMEZONES } from './src/server/globalPreferencesData';
import {
getShoppingAssistantResponse,
getReviewSummary,
generateProductDescription,
checkReviewValidity
} from './src/server/gemini';
import { Order, UserRole, UserSession } from './src/types';
// Global state tracking
let activeUserId: string | null = null; // Starts as unauthenticated
const GUEST_SESSION: UserSession = {
id: 'guest',
name: 'Guest User',
email: 'guest@ocean.com',
role: 'Customer',
walletBalance: 0,
rewardCoins: 0,
isOnboarded: true
};
const otpStorage = new Map<string, { otp: string; expires: number }>();
async function startServer() {
const app = express();
const PORT = 3000;
// Body parsers
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Attach activeUserId to request context for api-v1 routes
app.use((req: any, res: any, next: any) => {
req.userId = activeUserId;
next();
});
// Versioned Enterprise REST API Router (v1)
const { apiV1Router } = await import('./src/server/routes/api-v1');
app.use('/api/v1', apiV1Router);
// --- API ROUTES ---
// Auth/Session endpoints
app.get('/api/auth/sessions', (req: Request, res: Response) => {
const sessions = db.getUserSessions();
const active = activeUserId === 'guest' ? GUEST_SESSION : (sessions.find(s => s.id === activeUserId) || null);
res.json({ sessions, active });
});
app.get('/api/auth/session', (req: Request, res: Response) => {
const sessions = db.getUserSessions();
const active = activeUserId === 'guest' ? GUEST_SESSION : (sessions.find(s => s.id === activeUserId) || null);
res.json(active);
});
app.post('/api/auth/login', (req: Request, res: Response) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Identity (Email/Username/Phone) and password are required.' });
}
const inputLower = email.toLowerCase().trim();
const sessions = db.getUserSessions();
const user = sessions.find(s =>
s.email.toLowerCase() === inputLower ||
(s.username && s.username.toLowerCase() === inputLower) ||
(s.phone && s.phone.replace(/[^0-9+]/g, '') === inputLower.replace(/[^0-9+]/g, ''))
);
if (!user) {
return res.status(401).json({ error: 'Invalid identifier (Email/Username/Phone) or password.' });
}
// Check account lock
const now = Date.now();
if (user.lockedUntil && new Date(user.lockedUntil).getTime() > now) {
const remainingMinutes = Math.ceil((new Date(user.lockedUntil).getTime() - now) / 60000);
return res.status(403).json({ error: `Account is temporarily locked due to repeated failures. Please try again in ${remainingMinutes} minutes.` });
}
const { hashPassword } = require('./src/server/db');
const inputHash = hashPassword(password);
if (user.password !== inputHash) {
const attempts = (user.failedAttempts || 0) + 1;
const updates: Partial<UserSession> = { failedAttempts: attempts };
db.addAuditLog({
action: `Failed login attempt for ${inputLower}`,
user: user.name,
role: user.role,
status: 'Warning',
ip: req.ip || '127.0.0.1'
});
if (attempts >= 5) {
updates.lockedUntil = new Date(now + 5 * 60 * 1000).toISOString(); // lock for 5 mins
db.updateUserProfile(user.id, updates);
return res.status(403).json({ error: 'Account locked due to 5 consecutive failed attempts. Please try again in 5 minutes.' });
}
db.updateUserProfile(user.id, updates);
return res.status(401).json({ error: 'Invalid email or password.' });
}
// Success
const historyItem = {
timestamp: new Date().toISOString(),
ip: req.ip || '127.0.0.1',
device: req.headers['user-agent'] || 'Unknown Device',
status: 'Success'
};
const updates: Partial<UserSession> = {
failedAttempts: 0,
lockedUntil: null,
loginHistory: [historyItem, ...(user.loginHistory || [])].slice(0, 10)
};
db.updateUserProfile(user.id, updates);
activeUserId = user.id;
db.addAuditLog({
action: `User logged in successfully: ${user.name}`,
user: user.name,
role: user.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: user });
});
app.post('/api/auth/register', (req: Request, res: Response) => {
const { firstName, lastName, username, email, phone, password, confirmPassword } = req.body;
if (!firstName || !lastName || !email || !phone || !password || !confirmPassword) {
return res.status(400).json({ error: 'All fields are required.' });
}
if (password !== confirmPassword) {
return res.status(400).json({ error: 'Passwords do not match.' });
}
if (password.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters long.' });
}
const emailLower = email.toLowerCase().trim();
const sessions = db.getUserSessions();
const existingEmail = sessions.find(s => s.email.toLowerCase() === emailLower);
if (existingEmail) {
return res.status(400).json({ error: 'An account with this email address already exists.' });
}
const existingPhone = sessions.find(s => s.phone === phone);
if (existingPhone) {
return res.status(400).json({ error: 'An account with this phone number already exists.' });
}
if (username) {
const uLower = username.toLowerCase().trim();
const existingUser = sessions.find(s => s.username?.toLowerCase() === uLower);
if (existingUser) {
return res.status(400).json({ error: 'Username is already taken by another merchant or explorer.' });
}
}
const { hashPassword } = require('./src/server/db');
const newUser = db.registerUser({
name: `${firstName} ${lastName}`,
username: username || `${firstName.toLowerCase()}_${lastName.toLowerCase()}`,
email: emailLower,
phone,
role: 'Customer',
password: hashPassword(password),
isOnboarded: false,
failedAttempts: 0,
loginHistory: [{
timestamp: new Date().toISOString(),
ip: req.ip || '127.0.0.1',
device: req.headers['user-agent'] || 'Unknown Device',
status: 'Registered'
}]
});
db.addAuditLog({
action: `New account registered: ${emailLower}`,
user: newUser.name,
role: newUser.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
activeUserId = newUser.id;
res.json({ success: true, active: newUser });
});
app.post('/api/auth/otp-send', (req: Request, res: Response) => {
const { emailOrPhone } = req.body;
if (!emailOrPhone) {
return res.status(400).json({ error: 'Email or Phone is required.' });
}
const otp = Math.floor(100000 + Math.random() * 900000).toString();
const expires = Date.now() + 5 * 60 * 1000; // 5 mins
otpStorage.set(emailOrPhone.toLowerCase().trim(), { otp, expires });
db.addAuditLog({
action: `OTP simulated send for ${emailOrPhone} (Code: ${otp})`,
user: 'System',
role: 'Admin',
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, message: 'OTP sent successfully (Simulated)', otp });
});
app.post('/api/auth/otp-verify', (req: Request, res: Response) => {
const { emailOrPhone, otp } = req.body;
if (!emailOrPhone || !otp) {
return res.status(400).json({ error: 'Email/Phone and OTP are required.' });
}
const key = emailOrPhone.toLowerCase().trim();
const record = otpStorage.get(key);
if (!record) {
return res.status(400).json({ error: 'No OTP code was sent to this address.' });
}
if (Date.now() > record.expires) {
return res.status(400).json({ error: 'OTP code has expired. Please request a new one.' });
}
if (record.otp !== otp) {
return res.status(400).json({ error: 'Invalid OTP code.' });
}
otpStorage.delete(key);
db.addAuditLog({
action: `OTP verified successfully for ${emailOrPhone}`,
user: 'System',
role: 'Admin',
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true });
});
app.post('/api/auth/profile-complete', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const { avatar, gender, birthday, preferredLanguage, currency, country, city, address } = req.body;
const updatedUser = db.updateUserProfile(activeUserId, {
avatar: avatar || 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=100&auto=format&fit=crop&q=80',
gender,
birthday,
preferredLanguage: preferredLanguage || 'English',
currency: currency || 'USD',
country: country || 'United States',
city: city || 'Seattle',
address: address || '123 Pine St'
});
if (!updatedUser) {
return res.status(404).json({ error: 'User not found.' });
}
db.addAuditLog({
action: `Profile details completed: ${updatedUser.name}`,
user: updatedUser.name,
role: updatedUser.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: updatedUser });
});
app.post('/api/auth/interests-complete', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const { interests } = req.body;
if (!interests || !Array.isArray(interests) || interests.length < 3) {
return res.status(400).json({ error: 'Please select at least 3 interests.' });
}
const updatedUser = db.updateUserProfile(activeUserId, { interests });
if (!updatedUser) {
return res.status(404).json({ error: 'User not found.' });
}
db.addAuditLog({
action: `Interests completed: ${interests.join(', ')}`,
user: updatedUser.name,
role: updatedUser.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: updatedUser });
});
app.post('/api/auth/permissions-complete', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const { permissions } = req.body;
const updatedUser = db.updateUserProfile(activeUserId, {
permissions: permissions || {},
isOnboarded: true
});
if (!updatedUser) {
return res.status(404).json({ error: 'User not found.' });
}
db.addAuditLog({
action: `Permissions screen processed. App entry complete.`,
user: updatedUser.name,
role: updatedUser.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: updatedUser });
});
// Profile Update API Endpoint
app.post('/api/auth/profile-update', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const {
name,
username,
bio,
birthday,
gender,
preferredLanguage,
currency,
country,
city,
address,
timezone,
communicationPreferences,
subscriptions,
email,
phone
} = req.body;
const sessions = db.getUserSessions();
// Check username duplicates if username is changed
if (username) {
const uLower = username.toLowerCase().trim();
const duplicate = sessions.find(s => s.id !== activeUserId && s.username?.toLowerCase() === uLower);
if (duplicate) {
return res.status(400).json({ error: 'Username is already taken by another merchant or explorer.' });
}
}
// Check email duplicates if email is changed
if (email) {
const eLower = email.toLowerCase().trim();
const duplicate = sessions.find(s => s.id !== activeUserId && s.email.toLowerCase() === eLower);
if (duplicate) {
return res.status(400).json({ error: 'Email address is already in use by another account.' });
}
}
const updates: Partial<UserSession> = {};
if (name !== undefined) updates.name = name;
if (username !== undefined) updates.username = username;
if (bio !== undefined) updates.bio = bio;
if (birthday !== undefined) updates.birthday = birthday;
if (gender !== undefined) updates.gender = gender;
if (preferredLanguage !== undefined) updates.preferredLanguage = preferredLanguage;
if (currency !== undefined) updates.currency = currency;
if (country !== undefined) updates.country = country;
if (city !== undefined) updates.city = city;
if (address !== undefined) updates.address = address;
if (timezone !== undefined) updates.timezone = timezone;
if (communicationPreferences !== undefined) updates.communicationPreferences = communicationPreferences;
if (subscriptions !== undefined) updates.subscriptions = subscriptions;
if (email !== undefined) updates.email = email;
if (phone !== undefined) updates.phone = phone;
const updatedUser = db.updateUserProfile(activeUserId, updates);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found.' });
}
db.addAuditLog({
action: `Profile fields updated successfully: ${updatedUser.name}`,
user: updatedUser.name,
role: updatedUser.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: updatedUser });
});
// Security change password
app.post('/api/auth/change-password', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const { currentPassword, newPassword } = req.body;
const sessions = db.getUserSessions();
const user = sessions.find(s => s.id === activeUserId);
if (!user) {
return res.status(404).json({ error: 'User not found.' });
}
const { hashPassword } = require('./src/server/db');
const inputHash = hashPassword(currentPassword);
if (user.password !== inputHash) {
return res.status(400).json({ error: 'The current password you provided is incorrect.' });
}
const newHash = hashPassword(newPassword);
db.updateUserProfile(activeUserId, { password: newHash });
db.addAuditLog({
action: `Password updated securely for ${user.name}`,
user: user.name,
role: user.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true });
});
// Verify 2FA configuration
app.post('/api/auth/2fa/verify', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const { enabled, type, code } = req.body;
const sessions = db.getUserSessions();
const user = sessions.find(s => s.id === activeUserId);
if (!user) {
return res.status(404).json({ error: 'User not found.' });
}
if (enabled) {
if (!code || code !== '123456') {
return res.status(400).json({ error: 'Invalid verification token. Please type mock code: 123456.' });
}
db.updateUserProfile(activeUserId, {
is2FAEnabled: true,
twoFactorType: type || 'authenticator'
});
db.addAuditLog({
action: `Two-Factor Authentication enabled (${type}) for ${user.name}`,
user: user.name,
role: user.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
} else {
db.updateUserProfile(activeUserId, {
is2FAEnabled: false
});
db.addAuditLog({
action: `Two-Factor Authentication disabled for ${user.name}`,
user: user.name,
role: user.role,
status: 'Warning',
ip: req.ip || '127.0.0.1'
});
}
res.json({ success: true, active: db.getUserSessions().find(s => s.id === activeUserId) });
});
// Download complete account data
app.get('/api/auth/download-data', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const sessions = db.getUserSessions();
const user = sessions.find(s => s.id === activeUserId);
if (!user) {
return res.status(404).json({ error: 'User not found.' });
}
const auditLogs = db.getAuditLogs().filter(l => l.user === user.name);
const backupData = {
downloadTimestamp: new Date().toISOString(),
provider: "Ocean Enterprise Digital Platform LLC",
userProfile: {
id: user.id,
name: user.name,
username: user.username,
email: user.email,
phone: user.phone,
bio: user.bio,
role: user.role,
gender: user.gender,
birthday: user.birthday,
preferredLanguage: user.preferredLanguage,
currency: user.currency,
country: user.country,
city: user.city,
address: user.address,
timezone: user.timezone,
walletBalance: user.walletBalance,
rewardCoins: user.rewardCoins,
isOnboarded: user.isOnboarded,
is2FAEnabled: user.is2FAEnabled,
twoFactorType: user.twoFactorType,
interests: user.interests
},
auditLogs: auditLogs,
securityHistory: user.loginHistory || []
};
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Disposition', `attachment; filename=ocean_account_data_${user.id}.json`);
res.json(backupData);
});
// Terminate account
app.post('/api/auth/delete-account', (req: Request, res: Response) => {
if (!activeUserId) {
return res.status(401).json({ error: 'No active session.' });
}
const sessions = db.getUserSessions();
const userIndex = sessions.findIndex(s => s.id === activeUserId);
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found.' });
}
const user = sessions[userIndex];
db.addAuditLog({
action: `Account permanently deleted: ${user.name}`,
user: 'System',
role: 'Admin',
status: 'Warning',
ip: req.ip || '127.0.0.1'
});
sessions.splice(userIndex, 1);
db.save();
activeUserId = null;
res.json({ success: true });
});
// Forgot password request OTP
app.post('/api/auth/forgot-password/request', (req: Request, res: Response) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required.' });
}
const sessions = db.getUserSessions();
const user = sessions.find(s => s.email.toLowerCase() === email.toLowerCase().trim());
if (!user) {
return res.status(404).json({ error: 'No account registered with this email address.' });
}
const otp = '999999'; // standard test OTP for password forgot
const key = `forgot:${email.toLowerCase().trim()}`;
otpStorage.set(key, { otp, expires: Date.now() + 10 * 60 * 1000 });
db.addAuditLog({
action: `Recovery OTP code generated for ${email}`,
user: user.name,
role: user.role,
status: 'Warning',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, simulatedOtp: otp });
});
// Forgot password verify OTP
app.post('/api/auth/forgot-password/verify', (req: Request, res: Response) => {
const { email, code } = req.body;
if (!email || !code) {
return res.status(400).json({ error: 'Email and OTP code are required.' });
}
const key = `forgot:${email.toLowerCase().trim()}`;
const record = otpStorage.get(key);
if (!record) {
return res.status(400).json({ error: 'Verification window expired. Please request a new code.' });
}
if (record.otp !== code) {
return res.status(400).json({ error: 'Invalid verification token. Please type: 999999.' });
}
res.json({ success: true });
});
// Forgot password reset
app.post('/api/auth/forgot-password/reset', (req: Request, res: Response) => {
const { email, code, newPassword } = req.body;
if (!email || !code || !newPassword) {
return res.status(400).json({ error: 'All fields are required.' });
}
const key = `forgot:${email.toLowerCase().trim()}`;
const record = otpStorage.get(key);
if (!record || record.otp !== code) {
return res.status(400).json({ error: 'Verification token invalid or expired.' });
}
const sessions = db.getUserSessions();
const user = sessions.find(s => s.email.toLowerCase() === email.toLowerCase().trim());
if (!user) {
return res.status(404).json({ error: 'User session not found.' });
}
const { hashPassword } = require('./src/server/db');
const newHash = hashPassword(newPassword);
db.updateUserProfile(user.id, {
password: newHash,
failedAttempts: 0,
lockedUntil: null
});
otpStorage.delete(key);
db.addAuditLog({
action: `Password reset successfully via OTP recovery: ${user.name}`,
user: user.name,
role: user.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true });
});
app.post('/api/auth/guest', (req: Request, res: Response) => {
activeUserId = 'guest';
db.addAuditLog({
action: 'Guest browsing session initiated',
user: 'Guest',
role: 'Customer',
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: GUEST_SESSION });
});
app.post('/api/auth/logout', (req: Request, res: Response) => {
const sessions = db.getUserSessions();
const user = activeUserId === 'guest' ? GUEST_SESSION : sessions.find(s => s.id === activeUserId);
db.addAuditLog({
action: `User session ended / logged out`,
user: user ? user.name : 'Unknown',
role: user ? user.role : 'Customer',
status: 'Success',
ip: req.ip || '127.0.0.1'
});
activeUserId = null;
res.json({ success: true });
});
app.post('/api/auth/switch-role', (req: Request, res: Response) => {
const { role } = req.body;
const session = db.getUserSessions().find(s => s.role === role);
if (session) {
activeUserId = session.id;
db.addAuditLog({
action: `User switched role to ${role} (${session.name})`,
user: session.name,
role: session.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: session });
} else {
res.status(404).json({ error: `Session user with role ${role} not found.` });
}
});
app.post('/api/auth/select', (req: Request, res: Response) => {
const { userId } = req.body;
const session = db.getUserSessions().find(s => s.id === userId);
if (session) {
activeUserId = userId;
db.addAuditLog({
action: `User session switched to ${session.name}`,
user: session.name,
role: session.role,
status: 'Success',
ip: req.ip || '127.0.0.1'
});
res.json({ success: true, active: session });
} else {
res.status(404).json({ error: 'Session user not found.' });
}
});
// Get active session wallet & coins
app.get('/api/auth/me', (req: Request, res: Response) => {
const sessions = db.getUserSessions();
const active = activeUserId === 'guest' ? GUEST_SESSION : (sessions.find(s => s.id === activeUserId) || null);
res.json(active);
});
// Products endpoints
app.get('/api/products', (req: Request, res: Response) => {
const { q, category, brand, collection, minPrice, maxPrice, sortBy, limit, offset, paginated, deals, luxury, editorsChoice, trending, newReleases, bestSellers, seasonal, gifts } = req.query;
let products = db.getProducts();
if (category && category !== 'All') {
const catLower = (category as string).toLowerCase();
// Handle "Living Room" custom subnav categories mapping
if (catLower === 'living room' || catLower === 'living room design') {
products = products.filter(p =>
p.category === 'Home' ||
p.category === 'Home & Kitchen' ||
p.subcategory?.toLowerCase() === 'furniture' ||
p.subcategory?.toLowerCase() === 'decor' ||
p.subcategory?.toLowerCase() === 'lighting' ||
p.subcategory?.toLowerCase() === 'sofas' ||
p.subcategory?.toLowerCase() === 'tables' ||
p.subcategory?.toLowerCase() === 'plants' ||
p.subcategory?.toLowerCase() === 'wall art'
);
} else {
products = products.filter(p => p.category.toLowerCase() === catLower);
}
}
if (brand) {
const brandLower = (brand as string).toLowerCase();
products = products.filter(p => p.brand.toLowerCase() === brandLower);
}
if (collection) {
const collLower = (collection as string).toLowerCase();
products = products.filter(p =>
((p as any).collection && (p as any).collection.toLowerCase().includes(collLower)) ||
(collLower === 'sustainable' && (
(p as any).collection?.toLowerCase().includes('eco') ||
(p as any).collection?.toLowerCase().includes('sustainable') ||
p.description.toLowerCase().includes('eco-friendly') ||
p.description.toLowerCase().includes('organic') ||
p.description.toLowerCase().includes('sustainable')
)) ||
(collLower === 'minimal-workspace' && (p.category === 'Accessories' || p.category === 'Laptops' || p.subcategory?.toLowerCase() === 'audio'))
);
}
if (minPrice) {
const min = parseFloat(minPrice as string);
products = products.filter(p => p.price >= min);
}
if (maxPrice) {
const max = parseFloat(maxPrice as string);
products = products.filter(p => p.price <= max);
}
if (q) {
products = products.filter(p => matchesSearch(p, q as string));
}
if (deals === 'true') {
products = products.filter(p => p.price > 40);
}
if (luxury === 'true') {
products = products.filter(p => p.price > 500 || ['rolex', 'omega', 'gucci', 'prada', 'louis vuitton', 'leica', 'bose', 'apple'].includes(p.brand.toLowerCase()));
}
if (editorsChoice === 'true') {
products = products.filter(p => p.rating >= 4.7);
}
if (seasonal === 'true') {
products = products.filter(p => p.description.toLowerCase().includes('seasonal') || p.description.toLowerCase().includes('summer') || p.description.toLowerCase().includes('winter') || p.description.toLowerCase().includes('spring') || p.description.toLowerCase().includes('autumn'));
}
if (gifts === 'true') {
products = products.filter(p => p.description.toLowerCase().includes('gift') || p.description.toLowerCase().includes('present'));
}
// Apply Sorting
let activeSortBy = sortBy;
if (trending === 'true' && !sortBy) activeSortBy = 'rating';
if (newReleases === 'true' && !sortBy) activeSortBy = 'newest';
if (bestSellers === 'true' && !sortBy) activeSortBy = 'popularity';
if (activeSortBy === 'price_asc') {
products.sort((a, b) => a.price - b.price);
} else if (activeSortBy === 'price_desc') {
products.sort((a, b) => b.price - a.price);
} else if (activeSortBy === 'rating') {
products.sort((a, b) => (b.rating || 0) - (a.rating || 0));
} else if (activeSortBy === 'popularity') {
products.sort((a, b) => (b.reviewsCount || 0) - (a.reviewsCount || 0));
} else if (activeSortBy === 'newest') {
products.sort((a, b) => b.id.localeCompare(a.id));
}
const total = products.length;
// Apply Pagination
if (limit) {
const lim = parseInt(limit as string);
const off = offset ? parseInt(offset as string) : 0;
products = products.slice(off, off + lim);
}
if (paginated === 'true') {
res.json({
items: products,
total
});
} else {
res.json(products);
}
});
// Homepage curated discovery endpoint (only returns 80-150 products across sections)
app.get('/api/homepage-discovery', (req: Request, res: Response) => {
const products = db.getProducts();
const heroBanners = [
{
id: 'banner-1',
title: 'The Next-Gen Audio Drop',
subtitle: 'Immersive Active Noise Cancellation and high-fidelity soundscapes.',
image: 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=1600&auto=format&fit=crop&q=80',
cta: 'Explore Acoustics',
path: '/category/Electronics'
},
{
id: 'banner-2',
title: 'Minimalist Wardrobe',
subtitle: 'Tailored garments crafted with natural, breathable fibers.',
image: 'https://images.unsplash.com/photo-1483985988355-763728e1935b?w=1600&auto=format&fit=crop&q=80',
cta: 'View Apparel',
path: '/category/Fashion Men'
},
{
id: 'banner-3',
title: 'Living Space Aesthetics',
subtitle: 'Architectural home accessories designed for modern living.',
image: 'https://images.unsplash.com/photo-1513694203232-719a280e022f?w=1600&auto=format&fit=crop&q=80',
cta: 'Shop Collection',
path: '/home'
}
];
// Featured: first 12 items
const featuredProducts = products.slice(0, 12);
// 1. New Releases (12 newest products, or first 12 in the list)
const newReleases = [...products]
.filter(p => p.rating && p.stock > 0)
.slice(0, 12);
// 2. Best Sellers (12 highest rating or reviewsCount products)
const bestSellers = [...products]
.filter(p => p.rating >= 4.5 && p.stock > 0)
.sort((a, b) => (b.reviewsCount || 0) - (a.reviewsCount || 0))
.slice(0, 12);
// 3. Trending Today (sorted by reviews count or rating)
const trending = [...products]
.filter(p => p.stock > 0)
.sort((a, b) => {
return (b.rating * (b.reviewsCount || 1)) - (a.rating * (a.reviewsCount || 1));
})
.slice(0, 12);
// 4. Deals of the Day (discounted products with fake limited stock & countdown context)
const deals = [...products]
.filter(p => p.price > 40 && p.stock > 0)
.slice(15, 27)
.map((p, i) => ({
...p,
originalPrice: Math.round(p.price * 1.3),
discountPercent: 15 + (i * 3) % 25,
limitedStock: p.stock > 6 ? 3 : p.stock
}));
// 5. Luxury Collection (Rolex, Omega, high price products)
const luxury = [...products]
.filter(p => p.price > 700 || ['rolex', 'omega', 'gucci', 'prada', 'louis vuitton', 'leica', 'bose', 'apple'].includes(p.brand.toLowerCase()))
.slice(0, 12);
// Collections
const collections = [
{ id: 'sustainable', name: 'Sustainable Materials', description: 'Eco-friendly, recycled, and organic designs.', image: 'https://images.unsplash.com/photo-1542601906990-b4d3fb778b09?w=800&auto=format&fit=crop&q=80' },
{ id: 'minimal-workspace', name: 'Minimalist Workspaces', description: 'High-efficiency setups for deep focus.', image: 'https://images.unsplash.com/photo-1493934558415-9d19f0b2b4d2?w=800&auto=format&fit=crop&q=80' }
];
// Brands
const brands = [
{ name: 'Sony Direct Store', logo: 'https://images.unsplash.com/photo-1610030469983-98e550d6193c?w=100&auto=format&fit=crop&q=80', path: '/brand/Sony' },
{ name: 'Apple Certified Store', logo: 'https://images.unsplash.com/photo-1611186871348-b1ce696e52c9?w=100&auto=format&fit=crop&q=80', path: '/brand/Sony' },
{ name: 'Nike Store Front', logo: 'https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=100&auto=format&fit=crop&q=80', path: '/brand/Nike' },
{ name: 'Aesop Direct Store', logo: 'https://images.unsplash.com/photo-1608248597279-f99d160bfcbc?w=100&auto=format&fit=crop&q=80', path: '/brand/Sony' }
];
// Recently Viewed
const recentlyViewed = products.filter(p => ['prod-1', 'prod-2', 'prod-5'].includes(p.id));
// Recommended
const recommended = products.slice(4, 16);
// Flash Sale
const flashSale = products.slice(8, 14).map((p, i) => ({
...p,
originalPrice: Math.round(p.price * 1.4),
discountPercent: 25 + (i * 4) % 25,
limitedStock: Math.max(1, p.stock % 4)
}));
// New arrivals
const newArrivals = [...products]
.sort((a, b) => b.id.localeCompare(a.id))
.slice(0, 12);
// 6. Curated Category Sections (12 items each)
const electronics = products.filter(p => p.category === 'Electronics').slice(0, 12);
const fashion = products.filter(p => p.category === 'Fashion Men' || p.category === 'Fashion Women').slice(0, 12);
const homeKitchen = products.filter(p => p.category === 'Home & Kitchen' || p.category === 'Home').slice(0, 12);
const gaming = products.filter(p => p.category === 'Laptops' || p.subcategory?.toLowerCase() === 'gaming').slice(0, 12);
const beauty = products.filter(p => p.category === 'Beauty').slice(0, 12);
const books = products.filter(p => p.category === 'Books').slice(0, 12);
const toys = products.filter(p => p.category === 'Toys').slice(0, 12);
const sports = products.filter(p => p.category === 'Sports').slice(0, 12);
res.json({
heroBanners,
featuredProducts,
newReleases,
bestSellers,
trending,
deals,
luxury,
electronics,
fashion,
homeKitchen,
gaming,
beauty,
books,
toys,
sports,
collections,
brands,
recentlyViewed,
recommended,
flashSale,
newArrivals
});
});
app.post('/api/products', (req: Request, res: Response) => {