-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
979 lines (795 loc) · 31.3 KB
/
Copy pathserver.js
File metadata and controls
979 lines (795 loc) · 31.3 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
/*===========================================================================
=========================== server.js START =================================
===========================================================================*/
/*
This is the file that contains all of the backend code.
- It starts a server and also establishes a connection with the MongoDB database.
- It contains several POST and GET endpoints that are fetched from
the frontend as well as several helper functions which are used to access
the database.
- Each function and endpoint is documented with a docstring with format
=======================================================================
<TYPE> (POST, GET, FUNCTION): <NAME> (function name, endpoint name)
<SHORT DESCRIPTION>
======================================================================
- So, $ git grep POST:
would return a list of all the POST endpoints as well as all the functions
that are called by these post endpoints
*/
/*===========================================================================
Dependencies
===========================================================================*/
const { response } = require("express");
var express = require("express"),
bodyParser = require("body-parser"),
MongoClient = require('mongodb').MongoClient,
cookieSession = require('cookie-session'),
path = require('path'),
{ v4: uuidv4 } = require('uuid');
const { exit } = require("process");
/*===========================================================================
Database access information
===========================================================================*/
/* ENTER INFORMATION HERE */
// the connection string to your Mongo Atlas Cluster along with username and password
// this can be copied off the connection page for the cluster
require('dotenv').config();
const uri = process.env.MONGO_URI;
if (uri == null)
{
console.log("\n\n\n\n ERROR: No MongoDB cluster provided \n\n\n\n");
exit(1)
}
// create instance of mongo client
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
console.log("- Client created")
/*===========================================================================
Server set up
===========================================================================*/
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
/*===========================================================================
light-weight cookie session to store login information
===========================================================================*/
app.use(cookieSession({
name: 'session',
secret: "Don't use trays",
maxAge: 3600000, // 1 hour
username: null,
}))
console.log("- Server created")
/*===========================================================================
===================== ENDPOINTS ============================================
===========================================================================*/
/*===========================================================================
GET: /auth
checks if the user is currently logged in
all utils.jl/isLoggedIn() calls are redirected here
===========================================================================*/
app.get("/auth", function (req, res) {
console.log("inside auth");
console.log("cookie username = ", req.session.username);
if (req.session.username != null) //inspect cookie username value
{
res.json({ loggedIn: true });
}
else {
res.json({ loggedIn: false });
}
});
/*===========================================================================
POST: /signup
Handling new user signup
===========================================================================*/
app.post("/signup", async function (req, res) {
var name = req.body.name
var username = req.body.username
var password = req.body.password
var password_confirm = req.body.password_confirm;
console.log("Inside server.js /signup");
console.log("new user: ")
console.log(" name = ", name);
console.log(" username = ", username);
console.log(" password = ", password);
var successCode = 0;
if (username.length == 0 || password.length == 0) {
console.log("Username and Password must be non-empty");
successCode = 2;
return res.json({ successCode: successCode });
}
if (password_confirm != password) {
console.log("Passwords do not match");
successCode = 3;
return res.json({ successCode: successCode });
}
successCode = await addUser(name, username, password); // 1 = username taken, 4 = database errors
return res.json({ successCode: successCode });
});
/*===========================================================================
POST: /login
Handling user login
===========================================================================*/
app.post("/login", async (req, res) => {
console.log("login submitted, cookie username= ", req.session.username);
var username = req.body.username; // entered user name
var password = req.body.password; // entered password
console.log("attempt to log in : ")
console.log(" username = ", username);
console.log(" password = ", password);
successCode = await loginUser(username, password); // loginUser does all the checking
console.log("successCode = ", successCode)
if (successCode == 0) { // successful login
req.session.username = username;
console.log("cookie session username = ", req.session.username);
}
else { // unsuccessful login
req.session.username = null;
console.log("cookie session username = ", req.session.username);
}
return res.json({ successCode: successCode });
})
/*===========================================================================
GET: /findusers/:substring
find users with a particular username - used for searching and adding users
===========================================================================*/
app.get("/findusers/:substring", async (req, res) => {
curUser = req.session.username
console.log(req.session.username, " is searching for users");
console.log(req.params.substring, " is the entered substring");
users = await findUsers(req.params.substring);
listOfUsernames = []
//extract just the usernames from the list of dicts
for (var i in users) {
dict = users[i]
status = await friendStatus(dict['username'], curUser)
listOfUsernames.push({ user: dict['username'], addstatus: status })
}
console.log('final list')
console.log(listOfUsernames)
successCode = 0
if (users = -1) {
successCode = -1;
}
return res.json({ successCode: successCode, users: listOfUsernames });
})
/*===========================================================================
POST: /sendfriendrequest
send friend request from one user to another
===========================================================================*/
app.post("/sendfriendrequest", async (req, res) => {
console.log(req.session.username, " sent a friend request");
var username = req.body.username; // user sending the request
var friendname = req.body.friendname; // user receiving the request
console.log(username, "is sending a friend request to ", friendname);
// Here, as opposed to backend login functionality, no checking of the submitted data needs to be done
// Username is already confirmed to be in database during login page checking
// There are only 2 options: Accept and Delete
successCode = await sendFriendRequest(username, friendname);
return res.json({ successCode: successCode });
})
/*===========================================================================
POST: /handlefriendrequest
this post function handles the response to a friend request,
contained in the response field as true (accepted) or false (rejected)
===========================================================================*/
app.post("/handlefriendrequest", async (req, res) => {
console.log(req.session.username, " responded to friend request");
var username = req.body.curUser; // entered username
var friendname = req.body.curfriendreq; // entered name of person who sent friend req
var response = req.body.response; // entered user's response
console.log("In the friend request list of ", username);
console.log(" request changed = ", friendname);
console.log(" response = ", response);
// Here, as opposed to backend login functionality, no checking of the submitted data needs to be done
// Username is already confirmed to be in database during login page checking
// There are only 2 options: Accept and Delete
if (response === true) {
console.log("Friend request accepted", username);
successCode = await confirmFriend(username, friendname);
}
await removeFriendRequest(username, friendname);
return res.json({ successCode: successCode });
})
/*===========================================================================
POST: /settings/signout
Signs out current user by destroying the current cookie session
===========================================================================*/
app.post("/settings/signout", async (req, res) => {
console.log("logout submitted, cookie username= ", req.session.username);
console.log("attempt to log out")
// setting the username in the cookie to null
req.session.username = null;
res.redirect('/login');
})
/*===========================================================================
GET: /info
checks who the current user is by looking at the cookie session
===========================================================================*/
app.get("/info", async (req, res) => {
const username = req.session.username;
console.log("inside /info, username = ", username);
res.send({ username: req.session.username });
})
/*===========================================================================
GET: /info/:username
retrieves user information given a username
===========================================================================*/
app.get("/info/:username", async (req, res) => {
const username = req.params.username;
info = await userInfo(username);
if (info.returnCode != 0) {
res.send({ returnCode: info.returnCode, info: null });
}
info = await info.info;
res.send({ returnCode: 0, info: info });
});
/*===========================================================================
GET: /chat/:chat_id
returns the entire message list from this chatID
===========================================================================*/
// returns the entire message list from this chatID
app.get("/chat/:chat_id", async (req, res) => {
let returnCode;
let messages;
let participants;
try {
const chat_id = req.params.chat_id;
console.log("Inside server.js /chat/", chat_id);
db = await MongoClient.connect(uri);
console.log("- Connected to database for chat retrieval");
var dbo = db.db("main_db");
chat_data = dbo.collection("chat_data");
const chat = await chat_data.findOne({ chat_id: chat_id });
if (chat == null) // chat doesn't exist
{
console.log("Chat doesn't exist");
returnCode = 1;
return;
}
participants = await chat.participants;
if (!participants.includes(req.session.username)) // if user isn't a participant in the chat
{
console.log("User isn't logged in ");
returnCode = 2;
return;
}
messages = await chat.messages;
returnCode = 0;
}
catch (err) {
console.log(err);
returnCode = 3;
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
res.json({ returnCode: returnCode, messages: messages, participants: participants });
}
});
/*===========================================================================
POST: /sendchat/:chat_id
Send a message in a given chat_id
===========================================================================*/
app.post("/sendchat/:chat_id", async (req, res) => {
const chat_id = req.params.chat_id;
console.log("Inside server.js /sendchat/", chat_id);
const message = req.body;
let returnCode;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to database for chat submission");
var dbo = db.db("main_db");
chat_data = dbo.collection("chat_data");
const chat = await chat_data.findOne({ chat_id: chat_id });
if (chat == null) // chat doesn't exist
{
console.log("Chat doesn't exist");
returnCode = 1;
return;
}
participants = await chat.participants;
if (!participants.includes(req.session.username)) // if user isn't a participant in the chat
{
console.log("User isn't logged in ");
returnCode = 2;
return;
}
messages = await chat.messages;
updated_msgs = chat.messages;
updated_msgs.push(message);
chat_data.update({ chat_id: chat.chat_id }, { $set: { "messages": updated_msgs } });
console.log("chat updated");
returnCode = 0;
}
catch (err) {
console.log(err);
returnCode = 3;
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
res.json({ returnCode: returnCode });
}
});
/*===========================================================================
POST: /change/name/:username
handles changes in name from the settings page
===========================================================================*/
app.post('/change/name/:username', async (req, res) => {
const username = req.params.username;
const submittedName = req.body.submittedName;
console.log("inside server.js /change/name/", username);
let returnCode;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to database for name change");
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
const user = await user_data.findOne({ username: username });
if (user == null) // user doesn't exist
{
console.log("User doesn't exist");
returnCode = 1;
return;
}
user_data.update({ username: username }, { $set: { "name": submittedName } });
console.log("name updated");
returnCode = 0;
}
catch (err) {
console.log(err);
returnCode = 3; // database errors
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
res.json({ returnCode: returnCode });
}
});
/*===========================================================================
POST: /change/password/:username
handles changes in password from the settings page
===========================================================================*/
app.post('/change/password/:username', async (req, res) => {
const username = req.params.username;
const newPassword = req.body.newPassword;
console.log("inside server.js /change/password/", username);
let returnCode;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to database for password change");
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
const user = await user_data.findOne({ username: username });
if (user == null) // user doesn't exist
{
console.log("User doesn't exist");
returnCode = 1; // user DNE error
return;
}
user_data.update({ username: username }, { $set: { "password": newPassword } });
console.log("password updated");
returnCode = 0;
}
catch (err) {
console.log(err);
returnCode = 3; // database errors
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
res.json({ returnCode: returnCode });
}
});
/*===========================================================================
POST: /latexRequest
calls the python script that calls rTex's LaTeX rendering API
===========================================================================*/
app.post("/latexRequest", async (req, res) => {
const latex = await req.body.latex;
console.log('called', latex)
var spawn = require("child_process").spawn;
var request = spawn('python', ['latexRequest.py', latex]);
request.stderr.pipe(process.stderr);
request.stdout.pipe(process.stdout);
request.stdout.on('data', function (data) {
res.json({ filename: data.toString() }); //returns filename of converted latex
})
});
/*===========================================================================
================= HELPER FUNCTIONS ==========================================
===========================================================================*/
/*===========================================================================
FUNCTION: loginUser(username, password)
Verifies the login information entered by the user
called by POST: /login
===========================================================================*/
async function loginUser(username, password) {
console.log("Inside loginUser")
var returnCode = 0;
try {
db = await MongoClient.connect(uri)
console.log("- Connected to database for user login")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
user = await user_data.findOne({ username: username });
console.log("true user = ", user);
if (user == null) {
console.log("user not found");
returnCode = 2; // code 2 : user not found
}
else if (user.password == password) {
console.log("login successful");
returnCode = 0; // code 0 : success
}
else {
console.log("wrong password");
returnCode = 1; //code 1 : wrong password
}
}
catch (err) {
returnCode = 3; // code 3: database errors
console.log(err);
}
finally {
db.close();
console.log("- Database closed");
console.log("return code = ", returnCode);
return returnCode;
}
}
/*===========================================================================
FUNCTION: addUser(name, username, password)
adds a new user to the database
called by POST: /signup
===========================================================================*/
async function addUser(name, username, password) {
console.log("Inside add user");
let db;
var returnCode = 0;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to Database for user creation")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
var new_user = { name: name, username: username, password: password, chats: [], friends: [], notifs: [], pendingfr: [] };
prev_user = await user_data.findOne({ username: username }); // checks for previous user with given name
if (prev_user != null) // if the prev_user is already present
{
console.log("Username already taken")
returnCode = 1; // username taken
return;
}
user_data.insertOne(new_user,
function (err, res) {
console.log("- New user added");
}
);
}
catch (err) {
console.log(err);
returnCode = 4; // database errors
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
return returnCode;
}
}
/*===========================================================================
FUNCTION: userInfo(username)
get name, friends list, notifications list, pending friend requests of a
given user.
called by GET: /info/:username
===========================================================================*/
async function userInfo(username) {
console.log("Inside server.js/userInfo");
let returnCode;
let info;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to Database for user info lookup")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
user = await user_data.findOne({ username: username }, { name: true, username: false, password: false, friends: true, notifs: true, pendingfr: true });
if (user == null) {
console.log("User not found")
returnCode = 1;
return;
}
info = user;
returnCode = 0;
}
catch (err) {
console.log(err);
returnCode = 2;
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
return { returnCode: returnCode, info: info };
}
}
/*===========================================================================
FUNCTION: findUsers(substring)
returns an array of usernames that match substring
called by GET: /findusers/:substring
===========================================================================*/
async function findUsers(substring) {
matchingusers = [];
try {
db = await MongoClient.connect(uri);
console.log("Connected to Database for lookup of substring", substring)
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
matchingUsers = await user_data.find({ username: { $regex: substring } });
matchingUsers = await matchingUsers.toArray();
console.log("found users");
}
catch (err) {
console.log(err);
return -1;
}
finally {
db.close();
console.log("Database closed");
return matchingUsers;
}
}
/*===========================================================================
FUNCTION: friendStatus(username1, username2)
from user1's perspective, what is the friend status of user2?
4 outputs
-1 error,
0 not friends at all,
1 pending friends,
2 friends already
===========================================================================*/
async function friendStatus(username1, username2) {
retvar = -1;
try {
db = await MongoClient.connect(uri);
console.log("Connected to Database for lookup")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
user1status = await user_data.findOne({ username: username1 }, { notifs: 1, friends: 1 });
user2status = await user_data.findOne({ username: username2 }, { notifs: 1, friends: 1, });
// redundancy for an extra check
if (user1status.notifs.includes(username2) && user2status.notifs.includes(username1)) {
console.log("Issue: The user did not have their notifs scrubbed correctly");
retvar = -1;
}
//already friends
else if (user1status.friends.includes(username2) || user2status.friends.includes(username2)) {
retvar = 2;
}
//already pending a friend request
else if (user1status.notifs.includes(username2) || user2status.notifs.includes(username1)) {
retvar = 1;
}
else {
retvar = 0;
}
}
catch (err) {
console.log(err);
returnCode = 1;
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", retvar);
return retvar;
}
}
/*===========================================================================
FUNCTION: sendFriendRequest(username1, username2)
send friend request from username1 to username 2
called by POST: /sendfriendrequest
===========================================================================*/
// send friend request from username1 to username 2
async function sendFriendRequest(username1, username2) {
status = await friendStatus(username1, username2); // redundancy check - frontend should ensure this is never violated
if (status !== 0) {
console.log("Notice: Attempted to send invalid friend req");
return -1;
}
try {
db = await MongoClient.connect(uri);
console.log("Connected to Database for lookup")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
const filter1 = { username: username1 };
//push a new value to their pending friends
const updateDocument1 = {
$push: {
pendingfr: username2,
},
};
const result1 = await user_data.updateOne(filter1, updateDocument1);
const filter2 = { username: username2 };
//push a new value to their notifcations friends
const updateDocument2 = {
$push: {
notifs: username1,
},
};
const result2 = await user_data.updateOne(filter2, updateDocument2);
}
catch (err) {
console.log(err);
returnCode = 1;
}
finally {
//console.log("Attempted friend request. Status: ", result1, result2);
db.close();
console.log("Database closed");
//console.log("Return code = ", returnCode);
return 0;
}
}
/*===========================================================================
FUNCTION: removeFriendRequest(username, friendname)
handles removal of friend request after accepting/deleting
called by POST: /handlefriendrequest
===========================================================================*/
async function removeFriendRequest(username, friendname) {
let returnCode;
try {
db = await MongoClient.connect(uri);
console.log("- Connected to Database to remove a friend request")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
// Remove the friend request notification from the user
// who received the friend request
const filter1 = { username: username };
const updateDocument1 = {
$pull:
{
notifs: friendname,
},
};
const result1 = await user_data.updateOne(filter1, updateDocument1);
console.log("Notification removed");
// Remove the pending friend request from the user
// who sent the friend request
const filter2 = { username: friendname };
const updateDocument2 = {
$pull:
{
pendingfr: username,
},
};
const result2 = await user_data.updateOne(filter2, updateDocument2);
console.log("PendingFR removed");
}
catch (err) {
console.log(err);
returnCode = 1;
}
finally {
db.close();
console.log("Database closed")
console.log("Return code = ", returnCode);
return returnCode;
}
}
/*===========================================================================
FUNCTION: createNewChat(username1, username2)
creates an entry in the chat database for a chat between two new friends
called by confirmFriend()
===========================================================================*/
// creates an entry in the chat database for a chat between two new friends
async function createNewChat(username1, username2) {
let returnCode;
try {
db = await MongoClient.connect(uri);
console.log("Connected to database for new chat creation");
var dbo = db.db("main_db");
chat_data = dbo.collection("chat_data");
var uniqueChatID = uuidv4(); // universally unique identifier for the chat id
new_chat = {
chat_id: uniqueChatID,
messages: [],
participants: [username1, username2]
}
chat_data.insertOne(new_chat,
function (err, res) {
if (err) throw err;
console.log("New chat with ID ", uniqueChatID, " added");
});
returnCode = uniqueChatID;
}
catch (err) {
console.log(err);
returnCode = -1;
}
finally {
db.close();
console.log("Database closed");
console.log("Return code = ", returnCode);
return returnCode;
}
}
/*===========================================================================
FUNCTION: confirmFriend(username1, username2)
once a friend request is accepted, create a new chat, add users to each
others friends lists, add chat_id to users' chat lists
called by POST: /handlefriendrequest
===========================================================================*/
async function confirmFriend(username1, username2) {
//remove Friend request
matchingUserName = "";
try {
db = await MongoClient.connect(uri);
console.log("Connected to Database for lookup")
var dbo = db.db("main_db");
user_data = dbo.collection("user_data");
//create new chat here
chatID = await createNewChat(username1, username2);
const filter1 = { username: username1 };
//push a new value to their notifcations friends
const updateDocument1 = {
$push: {
friends: username2,
chats: { chat_id: chatID, chat_name: username2 },
},
};
const result1 = await user_data.updateOne(filter1, updateDocument1);
const filter2 = { username: username2 };
//push a new value to their notifcations friends
const updateDocument2 = {
$push: {
friends: username1,
chats: { chat_id: chatID, chat_name: username1 },
},
};
const result2 = await user_data.updateOne(filter2, updateDocument2);
}
catch (err) {
console.log(err);
returnCode = 0;
}
finally {
db.close();
console.log("Database closed");
var returnCode = 0
console.log("Return code = ", returnCode);
return returnCode;
}
}
console.log("here");
console.log(__dirname);
// //app.use('/static', express.static(path.join(`${__dirname}/client/build`)));
// app.use(express.static('client/build'));
// app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname, '/client/build'))
// })
// app.get('/', (req, res) => {
// res.sendFile(path.join(__dirname, '/cl ient/build'))
// });
if(process.env.NODE_ENV === "production"){
app.use(express.static(path.join(__dirname, '/client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
})
} else {
app.get('/', (req, res) => {
res.send("Api running");
})
}
const port = process.env.PORT || 5000;
app.listen(port, function () {
console.log("Server Has Started at port", port);
});
/*===========================================================================
=========================== server.js END ===================================
===========================================================================*/