-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1370 lines (1180 loc) · 40.9 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
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
require('dotenv').config();
const express = require("express");
const crypto = require("crypto");
var session = require("express-session");
var bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const mongoSanitize = require('express-mongo-sanitize');
const Users = require("./models/users");
const User_groups = require("./models/user_groups");
const Posts = require("./models/posts");
const Comments = require("./models/comments");
const Groups = require("./models/groups");
const Logs = require("./models/logs");
const Likes = require("./models/likes");
const Did_it = require("./models/did_it");
const Fitbot = require("./models/fitbot");
const now = new Date();
const currentDate = now.toLocaleDateString();
const currentTime = now.toLocaleTimeString();
app.use(express.static('assets'));
const port = 5500;
// ---------- Session ----------
session.user_id = null;
session.admin = null;
const checkSession = (user_type = 0) => {
if (user_type == "admin") {
if (session.admin === null) {
return false;
}
}
else
if (session.user_id === null) {
return false;
}
return true;
};
const generateRandomString = () => {
return crypto.randomBytes(32).toString("hex");
};
app.use(
session({
secret: generateRandomString(),
resave: false,
saveUninitialized: true,
user_id: null,
admin: null
})
);
// ---------- Create Log function ----------
const createLog = async (event_type, description, req, response = "") => {
try {
await Logs.create({
timestamp: new Date().toISOString(),
user_id: `${session.user_id}`,
event_type: event_type,
description: description,
response: response,
ip_address: req ? req.ip : "unknown",
});
} catch (error) {
console.error("Error logging:", error);
}
};
// ---------- Body Parser ----------
app.use(express.json());
app.use(express.static("public"));
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.use(
mongoSanitize({
onSanitize: ({ req, key }) => {
console.warn(`This request[${key}] is sanitized`, req);
},
}),
);
// ---------- CORS ----------
const cors = require("cors");
const { log } = require("console");
const { create } = require("domain");
const likes = require("./models/likes");
const { url } = require("inspector");
const corsOptions = {
origin: "*",
credentials: true,
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
// ****************************** //
// ********** Session ********** //
// ****************************** //
//
// ---------- Create User ----------
app.post("/user", async (req, res) => {
try {
var data = {
first_name: req.body.firstName,
last_name: req.body.lastName,
email: (req.body.email).toLocaleLowerCase(),
password: req.body.password,
date: req.body.dob,
profile_pic: req.body.profilePictureUrl,
admin: "",
secret_phrase: req.body.secretPhrase
};
var db = mongoose.connection;
db.collection("users").insertOne(data, (err, collection) => {
if (err) {
throw err;
}
session.user_id = (collection.insertedId).toString();
console.log("User Created Successfully");
});
return res.redirect("http://127.0.0.1:5500/SignupRedirect.html");
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ------- Check existing email --------
app.get("/check_email/:email", async (req, res) => {
try {
const email = (req.params.email).toLocaleLowerCase();
const user = await Users.findOne({ email: email });
if (user) {
return res.status(200).json({ message: "Exists" });
}
else {
return res.status(200).json({ message: "Not Exist" });
}
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Create SessionID with UserID ----------
app.get("/SetSessionID/:user_id", async (req, res) => {
try {
const the_user_id = req.params.user_id;
if (!the_user_id) {
return res.status(404).json({ message: "Invalid Session ID" });
}
session.user_id = the_user_id;
const user = await Users.findById(the_user_id);
const admin = user.admin;
if (admin === "master") {
session.admin = "master";
console.log("Admin User");
}
createLog("Signin", "", req);
res.status(200).json({ the_user_id });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Sign out ---------
app.get("/signout", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
createLog("Signout", "", req);
session.user_id = null;
session.admin = null;
res.status(200).json({ message: "User logged out successfully" });
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Password Reset ---------
app.post("/reset_password", async (req, res) => {
try {
const { email, password, secret_phrase, date } = req.body;
console.log(req.body);
const user = await Users.findOne({ email, secret_phrase, date });
if (!user) {
return res.status(404).json({ message: "Invalid credentials" });
}
user.password = password;
await user.save();
res.status(200).json({ message: "Password reset successful" });
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ********************************** //
// ********** Users Model ********** //
// ********************************** //
// ---------- Get User By ID ----------
app.get("/user/:id", async (req, res) => {
try {
const users = await Users.findById(req.params.id);
res.status(200).json({ users });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get User By Session ----------
app.get("/user_session", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_id = session.user_id;
const admin = session.admin;
res.status(200).json({ user_id, admin });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get User By ID ----------
app.get("/user_details", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const users = await Users.findById(session.user_id);
// console.log(users)
res.status(200).json({ users });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get User By Email - Sign In ----------
app.get("/getUserByMail/:email", async (req, res) => {
try {
//make the email with all lower case
const email = (req.params.email).toLocaleLowerCase();
const users = await Users.findOne({ email: email });
res.status(200).json({ users });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get All Users ----------
app.get("/getUsers", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const users = await Users.find({});
res.status(200).json({ users });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Update User ----------
app.post("/update_user", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const { firstName, lastName, newpassword, dob, profilePictureUrl } = req.body;
const updatedFields = {
first_name: firstName,
last_name: lastName,
date: dob,
};
if (newpassword != "") {
updatedFields.password = newpassword;
}
if (profilePictureUrl != "") {
updatedFields.profile_pic = profilePictureUrl;
}
const updatedUser = await Users.findByIdAndUpdate(session.user_id, updatedFields, {
new: true,
});
if (!updatedUser) {
return res.status(404).json({ message: "User not found" });
}
console.log("User Updated Successfully:", updatedUser);
return res.redirect("http://127.0.0.1:5500/index.html");
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Delete User by ID ----------
app.post("/delete_user/:user_id", async (req, res) => {
try {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
const user_id = req.params.user_id;
const deletedUser = await Users.findByIdAndDelete(user_id);
if (!deletedUser) {
return res.status(404).json({ message: "User not found" });
}
console.log("User Deleted Successfully:", deletedUser);
createLog("Delete User", `${user_id}`, req);
res.status(200).json({ message: "User deleted successfully" });
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Update User By ID ----------
app.post("/update_user/:user_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
const user_id = req.params.user_id;
try {
var data = {
first_name: req.body.firstName,
last_name: req.body.lastName,
password: req.body.password,
email: req.body.email,
date: req.body.dob,
secret_phrase: req.body.secretPhrase,
admin: req.body.admin,
};
console.log(req.body);
profile_pic_url = req.body.profilePictureUrl;
console.log(profile_pic_url);
if (req.body.profilePictureUrl != "") {
data.profile_pic = req.body.profilePictureUrl;
}
const updatedFields = data;
console.log(updatedFields);
const updatedUser = await Users.findByIdAndUpdate(user_id, updatedFields, {
new: true,
});
if (!updatedUser) {
return res.status(404).json({ message: "User not found" });
}
createLog("User Update", `Updated: ${user_id}`, req, updatedUser);
return res.status(200).json(updatedUser);
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// **************************************** //
// ********** User Groups Model ********** //
// **************************************** //
// ---------- Get All Users Groups By Session ID ----------
app.get("/user_groups/", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_groups_res = await User_groups.find({
user_id: session.user_id,
});
if (!user_groups_res) {
return res.status(404).json({ message: "User not found" });
}
res.status(200).json({ user_groups_res });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get All Users Groups By ID ----------
app.get("/user_groups/:user_id", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_groups_res = await User_groups.find({
user_id: req.params.user_id,
});
if (!user_groups_res) {
return res.status(404).json({ message: "User not found" });
}
res.status(200).json({ user_groups_res });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Delete User Group By ID ----------
app.post("/delete_user_group/:user_group_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_group_id = req.params.user_group_id;
const group = await User_groups.findById(user_group_id);
if (!group) {
return res.status(404).json({ message: "User Group not found" });
}
await group.deleteOne();
createLog("User Group Deleted", `${user_group_id}`, req);
res.status(200).json({ message: "User Group deleted successfully" });
} catch (error) {
console.error("Error deleting group:", error);
res.status(500).json({ message: "Failed to delete group" });
}
});
// ---------- Add user groups ----------
app.post("/add_user_groups", (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const { newSelectedCategories } = req.body;
newSelectedCategories.forEach(async (category) => {
await User_groups.create({ user_id: session.user_id, group: category });
});
res.status(200).json({ message: "New user groups added successfully" });
} catch (error) {
console.error("Error adding user groups to the database:", error);
res.status(500).json({ message: error.message });
}
});
// ---------- Add user groups by User ID and Group Name ----------
app.post("/add_user_group/:user_id/:group_name", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_id = req.params.user_id;
const group_name = req.params.group_name;
var data = {
user_id: user_id,
group: group_name
};
var db = mongoose.connection;
const result = await db.collection("user_groups").insertOne(data);
createLog("Create User Group", `${user_id}: ${group_name}`, req);
res.status(200).json({ message: "New user group added successfully" });
} catch (error) {
console.error("Error adding user groups to the database:", error);
res.status(500).json({ message: error.message });
}
});
// ---------- Remove user groups ----------
app.post("/remove_user_groups", (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const { unselectedCategories } = req.body;
unselectedCategories.forEach(async (category) => {
await User_groups.deleteOne({ user_id: session.user_id, group: category });
});
res.status(200).json({ message: "User groups removed successfully" });
} catch (error) {
console.error("Error removing user groups from the database:", error);
res.status(500).json({ message: error.message });
}
});
// ---------- Count user groups ----------
app.get("/count_user_groups", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const user_groups = await User_groups.find({ user_id: session.user_id });
const user_groups_count = user_groups.length;
res.status(200).json({ user_groups_count });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ********************************** //
// ********** Posts Model ********** //
// ********************************** //
// ---------- Get All Posts ----------
app.get("/posts", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
let userGroups = req.query.groups;
var posts = {};
if (userGroups) {
userGroups = JSON.parse(userGroups);
posts = await Posts.find({ group_name: { $in: userGroups } });
} else {
posts = await Posts.find({});
}
res.status(200).json({ posts });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
//----------- Get Post By ID -------------
app.get('/posts_id/:postId', async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
const post_id = req.params.postId;
try {
const foundPost = await Posts.findById(post_id);
if (!foundPost) {
return res.status(404).json({ error: 'Post not found' });
}
return res.status(200).json({ post: foundPost });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
});
// ---------- Create Post ----------
app.post("/create_post", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const user = await Users.findById(session.user_id);
const today = new Date();
const dd = String(today.getDate()).padStart(2, '0');
const mm = String(today.getMonth() + 1).padStart(2, '0');
const yyyy = today.getFullYear();
const currentDate = `${dd}.${mm}.${yyyy}`;
var data = {
user_id: session.user_id,
created: currentDate,
type: "event",
title: req.body.title,
pic: req.body.profilePictureUrl,
host: user.first_name + " " + user.last_name,
duration: req.body.duration,
location: req.body.location,
description: req.body.description,
likes: 0,
did: 0,
comments: 0,
group_name: req.body.group,
date: req.body.date,
time: req.body.time,
status: "pending"
};
var db = mongoose.connection;
const result = await db.collection("posts").insertOne(data);
const post_id = result.insertedId;
createLog("Post Created", `${post_id}`, req);
return res.redirect("http://127.0.0.1:5500/index.html");
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Update Post By ID ----------
app.post("/update_post/:post_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
const post_id = req.params.post_id;
try {
var data = {
user_id: req.body.firstName,
created: req.body.created,
type: req.body.type,
title: req.body.title,
host: req.body.host,
duration: req.body.duration,
location: req.body.location,
description: req.body.description,
group_name: req.body.group_name,
likes: req.body.likes,
did: req.body.did,
date: req.body.date,
time: req.body.time,
status: req.body.status
};
console.log(req.body);
cover_pic_url = req.body.pic;
console.log(cover_pic_url);
if (cover_pic_url != "") {
data.pic = cover_pic_url;
}
const updatedFields = data;
console.log(updatedFields);
const updatedPost = await Posts.findByIdAndUpdate(post_id, updatedFields, {
new: true,
});
if (!updatedPost) {
return res.status(404).json({ message: "User not found" });
}
createLog("Post Update", `Updated: ${post_id}`, req, updatedPost);
return res.status(200).json(updatedPost);
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Delete Post by ID ----------
app.post("/delete_post/:post_id", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const post_id = req.params.post_id;
const post = await Posts.findById(post_id);
if (!post) {
return res.status(404).json({ message: "Post not found" });
}
await post.deleteOne();
createLog("Delete Post", `${post_id}`, req);
res.status(200).json({ message: "Post deleted successfully" });
} catch (error) {
console.error("Error deleting post:", error);
res.status(500).json({ message: "Failed to delete post" });
}
});
// ---------- Get Posts by Group Name ----------
app.get("/posts/:group_name", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const posts = await Posts.find({ group_name: req.params.group_name });
res.status(200).json({ posts });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get Posts by User ID ----------
app.get("/posts/get_posts/:user_id", async (req, res) => {
try {
user_id = req.params.user_id;
const posts = await Posts.find({ user_id: user_id });
res.status(200).json({ posts });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get Posts by Group Name ----------
app.get("/posts/:group_name", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const posts = await Posts.find({ group_name: req.params.group_name });
res.status(200).json({ posts });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Approve Post ----------
app.post("/approve_post/:post_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
const post_id = req.params.post_id;
try {
var data = {
status: 'approved'
};
const updatedFields = data;
const updatedPost = await Posts.findByIdAndUpdate(post_id, updatedFields, {
new: true,
});
if (!updatedPost) {
return res.status(404).json({ message: "Post not found" });
}
createLog("Post Approved", `${post_id}`, req, updatedPost);
return res.status(200).json(updatedPost);
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get Posts Pending Count ----------
app.get("/get_pendings", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const pending_posts = await Posts.find({ status: "pending" });
const pending_posts_count = pending_posts.length;
res.status(200).json({ pending_posts_count });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// *********************************** //
// ********** Groups Model ********** //
// *********************************** //
// ---------- Get All Groups ----------
app.get("/groups", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const groups = await Groups.find({});
res.status(200).json({ groups });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Create a Group ----------
app.post("/create_group", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
group_name = req.body.group_name;
try {
var data = {
group_name: req.body.group_name,
pic: req.body.pic,
status: req.body.status
};
var db = mongoose.connection;
const result = await db.collection("groups").insertOne(data);
createLog("Group Created", `${group_name}`, req, result);
res.status(200).json({ result });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Update Group By ID ----------
app.post("/update_group/:group_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
const group_id = req.params.group_id;
try {
var data = {
group_name: req.body.group_name,
pic: req.body.pic,
status: req.body.status
};
const updatedFields = data;
const updatedGroup = await Groups.findByIdAndUpdate(group_id, updatedFields, {
new: true,
});
if (!updatedGroup) {
return res.status(404).json({ message: "Group not found" });
}
createLog("Group Update", `Updated: ${group_id}`, req, updatedGroup);
return res.status(200).json(updatedGroup);
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Delete Group By ID ----------
app.post("/delete_group/:group_id", async (req, res) => {
if (!checkSession("admin")) return res.status(401).json({ message: "Unauthorized" });
try {
const group_id = req.params.group_id;
const group = await Groups.findById(group_id);
if (!group) {
return res.status(404).json({ message: "Group not found" });
}
await group.deleteOne();
createLog("Group Deleted", `${group_id}`, req);
res.status(200).json({ message: "Group deleted successfully" });
} catch (error) {
console.error("Error deleting group:", error);
res.status(500).json({ message: "Failed to delete group" });
}
});
// ---------- Group Status By Group Name ----------
app.get("/group_status/:group_name", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const group_name = req.params.group_name;
const group = await Groups.find({ group_name: group_name });
if (!group) {
return res.status(404).json({ message: "Group not found" });
}
group_status = group[0].status;
res.status(200).json({ group_status });
} catch (error) {
console.error("Error returning group status:", error);
res.status(500).json({ message: "Error returning group status" });
}
});
// *********************************** //
// ********** Comments Model ********** //
// *********************************** //
//----------- Add Comment API -------------
app.post('/add_comment/:postId', async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
const postId = req.params.postId;
const sessionUserId = session.user_id;
console.log(postId);
try {
const foundPost = await Posts.findById(postId);
if (!foundPost) {
return res.status(404).json({ error: 'Post not found' });
}
console.log("comments counter = " + foundPost.comments);
CountComments = foundPost.comments + 1;
const foundUser = await Users.findById(sessionUserId);
if (!foundUser) {
return res.status(404).json({ error: 'User not found' });
}
data = {
post_id: postId,
user_id: sessionUserId,
first_name: foundUser.first_name,
last_name: foundUser.last_name,
description: req.body.description,
date: currentDate,
time: currentTime
}
var db = mongoose.connection;
const results = await db.collection("comments").insertOne(data);
console.log("comments data:" + data.description);
console.log(results);
const updatedPost = await Posts.findByIdAndUpdate(postId, { comments: CountComments }, {
new: true,
});
if (!updatedPost) {
return res.status(404).json({ message: "post not found" });
}
console.log(data);
return res.status(200).json({ message: 'Comments updated successfully', comment: data, comment_id: results.insertedId });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
});
// ---------- Get All Comments ----------
app.get("/comments", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const comments = await Comments.find({});
res.status(200).json({ comments });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Get Comments By Post ID ----------
app.get("/comments/:post_id", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const comments_res = await Comments.find({ post_id: req.params.post_id });
if (!comments_res) {
return res.status(404).json({ message: "Comment not found" });
}
res.status(200).json({ comments_res });
} catch (error) {
console.log(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Update Comment By ID ----------
app.post("/update_comment/:comment_id", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
const comment_id = req.params.comment_id;
try {
var data = {
post_id: req.body.post_id,
user_id: req.body.user_id,
first_name: req.body.first_name,
last_name: req.body.last_name,
description: req.body.description,
date: req.body.date,
time: req.body.time,
};
const updatedFields = data;
const updatedComment = await Comments.findByIdAndUpdate(comment_id, updatedFields, {
new: true,
});
if (!updatedComment) {
return res.status(404).json({ message: "Comment not found" });
}
createLog("Comment Update", `Updated: ${comment_id}`, req, updatedComment);
return res.status(200).json(updatedComment);
} catch (error) {
console.error(error);
res.status(500).json({ message: error.message });
}
});
// ---------- Delete Comment By ID ----------
app.post("/delete_comment/:comment_id", async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });
try {
const comment_id = req.params.comment_id;
const comment = await Comments.findById(comment_id);
if (!comment) {
return res.status(404).json({ message: "Comment not found" });
}
const post_id = comment.post_id;
await comment.deleteOne();
const post = await Posts.findById(post_id);
new_comments_counter = post.comments - 1;
data = {
comments: new_comments_counter
}
const updatedPost = await Posts.findByIdAndUpdate(post_id, data, {
new: true,
});
if (!updatedPost) {
return res.status(404).json({ message: "post not found" });
}
createLog("Delete Comment", `${comment_id}`, req);
res.status(200).json({ message: "Comment deleted successfully" });
} catch (error) {
console.error("Error deleting comment:", error);
res.status(500).json({ message: "Failed to delete comment" });
}
});
// ********************************* //
// ********** Like Model ********** //
// ********************************* //
//----------- Like API -------------
app.post('/like_posts/:postId', async (req, res) => {
if (!checkSession("user")) return res.status(401).json({ message: "Unauthorized" });