-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
865 lines (793 loc) · 24 KB
/
server.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
/* server.js - Express server*/
'use strict';
const log = console.log
log('Express server')
const path = require('path')
// Express
const express = require('express')
const app = express();
app.use(express.static(__dirname + "/client/quarantine/build"));
const bodyParser = require('body-parser')
app.use(bodyParser.json());
// Mongo and Mongoose
const { ObjectID } = require('mongodb')
const { mongoose } = require('./db/mongoose');
const { Post, Notification, User,Activities,Tips, News} = require('./models/schema'); // TODO: update this
const { Collection } = require('mongoose');
// helpers & middlewares
// check if mongoose is connected
const mongoChecker = (req, res, next) => {
// check mongoose connection established.
if (mongoose.connection.readyState != 1) {
log('Issue with mongoose connection')
res.status(500).send('Internal server error')
return;
} else {
next()
}
}
// Middleware for authentication of resources
const authenticate = (req, res, next) => {
if (req.session.user) {
User.findById(req.session.user).then((user) => {
if (!user) {
return Promise.reject()
} else {
req.user = user
next()
}
}).catch((error) => {
res.status(401).send("Unauthorized")
})
} else {
res.status(401).send("Unauthorized")
}
// req.session.user = new ObjectID("5f358e874fe8c47bf348b751")
// req.session.userType = "normal_user"
// req.session.userName = "user"
// next();
}
// check if mongo is disconnected
function isMongoError(error) { // checks for first error returned by promise rejection if Mongo database suddently disconnects
return typeof error === 'object' && error !== null && error.name === "MongoNetworkError";
}
// check if id is valid ObjectID
function checkObjctId(id) {
return ObjectID.isValid(id);
}
//Session
const session = require("express-session");
const { promises } = require('fs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
secret:"quarantine",
resave:false,
saveUninitialized:false,
cookie:{
expires: 500000,
httpOnly:true
}
})
);
// Qixin's API
// get all posts
app.get("/post", mongoChecker, authenticate, (req, res) => {
Post.find().then((posts) => {
res.send([ posts, {userName: req.session.userName, userType: req.session.userType, userId: req.session.user} ]);
})
.catch((err) => {
log(err);
res.status(500).send("Internal Server Error");
});
})
// Save a post to database
/* const data = {
names: ["user1"],
contents: [post.value + " " + tags.value],
times: [new Date()],
likes: [0],
tags: [tags.value],
}*/
app.post("/post", mongoChecker, authenticate, (req, res) => {
const posterId = req.session.user;
if (!checkObjctId(posterId)) {
res.status(404).send() // if invalid id, definitely can't find resource, 404.
return; // so that we don't run the rest of the handler.
}
// log(posterId)
const post = new Post({
posterId: [req.session.user],
posterType: [req.session.userType],
posterName: [req.session.userName],
postContent: req.body.contents,
postTime: req.body.times,
numLikes: req.body.likes,
tags: req.body.tags,
});
// console.log(post);
// log(post)
post.save().then((result) => {
return result._id;
})
.then(postId =>{
User.findById(req.session.user).then(user => {
if (!user){
// log('here');
res.status(404).send("resource not found")
} else{
// log("123")
// const fieldsToUpdate = { posts: [postId] };
user.posts.push(postId);
const fieldsToUpdate = { posts: user.posts };
return User.findOneAndUpdate({_id: req.session.user}, { $set: fieldsToUpdate }, {new: true, useFindAndModify: false});
}
})
.then(user => {
if (!user){
res.status(404).send("resource not found")
} else{
// log("123",{ currentPost: post._id, posterType: req.session.userType, posterId: req.session.user });
res.send({ currentPost: post._id });
}
}).catch(error => {
if (isMongoError(error)) { // check for if mongo server suddenly dissconnected before this request.
res.status(500).send('Internal server error')
} else {
// log("herer")
res.status(400).send('Bad Request') // 400 for bad request gets sent to client.
}
});
})
.catch((error) => {
if (isMongoError(error)) { // check for if mongo server suddenly dissconnected before this request.
res.status(500).send('Internal server error')
} else {
// log("here2")
res.status(400).send('Bad Request') // 400 for bad request gets sent to client.
}
})
});
//leave a reply
app.patch("/reply/:postId", mongoChecker, authenticate, (req, res) => {
const postId = req.params.postId;
console.log(postId)
if (!checkObjctId(postId)){
res.status(404).send('Resource not found');
}
Post.findById(postId)
.then( post => {
if (!post){
res.status(404).send("post not found");
Promise.reject();
}
post.posterId.push(req.session.user);
// log(post, newposterId);
const newPost = {
posterId: req.body.posterId,
posterType: req.body.posterType,
posterName: req.body.names,
postContent: req.body.contents,
postTime: req.body.times,
numLikes: req.body.likes,
tags: req.body.tags,
}
// console.log(newPost);
// log(newPost)
return Post.findOneAndUpdate({_id: postId}, {$set: newPost}, {new: true, useFindAndModify: false});
})
.then(post => {
if (!post){
// log("here1")
res.status(404).send("post not found");
} else{
return post._id;
}
})
.then(postId =>{
User.findById(req.session.user).then(user => {
if (!user){
// log("here2")
res.status(404).send("resource not found")
} else{
for (const existPost of user.posts){
// log(existPost, postId, existPost === postId, existPost == postId);
if (existPost.toString() === postId.toString()){
// log("here4")
return user;
}
}
user.posts.push(postId)
const fieldsToUpdate = { posts: user.posts };
return User.findOneAndUpdate({_id: req.session.user}, { $set: fieldsToUpdate }, {new: true, useFindAndModify: false});
}
})
.then(user => {
if (!user){
// log("here3")
res.status(404).send("resource not found")
} else{
res.send({ posterType: req.session.userType, posterId: req.session.user });
}
}).catch(error => {
if (isMongoError(error)) { // check for if mongo server suddenly dissconnected before this request.
res.status(500).send('Internal server error')
} else {
// console.log("here?");
res.status(400).send('Bad Request') // 400 for bad request gets sent to client.
}
});
})
.catch(error => {
if (isMongoError(error)){
res.status(500).send("Internal server error");
} else{
log(error);
res.status(400).send("Bad Request");
}
})
});
// Like a Post
app.patch("/post/like/:postId", mongoChecker, authenticate, (req, res) => {
const postId = req.params.postId;
if (!checkObjctId(postId)){
res.status(404).send('Resource not found');
}
Post.findById(postId)
.then( post => {
if (!post){
res.status(404).send('post not found');
return Promise.reject();
} else{
return post.numLikes;
}
})
.then( numLikes => {
numLikes[req.body.contentIndex] += req.body.likeNum;
const fieldsToUpdate = { numLikes: numLikes };
return Post.findOneAndUpdate({_id: postId}, { $set: fieldsToUpdate }, {new: true, useFindAndModify: false});
})
.then(post => {
if (!post){
res.status(404).send();
} else{
res.send();
}
})
.catch(error => {
if (isMongoError(error)){
res.status(500).send("Internal server error");
} else{
log(error);
res.status(400).send("Bad Request");
}
})
});
// Delete a post
app.delete("/post/:postId", mongoChecker, authenticate, (req, res) => {
const postId = req.params.postId;
if (!checkObjctId(postId)){
res.status(404).send('Resource not found');
}
Post.findByIdAndDelete(postId)
.then( post => {
if (!post){
res.status(404).send('post not found');
} else{
return User.findById(req.session.user);
}
})
.then( user => {
if (!user){
res.status(404).send("resource not found")
} else{
const posts = user.posts;
for (let currPostId = 0; currPostId < posts.length; currPostId++){
if (posts[currPostId].toString() === postId.toString()){
posts.splice(currPostId, 1);
break;
}
}
return User.findOneAndUpdate({_id: req.session.user}, { $set: { posts: posts } }, {new: true, useFindAndModify: false});
}
})
.then(user => {
res.send();
})
.catch(error => {
if (isMongoError(error)){
res.status(500).send("Internal server error");
} else{
log(error);
res.status(400).send("Bad Request");
}
})
});
// Delete a reply
app.patch("/reply/delete/:postId", mongoChecker, authenticate, (req, res) => {
const postId = req.params.postId;
if (!checkObjctId(postId)){
res.status(404).send('Resource not found');
}
Post.findById(postId)
.then( post => {
if (!post){
res.status(404).send('post not found');
return Promise.reject();
} else{
// log(post)
return post.postContent;
}
})
.then( contents => {
// log(contents)
contents[req.body.contentIndex] = "[content deleted by admin/author]";
const fieldsToUpdate = { postContent: contents };
return Post.findOneAndUpdate({_id: postId}, { $set: fieldsToUpdate }, {new: true, useFindAndModify: false});
})
.then(post => {
if (!post){
res.status(404).send();
} else{
res.send();
}
})
.catch(error => {
if (isMongoError(error)){
res.status(500).send("Internal server error");
} else{
log(error);
res.status(400).send("Bad Request");
}
})
});
// get user info
app.get("/profile/:id", mongoChecker, authenticate, (req, res) => {
/// req.params has the wildcard parameters in the url, in this case, id.
let id = req.params.id;
if (id == "me"){
id = req.session.user;
} else{
if (!checkObjctId(id)){
res.status(404).send('Resource not found');
}
}
// Good practise: Validate id immediately.
if (!ObjectID.isValid(id)) {
res.status(404).send(); // if invalid id, definitely can't find resource, 404.
return;
}
// Otherwise, findById
User.findById(id)
.then(user => {
if (!user) {
res.status(404).send(); // could not find this student
} else {
const RecentAct = []; // an array storing activities and posts
let p = Promise.resolve();
for (let i = 0; i < user.posts.length; i++) {
p = p.then(_ => Post.findById(user.posts[i]))
.then(post => {
if (post) {
RecentAct.push({ type: "post", contentSketch: post.postContent[0], time: post.postTime[0]})
// log("here1", RecentAct)
}
return Promise.resolve();
})
.catch(error => {
// log("something wrong internal")
res.status(500).send("server error");
});
// log("here1.3", p)
}
// log("here1.5")
p.then(_ => {
for (let i = 0; i < user.activities.length; i++) {
RecentAct.push({ type: "activity", title: user.activities[i].activityTitle})
}
})
.then( e => res.send([user, RecentAct, {userName: req.session.userName, userType: req.session.userType, userId: req.session.user}])).catch(e => res.status(400).send("bad request"));
}
})
.catch(error => {
res.status(500).send(); // server error
});
});
// update user info
app.patch("/profile", mongoChecker, authenticate, (req, res) => {
// log(req.body)
User.findById(req.session.user)
.then( user => {
if (!user){
res.status(404).send('user not found');
return Promise.reject();
} else{
return user;
}
})
.then( user => {
return User.findOneAndUpdate({_id: req.session.user}, { $set: req.body }, {new: true, useFindAndModify: false});
})
.then(user => {
if (!user){
res.status(404).send();
} else{
res.send();
}
})
.catch(error => {
if (isMongoError(error)){
res.status(500).send("Internal server error");
} else{
log(error);
res.status(400).send("Bad Request");
}
})
});
// =================
// Yifei's API
app.post("/users", (req, res) => {
// log(req.body);
// Create a new user
const user = new User({
userName: req.body.userName,
userType:req.body.userType,
email:req.body.email,
password: req.body.password
});
// Save the user
user.save().then(
user => {
res.send(user);
},
error => {
res.status(400).send(error); // 400 for bad request
}
);
});
app.post("/users/signIn",(req, res) =>{
const userName = req.body.userName;
const password = req.body.password;
// log(userName, password)
User.findUser(userName, password).then(user =>{
req.session.user = user._id;
req.session.userName = user.userName;
req.session.userType = user.userType;
req.session.quarantineStartDate = user.quarantineStartDate
res.send({
currentUserName:user.userName,
currentUserType:user.userType,
quarantineStartDate:user.quarantineStartDate
});
})
.catch(error=>{
res.status(400).send()
});
});
app.post("/users/signUp",(req,res) =>{
// log(req.body);
let userT;
let user;
// const current = new Date();
// const currentDate=current.getMonth()+1 +"/" +current.getDate()+"/"+current.getFullYear();
if(!req.body.userType){
! req.body.docCertificate ? userT = "normal_user" : userT = "doctor"
user = new User({
userName: req.body.userName,
userType:userT,
email:req.body.email,
password: req.body.password,
docCertificate:req.body.docCertificate
})
}
else{
user = new User({
userName: req.body.userName,
userType:req.body.userType,
email:req.body.email,
password: req.body.password,
docCertificate:req.body.docCertificate
});
}
// Save the user
user.save().then(
result => {
req.session.user = result._id;
req.session.userName = result.userName;
req.session.userType = result.userType;
req.session.quarantineStartDate = result.quarantineStartDate;
res.send({
currentUserName:result.userName,
currentUserType:result.userType,
quarantineStartDate:result.quarantineStartDate
});
},
error => {
res.status(400).send(error); // 400 for bad request
}
);
});
// app.post("/users/resetPswd",(req, res)=>{
// const userEmail = req.body.email;
// User.findOne({
// email:req.body.email
// }).then(user=>{
// if(user){
// res.send(user);
// }
// })
// })
app.patch("/users/resetPswd", (req, res)=>{
User.findOne(
{email:req.body.email}
)
.then(updated=>{
if(updated){
updated.password = req.body.password;
updated.save()
.then(res.send({user:updated}))
}
})
.catch(error=>{
res.status(404).send(error);
})
})
app.get("/users/check-session",(req, res) =>{
if(req.session.user){
res.send({
currentUserName: req.session.userName,
currentUserType:req.session.userType,
quarantineStartDate:req.session.quarantineStartDate
})
}
else{
res.status(401).send();
}
});
//logOut and destroy the session
app.get("/users/logout",(req,res) =>{
req.session.destroy(err =>{
if(err){
res.status(500).send(error);
}
else{
res.send()
}
});
});
//middleware to authenticate the current user is admin
const adminAuth = (req, res, next) =>{
if(req.session.user){
User.findById(req.session.user).then((user) =>{
if(!user){
return Promise.reject()
}
else{
if(user.userType !== "admin"){
return Promise.reject()
}
else{
req.user = user
next()
}
}
})
.catch((error) =>{
res.status(401).send(error +" Unauthorized")
})
}
else{
res.status(401).send("Unauthorized")
}
}
//get all users
app.get("/normalUsers", adminAuth,(req, res) =>{
User.find({
userType : "normal_user"
}).then(normalUsers =>{
res.send({normalUsers});
},
error =>{
res.status(500).send(error);
}
)
});
//get all doctors
app.get("/doctors", adminAuth,(req, res) =>{
User.find({
userType:"doctor"
}).then(doctors =>{
res.send({doctors});
}),
error=>{
res.status(500).send(error);
}
});
//delete user by id
app.delete("/user/:id", adminAuth, (req, res) =>{
const id= req.params.id;
if(!ObjectID.isValid(id)){
res.status(404).send("Recources is not found")
return;
}
User.findByIdAndRemove(id)
.then(user =>{
if(!user){
res.status(404).send();
}
else{
User.find({
userType:user.userType
}).then(
(users)=>{
res.send({users});
}
);
}
})
.catch((error) =>{
res.status(500).send(error);
})
});
//add an activitiy in to uses's list
app.post("/users/activities/:id",authenticate,(req, res) =>{
const actId = req.params.id;
const userId = req.user._id;
if(!ObjectID.isValid(actId)){
res.status(404).send("Recources is not found")
return;
}
Activities.findById(actId).then(
act=>{
if(!act){
res.status(404).send("activity not found");
}
else{
User.findById(userId).then(
user=>{
user.activities.push({
activityTitle:act.activityTitle,
activityType:act.activityType,
activityDescription:act.activityDescription
});
user.save().then(
(updatedUser)=>{
res.send({updatedUser});
}
);
}
),
error=>{
res.send(error);
}
}
}
),
error=>{
res.send(error);
}
});
//delete an activitiy form the user's list
app.delete("/users/activities/:id", authenticate,(req, res)=>{
const actId = req.params.id;
const userId = req.user._id;
User.findById(userId).then(
user=>{
user.activities.id(actId).remove();
user.save().then(
u=>{
res.send({updatedUser:u});
}
);
}
)
.catch(error=>{
res.send(error);
});
});
//add an activitiy in to the database
app.post("/activities", (req, res)=>{
const act = new Activities({
activityTitle:req.body.activityTitle,
activityType:req.body.activityType,
activityDescription:req.body.activityDescription
});
act.save().then(
act=>{
res.send(act);
},
error => {
res.status(400).send(error);
}
);
});
//get all activities in the database
app.get("/activities", (req, res)=>{
Activities.find().then(
(activities)=>{
res.send({activities});
},
error=>{
res.status(500).send(error);
}
);
});
//get all users' activities
app.get("/users/activities", authenticate,(req, res)=>{
const userId = req.user._id;
User.findById(userId).then(
user=>{
res.send({
activities: user.activities
});
},
error=>{
res.status(500).send(error);
}
);
});
//add tips to database
app.post("/tips",(req,res) =>{
const tips= new Tips({
title:req.body.title,
content:req.body.content
});
tips.save().then(
(tip)=>{
res.send({tip});
},
error=>{
res.status(404).send(error);
}
);
});
//get a random tips from database
app.get("/tips",(req, res)=>{
Tips.findOneRandom(
function(err, tip){
res.send({tip:tip});
}
);
});
//add news to database
app.post("/news",(req,res) =>{
const news= new News({
title:req.body.title,
content:req.body.content
});
news.save().then(
(news)=>{
res.send({news});
},
error=>{
res.status(404).send(error);
}
);
});
//get a random news from database
app.get("/news",(req, res)=>{
News.findOneRandom(
function(err, news){
res.send({news:news});
}
);
});
// Setting up a static directory for the files in /public
// using Express middleware.
// Don't put anything in /public that you don't want the public to have access to!
/* KEEP THIS BLOCK AT THE BOTTOM */
app.get("*", (req, res) => {
// check for page routes that we expect in the frontend to provide correct status code.
const goodPageRoutes = ["/", "/SignIn","/SignUp", "/qa", "/questionnaire", "/qaAdmin", "/UserProfile", "/DoctorProfile", "AdminProfile", "/dashboard", "doctordashboard", "admindashboard"];
if (!goodPageRoutes.includes(req.url)) {
// if url not in expected page routes, set status to 404.
res.status(404);
}
// send index.html
res.sendFile(path.join(__dirname + "/client/quarantine/build/index.html"));
});
// will use an 'environmental variable', process.env.PORT, for deployment.
const port = process.env.PORT || 5000
app.listen(port, () => {
log(`Listening on port ${port}...`)
})