forked from KianAzizkhani/2800-202210-BBY31
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
1722 lines (1607 loc) · 49.7 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
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
/**
* Dependencies.
*/
const express = require("express");
const path = require('path');
const session = require('express-session');
const User = require("./models/BBY_31_users");
const Chat = require("./models/BBY_31_messages");
const Cart = require("./models/BBY_31_shoppingCarts");
const mongoose = require("mongoose");
const multer = require("multer");
const bcrypt = require('bcrypt');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {
Server
} = require("socket.io");
const io = new Server(server);
const nodemailer = require('nodemailer');
/**
* MangoDB connection.
*/
if (process.env.NODE_ENV != 'production') {
require('dotenv').config()
}
mongoose.set('strictQuery', false);
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => console.log(err));
/**
* Middlewares to set up view engine.
*/
app.set('view engine', 'text/html');
app.use(express.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
app.use(session({
secret: "password",
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 10800000
}
}));
//Custom middleware functions
/**
* This function checks to see if a user is logged in.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns next if user is logged in or redirects to login page.
*/
function isLoggedIn(req, res, next) {
if (req.session.isLoggedIn) {
return next();
} else {
return res.redirect('/login');
}
}
/**
*
* This function checks to see if a user is logged out.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns next if user is logged out or redirects to userprofile page.
*/
function isLoggedOut(req, res, next) {
if (!req.session.isLoggedIn) {
return next();
} else {
return res.redirect('/userprofile');
}
}
/**
*
* This function checks to see if a user is an administrator.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns returns to login page if user is not logged in, next if user is administrator,
* or returns to home page if user is not admin AND is logged in.
*/
function isAdmin(req, res, next) {
let userId = req.session.user._id;
User.findById({
_id: userId
}, function (err, user) {
if (err) console.log(err)
else if (!user) {
return res.redirect('/login')
}
if (user.userType == 'admin') {
return next();
} else {
return res.redirect('/userprofile');
}
})
}
/**
*
* This function stops the browsers from storing protected pages on cache
* -User cannot backspace to previous page if page is protected(Eg. not logged in).
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns calls next middleware function.
*/
function setHeaders(req, res, next) {
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setHeader("Expires", "0"); // Proxies.
return next();
}
/**
*
* This function checks to see if a user has recently purchased a session within the last three minutes
* This function helps with displaying a thank-you page upon purchase.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns next if a user has recently placed an order or redirects to home page.
*/
async function hasRecentlyPurchased(req, res, next) {
//If a purchase was made in the last 3 mins, render thank-you page
var currentTime = new Date();
var nowMinus3Mins = new Date(currentTime.getTime() - 3 * 60000);
var recentOrderExists = await Cart.exists({
userId: req.session.user._id,
status: "completed",
purchased: {
$gt: nowMinus3Mins
}
})
if (recentOrderExists) {
return next();
} else {
return res.redirect('/');
}
}
/**
*
* This function checks to see if a user has an active session with a therapist.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns next if a user has an active session or redirects to home page.
*/
async function hasActiveSession(req, res, next) {
var currentTime = new Date();
var patientActiveSession = await Cart.exists({
$or: [{
therapist: req.session.user._id
}, {
userId: req.session.user._id
}],
status: "completed",
expiringTime: {
$gt: currentTime
}
})
if (patientActiveSession) {
return next();
} else {
return res.redirect('/');
}
}
/**
*
* Since therapist and patients have a one-to-one relationship, this function checks to see if a therapist is available.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns if a therapist has an active session with another user it will return an error message, else it will
* return next.
*/
async function isTherapistAvailable(req, res, next) {
var currentTime = new Date();
let orderExists = await Cart.exists({
therapist: req.body.therapistID,
status: "completed",
expiringTime: {
$gt: currentTime
}
})
if (orderExists) {
return res.json({
errorMsg: "Therapist is currently busy. Please delete him from your cart or wait until they become available again."
});
} else {
return next();
}
}
/**
*
* This function checks to see if the logged in user is a patient
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns next if the user is a patient, else redirects to home page.
*/
function isPatient(req, res, next) {
if (req.session.user.userType == 'patient') {
return next();
}
return res.redirect('/');
}
//Routes
/**
* This get route renders the home (index.html) page.
*/
app.get('/', function (req, res) {
res.sendFile(path.resolve('html/index.html'));
});
/**
* This get route renders the therapist.html page.
*/
app.get('/therapists', function (req, res) {
res.sendFile(path.resolve('html/therapists.html'));
});
/**
* This get route renders the chat-session.html page.
*/
app.get('/chat-session', isLoggedIn, hasActiveSession, setHeaders, function (req, res) {
res.sendFile(path.resolve('html/chat-session.html'));
});
/**
* This get route renders the my-patient.html page.
*/
app.get('/my-patients', isLoggedIn, setHeaders, function (req, res) {
res.sendFile(path.resolve('html/my-patients.html'));
});
/**
* This get route renders the checkout.html page.
*/
app.get('/checkout', isLoggedIn, isPatient, setHeaders, function (req, res) {
res.sendFile(path.resolve('html/checkout.html'));
});
/**
* This get route renders the privacypolicy.html page.
*/
app.get('/privacypolicy', function (req, res) {
res.sendFile(path.resolve('html/privacypolicy.html'));
});
/**
* This get route renders the termsandconditions.html page.
*/
app.get('/termsandconditions', function (req, res) {
res.sendFile(path.resolve('html/termsandconditions.html'));
});
/**
* This get route renders order-history.html page.
*/
app.get('/order-history', isLoggedIn, isPatient, setHeaders, function (req, res) {
res.sendFile(path.resolve('html/order-history.html'));
});
/**
* This get route renders thank-you.html page.
*/
app.get('/thank-you', isLoggedIn, hasRecentlyPurchased, setHeaders, function (req, res) {
res.sendFile(path.resolve('html/thank-you.html'));
});
/**
* This get route renders the login.html page.
*/
app.get("/login", isLoggedOut, setHeaders, (req, res) => {
res.sendFile(path.resolve('html/login.html'));
});
/**
* This get route renders the admin-dashboard.html page.
*/
app.get('/admin-dashboard', isLoggedIn, isAdmin, setHeaders, (req, res) => {
res.sendFile(path.resolve('html/admin-dashboard.html'))
});
/**
* This get route renders userprofile.html page.
*/
app.get('/userprofile', isLoggedIn, setHeaders, (req, res) => {
res.sendFile(path.resolve('html/userprofile.html'))
})
/**
* This get route renders edit-account.html page.
*/
app.get('/edit-account', isLoggedIn, setHeaders, (req, res) => {
res.sendFile(path.resolve('html/edit-account.html'))
})
/**
* This get route renders sign-up.html page.
*/
app.get("/sign-up", isLoggedOut, setHeaders, (req, res) => {
res.sendFile(path.resolve('html/sign-up.html'))
})
/**
* This variable initializes a diskStorage for multer.
* Multer is a dependency that stores user profile images.
*/
var profileStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
}
})
var profileUpload = multer({
storage: profileStorage
})
/**
* This post route allows users to upload their profile images onto mongodb.
*/
app.post('/uploadProfile', profileUpload.single('profileFile'), (req, res) => {
if (req.file) {
var fileName = req.file.filename;
var id = req.session.user._id;
User.updateOne({
"_id": id
}, {
profileImg: "../uploads/" + fileName
}).then((obj) => {})
} else {
return;
}
});
/**
* This get route will get the uploaded images from mongodb and render them on the html.
*/
app.get('/getProfilePicture', (req, res) => {
var id = req.session.user._id;
User.findById({
_id: id
}, function (err, user) {
if (user) {
res.send(user)
}
})
})
/**
* This get route checks to see if a user is logged in.
*/
app.get('/isLoggedIn', (req, res) => {
res.send(req.session.user);
})
/**
* This get route finds the user by their id from the database and returns
* the user and their information as an object.
*/
app.get('/getUserInfo', isLoggedIn, setHeaders, (req, res) => {
let userId = req.session.user._id;
User.findById({
_id: userId,
}, function (err, user) {
if (err) console.log(err)
if (user) {
res.json(user);
}
})
})
/**
* This post route finds a patient by their id from the database and returns
* the patient and their information as an object.
*/
app.post('/getPatientInfo', isLoggedIn, setHeaders, (req, res) => {
let userId = req.body._id
User.findById({
_id: userId,
}, function (err, user) {
if (err) console.log(err)
if (user) {
res.json(user);
}
})
})
/**
*
* This helper function for /getTherapists checks to see if a therapist has an active session with another user.
*
* @param {*} therapistInfo as therapist id
* @returns true if therapist has an active session OR false if they don't.
*/
async function therapistHasActiveSession(therapistInfo) {
var currentTime = new Date();
let orderExists = await Cart.exists({
therapist: therapistInfo._id,
status: "completed",
expiringTime: {
$gt: currentTime
}
})
if (orderExists) {
return true;
} else {
return false
}
}
/**
* This get route looks for all users with the type "therapist" and returns
* the therapist that do not have an active session as an array.
*/
app.get('/getTherapists', (req, res) => {
User.find({
userType: "therapist"
}, async function (err, user) {
if (err) console.log(err)
if (user) {
var existingSession;
for (let i = 0; i < user.length; i++) {
existingSession = await therapistHasActiveSession(user[i])
if (existingSession) {
user.splice(i, 1);
}
}
return res.json(user)
}
}).sort({
numSessions: 'desc'
})
})
/**
* This post route verifies the users email and password when logging in
* If the user has an invalid email, it will return "NoEmailExists", return
* user to login if an error occurs or calls auth (a helper function which checks the users password)
*/
app.post('/login', async (req, res) => {
User.findOne({
email: req.body.email.toLowerCase()
}, function (err, user) {
if (err) {
console.log(err);
res.redirect('/login');
}
if (!user) {
res.json("NoEmailExist");
} else {
return auth(req, res, user);
}
});
})
/**
*
* This helper function checks the users password from the database and if there is an error
* It will redirect the user to the login page, if the password is wrong, it will display an error
* message, else if password is correct it will log the user into the website and redirect them to homepage.
*
* @param {*} req
* @param {*} res
* @param {*} user
*/
function auth(req, res, user) {
bcrypt.compare(req.body.password, user.password, function (err, comp) {
if (err) {
console.log(err);
res.redirect('/login');
} else if (comp === false) {
res.json("wrongPassword");
} else {
req.session.user = user;
req.session.isLoggedIn = true;
res.json(user);
}
})
}
/**
* This post route will destory the user's session (log them out) and redirect them to login page.
*/
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) console.log(err);
});
res.redirect('/login')
})
/**
* This post route will update the user's information from the database when a user wants to
* edit their profile and change their information including their password.
* It also uses the isNotExisting helper function to help not allow
* duplicate records in the datbase (two users having the same email, etc.)
*/
app.post('/editProfile', isLoggedIn, isNotExisting, async (req, res) => {
let hashedPassword;
var pass = req.session.user.password;
var newpass;
if (req.body.password == "") {
newpass = pass;
} else {
hashedPassword = await bcrypt.hash(req.body.password, 10);
newpass = hashedPassword;
}
User.updateOne({
"_id": req.session.user._id
}, {
"firstName": req.body.firstname,
"lastName": req.body.lastname,
"username": req.body.username,
"email": req.body.email,
"phoneNum": req.body.phone,
"password": newpass,
"yearsExperience": req.body.yearsExperience,
"sessionCost": req.body.sessionCost
})
.then((obj) => {
return res.json("updated");
})
.catch((err) => {
console.log(err);
})
})
/**
*
* This helper function checks to see if an email, phone number, or username exists
* or not from the database.
* It returns an error message if an email, phone number, or username exists in the
* database or else it returns next.
* If there is an error finding the user it will load an error message else it will
* destory the session and log the user out.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
*/
async function isNotExisting(req, res, next) {
var emailExists = await User.exists({
email: req.body.email
})
var phoneExists = await User.exists({
phoneNum: req.body.phone
})
var usernameExists = await User.exists({
username: req.body.username
})
let userId = req.session.user._id;
User.findById({
_id: userId
}, function (err, user) {
if (err) console.log(err)
if (user) {
if (emailExists && req.body.email != user.email) {
return res.json("existingEmail");
} else if (phoneExists && req.body.phone != user.phoneNum) {
return res.json("existingPhone")
} else if (usernameExists && req.body.username != user.username) {
return res.json("existingUsername")
} else {
return next();
}
} else {
req.session.destroy();
return res.json("logout");
}
})
}
/**
*
* This helper function creates an account for user's who are therapists with
* different fields to be saved in the database.
*
* @param {*} req as request object
* @param {*} res as response object
*/
async function createTherapistAccount(req, res) {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
yearsExperience: req.body.yearsExperience,
sessionCost: req.body.sessionCost,
email: req.body.email,
password: hashedPassword
});
new_user.save()
.then((result) => {
res.json("login");
});
}
/**
*
* This helper function creates an account for user's who are patients
* with different fields than the therapist user's to be saved in the
* database.
*
* @param {*} req as request object
* @param {*} res as response object
*/
async function createPatientAccount(req, res) {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
email: req.body.email,
password: hashedPassword
});
new_user.save()
.then((result) => {
res.json("login");
});
}
/**
* This route post allows users to sign up their account and store their information
* on mongodb and stores the password as a hashed password. Uses isNotRegistered
* helper function to ensure another user with given fields for
* email, phone number, or username does not already exist.
*/
app.post("/sign-up", isNotRegistered, async (req, res) => {
if (req.body.userType == "therapist") {
return createTherapistAccount(req, res);
} else {
return createPatientAccount(req, res);
}
})
/**
*
* This helper function checks to see if a user with the email, phone number, or username
* the user provided upon sign-up already exist in the database.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns a certain message corrosponding to which field already exists(email, phonenum, or username)
* else if returns next.
*/
async function isNotRegistered(req, res, next) {
var emailExists = await User.exists({
email: req.body.email
})
var phoneExists = await User.exists({
phoneNum: req.body.phone
})
var usernameExists = await User.exists({
username: req.body.username
})
if (emailExists) {
return res.json("existingEmail");
} else if (phoneExists) {
return res.json("existingPhone")
} else if (usernameExists) {
return res.json("existingUsername")
} else {
return next();
}
}
//////Admin Dashboard\\\\\\
//MiddleWare
/**
*
* This helper function checks to see if an admin is deleted
* from the database from the admin dashboard is not the
* last administrator in the database to ensure there is always
* at least one admin.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns an error message if the admin to be deleted is the last administrator
* in the database else it returns next.
*/
function isNotLastAdminDelete(req, res, next) {
if (req.body.previousUserType == 'admin') {
User.count({
userType: 'admin'
}, (err, count) => {
if (err) {
console.log(err);
} else if (count > 1) {
return next();
} else {
return res.send('lastAdmin');
}
})
} else {
return next();
}
}
/**
*
* This helper function checks to see if an admin's usertype is editted
* from the database from the admin dashboard is not the
* last administrator in the database to ensure there is always
* at least one admin.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
* @returns an error message if the admin to be editted is the last administrator
* in the database else it returns next.
*/
function isNotLastAdminEdit(req, res, next) {
if (req.body.previousUserType == 'admin' && req.body.userType != 'admin') {
User.count({
userType: 'admin'
}, (err, count) => {
if (err) {
console.log(err);
} else if (count > 1) {
return next();
} else {
return res.send('lastAdmin');
}
})
} else {
return next();
}
}
//Routes
/**
* This get route grabs all users from the database and returns them as a json object
* so that they can be loaded in the admin dashboard.
*/
app.get('/getAllUsersData', isLoggedIn, isAdmin, setHeaders, (req, res) => {
User.find({}, function (err, user) {
if (err) {
console.log(err);
}
if (!user) {}
res.json(user);
});
})
/**
* This delete route allows administrators to delete a certain user from the database
* using their id.
*/
app.delete('/deleteUser', isLoggedIn, isAdmin, isNotLastAdminDelete, async (req, res) => {
User.deleteOne({
_id: req.body.id
})
.then(function () {
//if user is deleting themselves, delete session data
if (req.body.id == req.session.user._id) {
req.session.destroy();
}
res.send();
}).catch(function (error) {
console.log(error); // Failure
});
})
/**
* This delete route allows users to delete their profiles from the database (Delete account).
*/
app.delete('/deleteUserProfile', isLoggedIn, isNotLastAdminDelete, async (req, res) => {
User.deleteOne({
_id: req.session.user._id
})
.then(function () {
req.session.destroy();
res.send();
}).catch(function (error) {
console.log(error); // Failure
});
})
/**
*
* This helper function checks to see if the given email, phone number, or username
* to be editted does not already exist in the database for administrators when they
* edit a certain users information.
*
* @param {*} req as request object
* @param {*} res as response object
* @param {*} next executes the middleware succeeding the current middleware.
*/
async function isNotExistingAdmin(req, res, next) {
var emailExists = await User.exists({
email: req.body.email
})
var phoneExists = await User.exists({
phoneNum: req.body.phone
})
var usernameExists = await User.exists({
username: req.body.username
})
let userId = req.body.id;
User.findById({
_id: userId
}, function (err, user) {
if (err) console.log(err)
if (user) {
if (emailExists && req.body.email != user.email) {
return res.send("existingEmail");
} else if (phoneExists && req.body.phone != user.phoneNum) {
return res.send("existingPhone")
} else if (usernameExists && req.body.username != user.username) {
return res.send("existingUsername")
} else {
return next();
}
} else {
res.send("unexistingUser")
}
})
}
/**
*
* This helper function updates a user's account that is a therapist
* with certain fields that belong to the therapist user's in the
* databsae.
*
* @param {*} req as request object
* @param {*} res as response object
*/
function updateTherapist(req, res) {
User.updateOne({
"_id": req.body.id
}, {
"firstName": req.body.firstname,
"lastName": req.body.lastname,
"username": req.body.username,
"email": req.body.email,
"phoneNum": req.body.phone,
"userType": req.body.userType,
"yearsExperience": req.body.yearsExperience,
"sessionCost": req.body.sessionCost
})
.then((obj) => {
if (req.session.user._id == req.body.id && req.body.userType != req.session.user.userType)
req.session.destroy();
return res.send("updatedWithoutPassword");
})
.catch((err) => {
console.log(err);
})
}
/**
*
* This helper function updates a user's account that is a patient
* with certain fields that belong to the patient user's in the
* database.
*
* @param {*} req as request object
* @param {*} res as response object
*/
async function updatePatient(req, res) {
User.updateOne({
"_id": req.body.id
}, {
$unset: {
"yearsExperience": "",
"sessionCost": ""
},
"firstName": req.body.firstname,
"lastName": req.body.lastname,
"username": req.body.username,
"email": req.body.email,
"phoneNum": req.body.phone,
"userType": req.body.userType
})
.then((obj) => {
if (req.session.user._id == req.body.id && req.body.userType != req.session.user.userType)
req.session.destroy();
return res.send("updatedWithoutPassword");
})
.catch((err) => {
console.log(err);
})
}
/**
*
* Helper function that updates a therapist's user account AND
* updates their password in the database.
*
* @param {*} req as request object
* @param {*} res as response object
*/
async function updateTherapistWithPassword(req, res) {
var hashedPassword = await bcrypt.hash(req.body.password, 10);
User.updateOne({
"_id": req.body.id
}, {
"firstName": req.body.firstname,
"lastName": req.body.lastname,
"username": req.body.username,
"email": req.body.email,
"phoneNum": req.body.phone,
"userType": req.body.userType,
"yearsExperience": req.body.yearsExperience,
"sessionCost": req.body.sessionCost,
"password": hashedPassword
})
.then((obj) => {
if (req.session.user._id == req.body.id && req.body.userType != req.session.user.userType)
req.session.destroy();
return res.send("updatedWithPassword");
})
.catch((err) => {
console.log(err);
})
}
/**
*
* This helper function updates a patient's user account AND
* updates their password in the database.
*
* @param {*} req as request object
* @param {*} res as response object
*/
async function updatePatientWithPassword(req, res) {
var hashedPassword = await bcrypt.hash(req.body.password, 10);
User.updateOne({
"_id": req.body.id
}, {
$unset: {
"yearsExperience": "",
"sessionCost": ""
},
"firstName": req.body.firstname,
"lastName": req.body.lastname,
"username": req.body.username,
"email": req.body.email,
"phoneNum": req.body.phone,
"userType": req.body.userType,
"password": hashedPassword
})
.then((obj) => {
if (req.session.user._id == req.body.id && req.body.userType != req.session.user.userType)
req.session.destroy();
return res.send("updatedWithPassword");
})
.catch((err) => {
console.log(err);
})