-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
708 lines (608 loc) · 22 KB
/
index.js
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
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');
const app = express();
const port = 3000;
var favicon = require('serve-favicon');
const sqlite3 = require('sqlite3').verbose();
const nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail', // use 'gmail' as an example, you can use other services
auth: {
user: 'teamsynthia@gmail.com', // your email
pass: 'kjih rrxd gdmw ycht' // your email password
}
});
// Cookie Configuration Start
app.use(cookieParser());
// Cookie Configuration End
// Database Configuration Start
const db = new sqlite3.Database('synthia.db');
db.serialize(() => {
console.log('Database Connected Successfully :)');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Database Configuration End
// Static Files Start
app.use(express.static(path.join(__dirname, 'public')));
// Static Files End
// Favicon Start
app.use(favicon(path.join(__dirname, 'public', 'assets', 'favicon.png')));
// Favicon End
// URL Routes Start
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/login', function(req, res) {
if (req.cookies.email) {
res.redirect('/chat');
} else {
res.sendFile(path.join(__dirname, 'public', 'login.html'));
}
});
app.get('/register', function(req, res) {
if (req.cookies.email) {
res.redirect('/chat');
} else {
res.sendFile(path.join(__dirname, 'public', 'register.html'));
}
});
app.get('/chat', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'chat.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/entertainment', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'entertainment.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
// Games Routes Start
app.get('/games', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/bullseye', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'bullseye.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/catjumper', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'catjumper.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/clickonthecircle', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'clickonthecircle.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/cubnpup', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'cubnpup.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/minesweeper', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'minesweeper.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/remembercard', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'remembercard.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/rockpaperscissors', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'rockpaperscissors.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/snakesandladders', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'snakesandladders.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/thecube', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'thecube.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/tictactoe', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'tictactoe.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/tiltingmaze', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'tiltingmaze.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/games/towerblocks', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'games', 'towerblocks.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
// Games Routes End
app.get('/resources', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'resources.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
app.get('/help', function(req, res) {
res.sendFile(path.join(__dirname, 'public', 'help.html'));
});
app.get('/settings', function(req, res) {
if (req.cookies.email) {
res.sendFile(path.join(__dirname, 'public', 'settings.html'));
} else {
res.sendFile(path.join(__dirname, 'public', 'noaccess.html'));
}
});
// URL Routes End
// Register User Start
app.post('/userRegister', (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
const timestamp = new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear() + ' ' + new Date().toTimeString().slice(0, 5);
if (password === confirmPassword) {
// Check if email already exists in the database
db.get('SELECT email FROM users WHERE email = ?', [email], (err, row) => {
if (err) {
console.error('Error querying database:', err.message);
res.status(500).send('Error querying database :(');
return;
}
if (row) {
// If the SELECT statement returned a row, the email already exists
console.error('Email already exists');
res.status(500).send(`<script>alert('Email already exists'); window.history.back();</script>`);
return;
}
// If the SELECT statement didn't return a row, the email doesn't exist and we can insert the new user
db.run('INSERT INTO users (name, email, password, timestamp) VALUES (?, ?, ?, ?)', [name, email, password, timestamp], (err) => {
if (err) {
console.error('Error Saving Data To Database:', err.message);
res.status(500).send('Error Saving Data To Database :(');
return;
}
console.log('Data Saved To Database :)');
// HTML To Display Thanks & Submitted Data To User
let userRegisterHtml = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome | Synthia</title>
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:ital,opsz,wght@0,6..12,300;0,6..12,400;0,6..12,500;0,6..12,600;0,6..12,700;1,6..12,300;1,6..12,400;1,6..12,500;1,6..12,600;1,6..12,700&display=swap" rel="stylesheet">
<script src="/js/script.js" defer></script>
<!-- Preload CSS -->
<link rel="preload" href="/css/style.css" as="style" type="text/css">
<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" as="style" type="text/css" crossorigin>
<!-- Preload JS -->
<link rel="preload" href="/js/script.js" as="script" type="text/javascript">
<link rel="preload" href="/js/menubar.js" as="script" type="text/javascript">
<link rel="preload" href="/js/navmenu.js" as="script" type="text/javascript">
<!-- Prefetch HTML -->
<link rel="prefetch" href="index.html" as="document">
<link rel="prefetch" href="chat.html" as="document">
<link rel="prefetch" href="entertainment.html" as="document">
<link rel="prefetch" href="games.html" as="document">
<link rel="prefetch" href="resources.html" as="document">
<link rel="prefetch" href="settings.html" as="document">
<link rel="prefetch" href="help.html" as="document">
</head>
<body>
<div class="flex flexCol" style="height: 100vh; width: 100%; position: fixed; top: 0; align-items: center; justify-content: center;">
<!-- MENUBAR START =====================================================================-->
<div id="menubar"></div>
<script src="/js/menubar.js"></script>
<!--======================================================================= MENUBAR END -->
<!-- PAGE CONTENT START ================================================================-->
<div class="flex" style="height: calc(100% - 70px); width: 100%; align-items: center; justify-content: center;">
<span class="flex flexCol" style="align-items: center; justify-content: center; gap: 50px;">
<div style="height: 300px; width: 700px;">
<img src="/assets/images/welcome.jpg" alt="Welcome" style="width: 100%; height: 100%; border-radius: 10px; object-fit: cover; object-position: center;">
</div>
<span class="flex flexCol" style="align-items: center; gap: 15px;">
<h1><span style="color: var(--accent);">Welcome</span> ${name.split(' ')[0]}!</h1>
<p>You're just one step away from accessing all the features of Synthia. Login to your account to get started.</p>
</span>
<button style="background: var(--accent);" onclick="window.location.href='/login'">Login Now</button>
</span>
</div>
<!--================================================================== PAGE CONTENT END -->
</div>
</body>
</html>
`;
res.send(userRegisterHtml);
// after user is registered
let mailOptions = {
from: 'teamsynthia@gmail.com', // sender address
to: email, // list of receivers
subject: 'Welcome to Synthia', // Subject line
text: 'Thank you for registering ' + name.split(' ')[0] + '.', // plain text body
html: `
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
color: #333;
}
a {
color: #4CAF50;
text-decoration: none;
}
a:hover {
color: #3e8e41;
}
.container {
padding: 20px;
max-width: 600px;
margin: 0 auto;
border-radius: 5px;
background-color: #f2f2f2;
}
.header {
text-align: center;
}
.content {
padding: 20px;
}
.footer {
text-align: center;
padding: 10px;
background-color: #ddd;
}
</style>
<div class="container">
<div class="header">
<h1>Welcome to Synthia, ${name.split(' ')[0]}!</h1>
</div>
<div class="content">
<p>We're thrilled to have you join us on your journey to mental well-being. Here at Synthia, we understand that mental health is just as important as physical health.</p>
<p>That's why we offer a variety of resources and tools to help you manage stress, improve your mood, and build resilience. Explore what we have to offer:</p>
<ul>
<li><b>AI Chatbot:</b> Feeling overwhelmed and need someone to talk to? Our friendly AI chatbot is available 24/7 to listen without judgment and offer support.</li>
<li><b>Entertainment:</b> Take a break and unwind with our curated selection of music genres.</li>
<li><b>Games:</b> Engage in fun and interactive games designed to reduce stress, improve focus, and promote positive thinking.</li>
<li><b>Resources:</b> Find valuable information, articles, and exercises on a wide range of mental health topics.</li>
</ul>
<p>We're constantly adding new features and content, so be sure to check back often!</p>
<h2>Getting Started</h2>
<p>For a seamless experience, we recommend creating a profile. This allows you to personalize your experience, track your progress, and access exclusive features. You can create your profile by logging in to your account.</p>
<h2>Stay Connected</h2>
<p>Follow us on social media for daily inspiration and updates:</p>
<ul>
<li><a href="">Link 1</a></li>
<li><a href="">Link 2</a></li>
</ul>
<p>If you have any questions or suggestions, please don't hesitate to contact us at <a href="mailto:teamsynthia@gmail.com">teamsynthia@gmail.com</a>.</p>
<p>We're here to support you on your path to mental well-being.</p>
<p>Warmly,</p>
<p>Synthia Team</p>
</div>
<div class="footer">
<p>© 2024 Synthia</p>
</div>
</div>
</body>
</html>
` // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
});
});
} else {
console.error('Password and Confirm Password do not match');
res.status(500).send(`<script>alert('Password and Confirm Password do not match'); window.history.back();</script>`);
return;
}
});
// Register User End
// Login User Start
app.post('/userLogin', (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.get('SELECT * FROM users WHERE email = ?', [email], (err, row) => {
if (err) {
console.error(err.message);
res.status(500).send('Error Fetching Data From Database :(');
return;
}
if (row) {
if (password === row.password) {
console.log('Login Successful :)');
res.cookie('userid', row.id, {
maxAge: 1000 * 60 * 60 * 24 * 30, // Expires in 30 days
httpOnly: true, // Only accessible by the server
secure: false // Only sent over HTTPS
});
console.log('User ID Cookie Set Successfully');
res.cookie('email', email, {
maxAge: 1000 * 60 * 60 * 24 * 30, // Expires in 30 days
httpOnly: true, // Only accessible by the server
secure: false // Only sent over HTTPS
});
console.log('Email Cookie Set Successfully');
res.cookie('name', row.name, { // Save the name of the user from the database
maxAge: 1000 * 60 * 60 * 24 * 30, // Expires in 30 days
httpOnly: true, // Only accessible by the server
secure: false // Only sent over HTTPS
});
console.log('Name Cookie Set Successfully');
res.redirect('/chat');
} else {
console.error('Invalid Password :(');
res.status(500).send(`<script>alert('Invalid Password :('); window.history.back();</script>`);
}
} else {
console.error('Invalid Email :(');
res.status(500).send(`<script>alert('Invalid Email :('); window.history.back();</script>`);
}
});
});
// Login User End
// Loggedin User Info Endpoint Start
app.get('/api/loggedin-userinfo', (req, res) => {
const userInfo = {
userid: req.cookies.userid,
email: req.cookies.email,
name: req.cookies.name
};
res.json(userInfo);
});
// Loggedin User Info Endpoint End
// Update Username Start
app.post('/api/updateusername', (req, res) => {
const id = req.cookies.userid;
const newName = req.body.newName;
db.run('UPDATE users SET name = ? WHERE id = ?', [newName, id], (err) => {
if (err) {
console.error(err.message);
res.json({ success: false });
} else {
res.cookie('name', newName, { // Save the name of the user from the database
maxAge: 1000 * 60 * 60 * 24 * 30, // Expires in 30 days
httpOnly: true, // Only accessible by the server
secure: false // Only sent over HTTPS
});
console.log('Name Updated Successfully\nNew Name: ' + newName);
res.json({ success: true });
}
});
});
// Update Username End
// Update Email Start
app.post('/api/updateuseremail', (req, res) => {
const id = req.cookies.userid;
const newEmail = req.body.newEmail;
db.run('UPDATE users SET email = ? WHERE id = ?', [newEmail, id], (err) => {
if (err) {
console.error(err.message);
res.json({ success: false });
} else {
res.cookie('email', newEmail, { // Save the email of the user from the database
maxAge: 1000 * 60 * 60 * 24 * 30, // Expires in 30 days
httpOnly: true, // Only accessible by the server
secure: false // Only sent over HTTPS
});
console.log('Email Updated Successfully\nNew Email: ' + newEmail);
res.json({ success: true });
}
});
});
// Update Email End
// Update Password Start
app.post('/api/updateuserpassword', (req, res) => {
const id = req.cookies.userid;
const newPassword = req.body.newPassword;
const name = req.cookies.name;
const email = req.cookies.email;
db.run('UPDATE users SET password = ? WHERE id = ?', [newPassword, id], (err) => {
if (err) {
console.error(err.message);
res.json({ success: false });
} else {
console.log('Password Updated Successfully\nNew Password: ' + newPassword);
// after password is updated
let mailOptions = {
from: 'teamsynthia@gmail.com', // sender address
to: email, // list of receivers
subject: 'Your Password Has Been Updated', // Subject line
text: 'Your password has been updated.', // plain text body
html: `
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
color: #333;
}
a {
color: #4CAF50;
text-decoration: none;
}
a:hover {
color: #3e8e41;
}
.container {
padding: 20px;
max-width: 600px;
margin: 0 auto;
border-radius: 5px;
background-color: #f2f2f2;
}
.content {
padding: 20px;
}
</style>
<div class="container">
<div class="content">
<p>Hi ${name.split(' ')[0]},</p>
<p>This email confirms that your password for your account on Synthia has been successfully updated.</p>
<p>**Important:** For your security, we cannot disclose your new password in this email. We recommend you choose a strong password that is unique to Synthia and not used for any other online accounts.</p>
<p>If you did not request this password update, please contact us immediately at <a href="mailto:teamsynthia@gmail.com">teamsynthia@gmail.com</a> to ensure the security of your account.</p>
<p>Thanks,</p>
<p>The Synthia Team</p>
</div>
</div>
</body>
</html>
` // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
res.json({ success: true });
}
});
});
// Update Password End
// Logout User Start
app.get('/logout', (req, res) => {
function removeCookies() {
res.clearCookie('userid');
console.log('User ID Cookie Cleared');
res.clearCookie('email');
console.log('Email Cookie Cleared');
res.clearCookie('name');
console.log('Name Cookie Cleared');
}
removeCookies();
res.redirect('/login');
});
// Logout User End
// Get Users Start
app.get('/api/getUsers', (req, res) => {
db.all('SELECT * FROM users', (err, rows) => {
if (err) {
console.error(err.message);
}
res.json(rows);
});
});
// Get Users End
// Get Entertainment Start
app.get('/api/getEntertainment', function(req, res) {
db.all('SELECT * FROM entertainment ORDER BY title ASC', (err, rows) => {
if (err) {
console.error(err.message);
}
res.json(rows);
});
});
// Get Entertainment End
// Get Games Start
app.get('/api/getGames', function(req, res) {
db.all('SELECT * FROM games ORDER BY title ASC', (err, rows) => {
if (err) {
console.error(err.message);
}
res.json(rows);
});
});
// Get Games End
// Get Resources Start
app.get('/api/getResources', function(req, res) {
db.all('SELECT * FROM resources ORDER BY title ASC', (err, rows) => {
if (err) {
console.error(err.message);
}
res.json(rows);
});
});
// Get Resources End
// Get Resource Start
app.get('/resources/:url', function(req, res) {
const url = req.params.url;
db.get('SELECT * FROM resources WHERE url = ?', [url], (err, row) => {
if (err) {
console.error(err.message);
res.status(500).send(err.message);
} else if (row) {
res.sendFile(path.join(__dirname, 'public', 'resources', row.url + '.html'));
} else {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
}
});
});
// Get Resource End
// Error Handling Start
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});
// Error Handling End
// Port Configuration Start
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
// Port Configuration End