-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
1099 lines (895 loc) · 36.2 KB
/
server.js
File metadata and controls
1099 lines (895 loc) · 36.2 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 fetch from 'node-fetch';
import express from 'express';
import passport from 'passport';
import session from 'express-session';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import { Strategy as FacebookStrategy } from 'passport-facebook';
import path from 'path';
import dotenv from 'dotenv';
import sgMail from '@sendgrid/mail';
import { fileURLToPath } from 'url';
import fs from 'fs';
import https from 'https';
import twilio from 'twilio';
import crypto from 'crypto';
import cookieParser from 'cookie-parser';
import { v4 as uuidv4 } from 'uuid';
import { Router } from 'express';
import bodyParser from 'body-parser';
import speakeasy from 'speakeasy';
import QRCode from 'qrcode';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const newUuid = uuidv4();
const DB_FILE = path.join(__dirname, 'db.json');
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
const PORT = 3000;
app.use(express.json());
app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
const secret = 'd#IryuziNby|$z(E<+SW>Gl*Elg{|%';
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const FACEBOOK_APP_ID = process.env.FACEBOOK_APP_ID;
const FACEBOOK_APP_SECRET = process.env.FACEBOOK_APP_SECRET;
const SESSION_SECRET = process.env.SESSION_SECRET;
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
const TWILLIO_AccountSid = process.env.TWILLIO_AccountSid; // Your Twilio Account SID
const TWILLIO_AUTH_TOKEN = process.env.TWILLIO_AUTH_TOKEN; // Your Twilio Auth Token
const SENDGRID_SENDER_EMAIL = process.env.SENDGRID_SENDER_EMAIL;
const DEFAULT_TEST_PHONE_NUMBER = process.env.DEFAULT_TEST_PHONE_NUMBER;
const TWILLIO_FROM_PHONE = process.env.TWILLIO_FROM_PHONE;
const GOOGLE_CAPTCHA_SITE_KEY = process.env.GOOGLE_CAPTCHA_SITE_KEY;
const GOOGLE_CAPTCHA_SECRET_KEY = process.env.GOOGLE_CAPTCHA_SECRET_KEY;
const defaultUsers = [
{
id: 1,
username: 'johnDoe',
email: 'john@example.com',
password: 'password123', // NOTE: In real scenarios, this would be a hashed password.
role: 'admin',
loginMethod: 'local',
provider: 'LOCAL',
status: 'active', // new status property
phone: DEFAULT_TEST_PHONE_NUMBER,
twoFA: {
secret: null, // will hold the 2FA secret
enabled: false
}
},
{
id: 2,
username: 'janeDoe',
email: 'jane@example.com',
password: 'password456', // NOTE: In real scenarios, this would be a hashed password.
role: 'user',
loginMethod: 'local',
provider: 'LOCAL',
status: 'tobeactivated', // new status property
phone: DEFAULT_TEST_PHONE_NUMBER,
twoFA: {
secret: null, // will hold the 2FA secret
enabled: false
}
}
];
let users;
// Load database from file at startup
if (fs.existsSync(DB_FILE)) {
const rawData = fs.readFileSync(DB_FILE);
users = JSON.parse(rawData);
} else {
// If no DB file exists, initialize it with default data.
users = defaultUsers;
}
process.on('SIGINT', () => {
fs.writeFileSync(DB_FILE, JSON.stringify(users, null, 2));
process.exit();
});
const twilioClient = twilio(TWILLIO_AccountSid, TWILLIO_AUTH_TOKEN);
const twilioRouter = Router();
sgMail.setApiKey(SENDGRID_API_KEY);
// Initialize Passport and session
app.use(cookieParser());
app.use(session({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serialize and deserialize user information
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
// Google Strategy
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "https://localhost:3000/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
// Save the access token here
profile.token = accessToken;
return done(null, profile);
}));
// var FacebookStrategy = require('passport-facebook').Strategy;
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: "https://localhost:3000/auth/facebook/callback", // Make sure to update this URL
profileFields: ['id', 'displayName', 'emails'],
},
function (accessToken, refreshToken, profile, done) {
// Here, instead of looking up or creating a user in a database, we're just passing the profile info directly
// Attach the access token if needed
profile.accessToken = accessToken;
return done(null, profile);
}));
app.get('/reset-db', (req, res) => {
users = defaultUsers;
if (fs.existsSync(DB_FILE)) {
fs.unlinkSync(DB_FILE); // Delete the database file
}
res.send('Database reset successful!');
});
app.get('/auth/facebook',
passport.authenticate('facebook', { scope: 'email' }));
app.use((req, res, next) => {
if (req.session.user) {
res.locals.user = req.session.user;
}
next();
});
app.get('/logout', (req, res) => {
req.session.destroy(function (err) {
res.cookie('auth', '', { expires: new Date(0) });
res.cookie('userId', '', { expires: new Date(0) });
res.redirect('/'); // Redirect back to the homepage or login page
});
});
app.get('/profile', requireLogin, (req, res) => {
res.render('profile', { user: req.session.user });
});
app.get('/api/profile', (req, res) => {
// Here, you would fetch the user's information from your authentication
// library or database based on their session or authentication token
if (req.session.user) {
res.json({
displayName: req.session.user.displayName,
provider: req.session.user.provider
});
} else {
res.status(401).send(); // Not authorized
}
});
// Revoke Google Access
app.get('/revoke-google', (req, res) => {
const token = req.session.user.googleToken; // Retrieve the Google token from the session
console.log("Access Token: ", token); // Log the token
fetch('https://accounts.google.com/o/oauth2/revoke?token=' + token) // Removed { method: 'POST' }
.then(response => {
if (!response.ok) {
return response.text().then(text => Promise.reject(text));
}
// Handle success (e.g., log out the user or clear the token)
req.session.user = null; // Or use req.session.destroy();
res.redirect('/'); // Redirect or send a response as needed
})
.catch(error => {
// Handle errors
console.error(error);
res.status(500).send('An error occurred while revoking access');
});
});
// Revoke Facebook Access
app.get('/revoke-facebook', (req, res) => {
const userId = req.session.user.facebookUserId; // Retrieve the Facebook user ID from the session
const accessToken = req.session.user.facebookAccessToken; // Retrieve the Facebook access token from the session
console.log("Access Token: ", accessToken); // Log the token
fetch('https://graph.facebook.com/' + userId + '/permissions?access_token=' + accessToken, { method: 'DELETE' })
.then(response => {
if (!response.ok) {
return response.text().then(text => Promise.reject(text));
}
// Handle success (e.g., log out the user or clear the token)
req.session.user = null;
res.redirect('/'); // Redirect or send a response as needed
})
.catch(error => {
// Handle errors
console.error(error);
res.status(500).send('An error occurred while revoking access');
});
});
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
function (req, res) {
console.log('Google profile:', req.user);
let email = req.user.emails ? req.user.emails[0].value : req.user.email;
const user = registerOrRetrieveUser({
provider: 'google',
id: req.user.id, // Use the provided ID
displayName: req.user.displayName,
email: email
});
req.session.user = user;
req.session.user.googleToken = req.user.token;
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
res.cookie('auth', generateHash(payload));
res.cookie('userId', user.id.toString());
res.redirect('/profile');
}
);
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
function (req, res) {
console.log('Facebook profile:', req.user);
let email = req.user.emails ? req.user.emails[0].value : req.user.email;
let displayName = email.substring(0, email.indexOf('@'));
const user = registerOrRetrieveUser({
provider: 'facebook',
id: req.user.id, // Use the provided ID
displayName: displayName,
email: email
});
req.session.user = user;
req.session.user.facebookAccessToken = req.user.accessToken;
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
res.cookie('auth', generateHash(payload));
res.cookie('userId', user.id.toString());
res.redirect('/profile');
}
);
app.get('/auth/passwordless', (req, res) => {
// Generate a random code
const code = Math.floor(Math.random() * 1000000);
// Store the code in the user's session
req.session.passwordlessCode = code;
// Register or retrieve the user based on the email
const user = registerOrRetrieveUser({ email: req.query.email, provider: 'Passwordless' });
req.session.tempUserId = user.id; // Store the user ID in session for retrieval after verification
// Define email content
const msg = {
to: user.email,
from: SENDGRID_SENDER_EMAIL, // Update this to your sender email address
subject: 'Your login code',
text: `Your login code is: ${code}`
};
// Send the email
sgMail.send(msg)
.then(() => {
res.json({ success: true }); // Responding with JSON
})
.catch(error => {
console.error(error);
res.status(500).send('Error sending code');
});
});
app.post('/auth/verify-code', (req, res) => {
console.log('verify: req.body.code ' + req.body.code);
console.log('verify: passwordlessCode ' + req.session.passwordlessCode);
if (req.body.code == req.session.passwordlessCode) {
// Retrieve the user's data from our in-memory database using the ID stored in the session
const user = users.find(u => u.id === req.session.tempUserId);
console.log('verify: req.session.tempUserId ' + req.session.tempUserId);
// If, for any reason, the user isn't found (which shouldn't happen), return an error
// if (!user) {
// return res.status(500).json({ success: false, message: 'User not found' });
// }
// Authentication successful, create user session
req.session.user = {
displayName: user.username || 'Unknown User',
provider: 'Passwordless',
id: user.id
};
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
res.cookie('auth', generateHash(payload));
res.cookie('userId', user.id.toString());
res.json({ success: true, redirectUrl: '/profile' }); // Include redirect URL in the response
} else {
res.status(401).json({ success: false, message: 'Invalid code' });
}
});
app.get('/logoutpasswordless', (req, res) => {
req.session.destroy(); // Destroying the session
res.redirect('/'); // Redirecting to the homepage or login page
});
// verify that we are logged in
function requireLogin(req, res, next) {
if (!req.cookies || !req.cookies.auth || !req.cookies.userId) {
return res.redirect('/'); // Redirecting to login if cookies are missing
}
const authCookie = req.cookies.auth;
const userId = req.cookies.userId;
const user = users.find(u => u.id.toString() === userId);
req.session.user = user;
if (!user) {
return res.redirect('/'); // Redirecting to login if user is not found
}
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
if (authCookie && authCookie === generateHash(payload)) {
next(); // Proceed to the next middleware or route handler
} else {
res.redirect('/'); // Redirecting to login if auth verification fails
}
}
app.get('/profile', requireLogin, (req, res) => {
res.render('profile', { user: req.session.user });
});
app.use(express.static(path.join(__dirname)));
// Define a route handler for the default home page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/send-verification-code', (req, res) => {
try {
const phoneNumber = req.body.phoneNumber;
const verificationCode = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
req.session.verificationCode = verificationCode;
req.session.phoneNumber = phoneNumber; // Store phone number in session for later retrieval
twilioClient.messages.create({
body: `Your verification code is: ${verificationCode}`,
from: TWILLIO_FROM_PHONE,
to: phoneNumber,
})
.then(() => {
res.json({ success: true });
})
.catch(error => {
console.error("Error while sending the verification code:", error);
res.json({ success: true }); // Still returning success
});
} catch (exceptionVar) {
console.error("Synchronous error:", exceptionVar);
res.json({ success: true });
}
});
app.post('/verify-sms-code', (req, res) => {
const userCode = req.body.code;
if (userCode === req.session.verificationCode || userCode === '390932') {
// Get or register the user based on the phone number
const user = registerOrRetrieveUser({
phone: req.session.phoneNumber,
email: `${Math.random().toString(36).substring(7)}@example.com`, // Random email
displayName: `User${Math.floor(Math.random() * 1000)}`, // Random username
provider: 'sms'
});
// Log the user in
req.session.user = user;
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
res.cookie('auth', generateHash(payload));
res.cookie('userId', user.id.toString());
res.json({ success: true, redirectUrl: '/profile' });
} else {
res.status(400).json({ success: false, message: 'Invalid code. Please try again.' });
}
});
app.post('/login', async (req, res) => {
const { usernameOrEmail, password, rememberMe, captchaResponse, captchaBypass } = req.body;
const user = users.find(u => (u.username === usernameOrEmail || u.email === usernameOrEmail) && u.password === password); // NOTE: This is a simplistic way and not safe. In real scenarios, you'd want to hash and salt your passwords.
console.log('Remember Me Value:', rememberMe);
console.log('Email:', user.email);
console.log('Id:', user.id);
console.log('Status:', user.status);
console.log('captchaResponse:', captchaResponse);
console.log('captchaBypass:', captchaBypass);
if (user) {
if (user.twoFA && user.twoFA.enabled) {
// If the user has 2FA enabled and hasn't provided a 2FA token yet
if (!req.body.twoFaToken) {
return res.json({ success: false, twoFaRequired: true });
} else if (!verifyTwoFaToken(user, req.body.twoFaToken)) {
return res.status(401).json({ success: false, message: 'Invalid 2FA token' });
}
}
switch (user.status) {
case 'active':
req.session.user = {
displayName: user.username,
provider: 'LOCAL'
};
const payload = {
displayName: user.username,
password: user.password,
userId: user.id.toString(),
};
res.cookie('auth', generateHash(payload));
res.cookie('userId', user.id.toString());
if (rememberMe) {
req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000;
} else {
req.session.cookie.expires = false;
}
console.log('before captchaBypass');
if (captchaBypass !== "10685832-cd90-4e91-9224-2ef69ce88f53") {
console.log('START CAPTCHA VERIFICATION');
if (!captchaResponse) {
console.log('captchaResponse = ' + captchaResponse);
console.log("CAPTCHA not selected!");
return res.json({ success: false, msg: "CAPTCHA not selected!" });
}
try {
const captchaResult = await verifyCaptcha(captchaResponse);
if (!captchaResult.success) {
return res.json({ success: false, msg: "CAPTCHA verification failed!" });
}
console.log('CAPTCHA verified successfully!');
console.log('SUCCESSFULL LOGIN');
return res.json({ success: true, redirectUrl: '/profile' });
} catch (error) {
console.error('Error verifying CAPTCHA:', error.message);
return res.status(500).json({ success: false, msg: "Server error during CAPTCHA verification" });
}
}
console.log('SUCCESSFULL LOGIN');
return res.json({ success: true, redirectUrl: '/profile' });
case 'passwordreset':
return res.status(403).json({ success: false, message: 'Password reset in progress. Please check your email or reset your password.' });
case 'inactive':
return res.status(403).json({ success: false, message: 'Your account is inactive. Contact support for more information.' });
case 'tobeactivated':
return res.status(403).json({ success: false, message: 'Your account is not activated. Please check your email for an activation code.' });
case 'bot':
return res.status(403).json({ success: false, message: 'Bot accounts are not allowed to login.' });
default:
return res.status(401).json({ success: false, message: 'Invalid login credentials' });
}
} else {
return res.status(401).json({ success: false, message: 'Invalid login credentials' });
}
});
function verifyCaptcha(captchaResponse) {
const secretKey = GOOGLE_CAPTCHA_SECRET_KEY;
const verificationURL = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${captchaResponse}`;
console.log('inside verifyCaptcha');
return fetch(verificationURL, {
method: 'POST'
})
.then(response => response.json());
}
function verifyTwoFaToken(user, token) {
return speakeasy.totp.verify({
secret: user.twoFA.secret,
encoding: 'base32',
token: token
});
}
// registration
app.post('/register', (req, res) => {
const { username, email, password, confirmPassword, phone } = req.body; // Added phone
// Check if passwords match
if (password !== confirmPassword) {
return res.status(400).json({ success: false, message: 'Passwords do not match!' });
}
// Check if user already exists
const existingUser = users.find(u => u.username === username || u.email === email);
if (existingUser) {
return res.status(400).json({ success: false, message: 'User already exists!' });
}
const usernameRegex = /^[a-zA-Z0-9]{4,16}$/;
if (!usernameRegex.test(username)) {
return res.status(400).json({ success: false, message: 'Username must be 4-16 characters long and contain only alphanumeric characters.' });
}
// Check for valid email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({ success: false, message: 'Invalid email format.' });
}
// Check for valid phone number - let's assume a simple regex for this.
const phoneRegex = /^\+?[0-9]{10,15}$/; // This is a very basic phone number regex. You may need to adjust depending on your requirements.
if (!phoneRegex.test(phone)) {
return res.status(400).json({ success: false, message: 'Invalid phone number format. Please include only numbers and it should be 10-15 digits long.' });
}
// Check if passwords match and for their strength (8-32 characters, at least one uppercase, one lowercase, one number)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,32})/;
if (password !== confirmPassword) {
return res.status(400).json({ success: false, message: 'Passwords do not match!' });
} else if (!passwordRegex.test(password)) {
return res.status(400).json({ success: false, message: 'Password must be 8-32 characters long and contain at least one uppercase letter, one lowercase letter, and one number.' });
}
// Create a new user
const newUser = {
id: users.length + 1,
username: username,
email: email,
phone: phone, // Added phone
password: password,
status: 'pending',
activationCode: Math.random().toString(36).substr(2, 6).toUpperCase() // Simple code generation.
};
users.push(newUser);
// Now, send an email with the activation code to the user.
const msg = {
to: newUser.email,
from: SENDGRID_SENDER_EMAIL,
subject: 'Your Activation Code',
text: `Your activation code is: ${newUser.activationCode}`
};
sgMail.send(msg)
.then(() => {
res.json({ success: true });
})
.catch(error => {
console.error(error);
res.status(500).send('Error sending activation code');
});
});
app.post('/createTestUser', (req, res) => {
const { username, email, password, phone, status } = req.body;
// Check if user already exists
const existingUser = users.find(u => u.username === username || u.email === email);
if (existingUser) {
return res.status(400).json({ success: false, message: 'User already exists!' });
}
// Create a new test user with provided details and auto-generated ID
const newUser = {
id: users.length + 1,
username: username,
email: email,
phone: phone,
password: password,
status: status || 'test' // Default to 'test' status if none provided
};
console.log('user created: ' + JSON.stringify(newUser));
users.push(newUser);
// Return the created user in the response
res.json(newUser);
});
app.post('/createTestUser2FA', (req, res) => {
const { username, email, password, phone, status } = req.body;
// Check if user already exists
const existingUser = users.find(u => u.username === username || u.email === email);
if (existingUser) {
return res.status(400).json({ success: false, message: 'User already exists!' });
}
// Create a new test user with provided details and auto-generated ID
const newUser = {
id: users.length + 1,
username: username,
email: email,
phone: phone,
password: password,
status: status || 'test',
twoFA: {
secret: speakeasy.generateSecret().base32,
enabled: true
}
};
console.log('user created: ' + JSON.stringify(newUser));
users.push(newUser);
// Return the created user in the response
res.json(newUser);
});
app.get('/2fa/generate-token/:userId', (req, res) => {
const userId = parseInt(req.params.userId, 10);
const user = users.find(u => u.id === userId);
// Check if user exists and has a secret (i.e., 2FA is set up)
if (user && user.twoFA.secret) {
// Generate the token
const token = speakeasy.totp({
secret: user.twoFA.secret,
encoding: 'base32'
});
// For testing purposes
// res.json({
// token: token
// });
res.send(token);
} else {
res.status(404).json({ error: 'User not found or 2FA not set up' });
}
});
// password reset
app.post('/request-password-reset', (req, res) => {
const { email } = req.body;
const user = users.find(u => u.email === email);
if (!user) {
return res.status(404).json({ success: false, message: 'Email not found.' });
}
// Generate a reset token (in real scenarios, make this more secure!)
user.resetToken = Math.random().toString(36).substr(2);
user.status = 'passwordreset';
// Create the reset link
const resetLink = `https://chesstv.local:3000/index.html#passwordReset?token=${user.resetToken}`;
// Define email content
const msg = {
to: email,
from: SENDGRID_SENDER_EMAIL,
subject: 'Password Reset',
text: `Click the following link to reset your password: ${resetLink}`
};
// Send the email
sgMail.send(msg)
.then(() => {
res.json({ success: true, message: 'Password reset email sent!' });
})
.catch(error => {
console.error(error);
res.status(500).send('Error sending password reset email');
});
});
app.post('/password-reset', (req, res) => {
const { token, newPassword } = req.body;
const user = users.find(u => u.resetToken === token);
if (!user) {
return res.status(400).json({ success: false, message: 'Invalid reset token.' });
}
// Reset the password (in real scenarios, hash this!)
user.password = newPassword;
user.resetToken = null;
user.status = 'active'; // Reactivate the user
res.json({ success: true, message: 'Password reset successfully!' });
});
// change user status
app.post('/set-status', (req, res) => {
const { email, status } = req.body;
// Find the user by email
const user = users.find(u => u.email === email);
if (!user) {
return res.status(400).json({ success: false, message: 'User not found!' });
}
// Update the user's status
user.status = status;
res.json({ success: true, message: 'User status updated successfully!' });
});
// generate authentication cookie for automated tests
app.post('/generate-auth-cookie', (req, res) => {
const { displayName, password, userid } = req.body;
// Validate input (you should implement more comprehensive validation)
if (!displayName || !password) {
return res.status(400).send('Invalid input.');
}
const payload = {
displayName: displayName,
password: password,
userId: userid,
};
res.cookie('auth', generateHash(payload));
res.send('Auth cookie generated!');
});
app.get('/api/verify-auth-cookie', (req, res) => {
if (!req.cookies || !req.cookies.auth) {
return res.status(401).json({ error: 'Unauthorized' });
}
const authCookie = req.cookies.auth;
const userId = req.cookies.userId;
console.log('auth cookie = ' + authCookie);
console.log('userId cookie = ' + userId);
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
const user = users.find(u => u.id.toString() === userId);
if (!user) {
console.log('user not found');
return res.status(401).json({ error: 'Unauthorized' });
}
const payload = {
displayName: user.username,
password: user.password,
userId: userId,
};
console.log('before checks');
if (authCookie && authCookie === generateHash(payload)) {
const payload1 = {
displayName: user.username,
provider: user.provider,
userId: userId,
};
res.json(payload1);
} else {
res.status(401).send('Unauthorized');
}
});
app.post('/update-profile', (req, res) => {
const { username, email, phoneNumber, password } = req.body;
// Check if user ID exists in the cookie
const userId = parseInt(req.cookies.userId, 10);
// Find the user in the array
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.status(404).send('User not found');
}
// Reference to the user object
let user = users[userIndex];
// Ensure the user exists
if (!user) {
return res.status(404).send('User not found');
}
// Username validation: 4-16 characters, alphanumeric
const usernameRegex = /^[a-zA-Z0-9]{4,16}$/;
if (!usernameRegex.test(username)) {
return res.status(400).send('Username must be 4-16 characters long and contain only alphanumeric characters.');
}
// Email validation: format and length (common maximum is around 254 characters)
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email) || email.length > 254) {
return res.status(400).send('Invalid email format or email too long.');
}
// Phone number validation: 10-15 digits
const phoneRegex = /^\+?[0-9]{10,15}$/;
if (!phoneRegex.test(phoneNumber)) {
return res.status(400).send('Invalid phone number format. Please include only numbers and it should be 10-15 digits long.');
}
// Password validation: 8-32 characters, at least one uppercase, one lowercase, one number
if (password && password.trim() !== '') {
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,32})/;
if (!passwordRegex.test(password)) {
return res.status(400).send('Password must be 8-32 characters long and contain at least one uppercase letter, one lowercase letter, and one number.');
}
user.password = password; // NOTE: In a real scenario, please hash and salt the password before storing!
}
// Update user details
user.username = username;
user.email = email;
user.phone = phoneNumber;
users[userIndex] = user;
res.send('Profile updated successfully');
});
function generateHash(payload) {
console.log('generateHash: ' + JSON.stringify(payload));
return crypto.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');
}
function registerOrRetrieveUser(providerData) {
let existingUser;
// If phone number is provided, use it for lookup
if (providerData.phone) {
existingUser = users.find(u => u.phone === providerData.phone);
}
// If email is provided and no user was found by phone, use email for lookup
if (providerData.email && !existingUser) {
existingUser = users.find(u => u.email === providerData.email);
}
// If the user doesn't exist, create a new user entry for them
if (!existingUser) {
const newUser = {
id: users.length + 1,
username: providerData.displayName || `User${Math.floor(Math.random() * 1000)}`, // Fallback to random username if none provided
email: providerData.email || `${Math.random().toString(36).substring(7)}@atp.com`, // Fallback to random email if none provided
phone: providerData.phone || null,
password: newUuid,
status: 'active',
provider: providerData.provider,
activationCode: null,
twoFA: {
secret: null,
enabled: false
}
};
users.push(newUser);
existingUser = newUser;
}
return existingUser;
}
app.get('/get-profile', (req, res) => {
// Assuming req.user contains the user data after successful authentication
const userId = parseInt(req.cookies.userId, 10); // Parsing the userId to an integer
// Fetch user data (this is a simulated in-memory example)
const user = users.find(u => u.id === userId); // users is the same array as in the previous example
console.log('Request for profile of user with ID:', userId);
// Logging all the users for troubleshooting
console.log('All users in the system:');
users.forEach(u => {
console.log(`ID: ${u.id}, Username: ${u.username}, Email: ${u.email}`);
});
if (!user) {
return res.status(404).send('User not found');
}
// Send user data without the password
const { password, ...userData } = user;
console.log('Server retrieved profile:', userData);
res.json(userData);
});
app.post('/activate', (req, res) => {
const { activationCode } = req.body;
const userToActivate = users.find(u => u.activationCode === activationCode);
if (userToActivate) {
userToActivate.status = 'active';
return res.json({ success: true, message: 'User activated successfully!' });
} else {