-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-old.js
1309 lines (1272 loc) · 40.6 KB
/
server-old.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
// jshint -W014
// ? PACKAGES //////////////////////////////////////////////////////////////////////////////////////////
const { check, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const ejs = require('ejs');
const express = require('express');
const expressIp = require('express-ip');
const fileUpload = require('express-fileupload');
const fs = require('fs');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo');
const nodemailer = require('nodemailer');
const path = require('path');
const session = require('express-session');
const csrf = require('csurf');
require('dotenv').config();
require('express-async-errors');
// const passport = require('passport');
// const { MongoClient } = require('mongodb');
// const utils = require('util');
// const { readFile, writeFile } = require('fs');
//? DATA IMPORT //////////////////////////////////////////////////////////////////////////////////////////
const data = require('./data/data');
// ? MIDDLEWARE & FUNCTION IMPORTS /////////////////////////////////////////////////////////////////////
const authenticate = require('./middleware/authenticate');
const errorHandler = require('./middleware/errorHandler');
const { createAccountLimiter } = require('./middleware/rate-limit');
const {
testDatabaseConnection,
countDocuments,
createUser,
checkUser,
requestData,
updateUserData,
updateData,
createArticle,
} = require('./config/database');
testDatabaseConnection();
const csrfProtection = csrf({ cookie: true });
const validateFileExtensions = require('./middleware/validateFileExtensions');
// ? /////////////////////////////////////////////////////////////////////////////////////////////////////
const app = express();
// ? ///////////////////////////////// GLOBAL MIDDLEWARE ///////////////////////////////////////////////
// view engine
app.set('view engine', 'ejs');
// public files
app.use(express.static('./public'));
// parse form data
app.use(bodyParser.urlencoded({ extended: false }));
// parse json
app.use(bodyParser.json());
//handles cross-origin-resource-sharing
app.use(cors());
// handles cookies
app.use(cookieParser());
// sets ip-related information
app.use(expressIp().getIpInfoMiddleware);
// handles sessions required for user authentication and authorization
app.use(
session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 1000 * 60 * 60 * 24 }, // Session cookie expires in one day(s)
resave: false,
saveUninitialized: true,
store: MongoStore.create({
clientPromise: mongoose
.connect(process.env.DATABASE_CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((m) => m.connection.getClient()),
dbName: 'Zeerum',
collection: 'sessions',
stringify: false,
autoRemove: 'interval',
autoRemoveInterval: 1,
}),
})
);
// ? /////////////////////////////////// MAIN ROUTES ///////////////////////////////////////////////
app.get('/', csrfProtection, (req, res) => {
res.render('index', { status: 'Development in progress.', csrfToken: req.csrfToken() });
});
app.get('/discover', csrfProtection, (req, res) => {
res.render('discover', { csrfToken: req.csrfToken() });
});
app.get('/write', csrfProtection, (req, res) => {
res.render('write', { csrfToken: req.csrfToken() });
});
app.get('/about', csrfProtection, (req, res) => {
res.render('about', { csrfToken: req.csrfToken() });
});
app.get('/login', csrfProtection, (req, res) => {
if (req.session.userId !== undefined || req.session.username)
res.status(307).redirect('/profile');
else res.render('login', { csrfToken: req.csrfToken() });
});
app.get('/signup', csrfProtection, (req, res) => {
if (req.session.username || req.session.userId !== undefined)
res.status(307).redirect('/profile');
else res.render('signup', { csrfToken: req.csrfToken() });
});
app.get('/profile', csrfProtection, authenticate, (req, res) => {
res.render('profile', { csrfToken: req.csrfToken() });
});
app.get('/404', csrfProtection, (req, res) => {
res.render('404', { csrfToken: req.csrfToken() });
});
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) console.log(err);
res.status(308).redirect('/');
});
});
//? //////////////////////////////////////////////////////////////////
/*
.replace(/[^a-zA-Z0-9\s]/gm, '')
.replace(/\s/gm, '-')
.replace(/-$/gm, '')
.toLowerCase()
*/
app.get('/articles/:article', csrfProtection, async (req, res, next) => {
const articleId = isNaN(Number(req.params.article))
? req.params.article
: Number(req.params.article);
const articleData = isNaN(articleId)
? await requestData('articles', { urlSafeTitle: articleId })
: await requestData('articles', { articleId: articleId });
// console.log(articleId, articleData);
if (articleData.success && articleData.data.length !== 0)
res.render('article', { csrfToken: req.csrfToken() });
else next();
});
app.get('/categories/:category', csrfProtection, async (req, res, next) => {
const category = isNaN(Number(req.params.category))
? req.params.category.toLowerCase()
: Number(req.params.category);
const categoryData = isNaN(category)
? await requestData('categories', { name: { $regex: new RegExp(category, 'i') } })
: await requestData('categories', { categoryId: category });
if (categoryData.success && categoryData.data.length !== 0)
res.render('categories', { csrfToken: req.csrfToken() });
else next();
});
app.get('/search/:searchItem', csrfProtection, (req, res) => {
res.render('categories', { csrfToken: req.csrfToken() });
});
app.get('/user/:user', csrfProtection, async (req, res, next) => {
const userId = isNaN(Number(req.params.user)) ? req.params.user : Number(req.params.user);
if (
req.session.userId !== undefined &&
(req.session.userId === userId || userId.toString().toLowerCase() === req.session.username)
)
res.redirect('/profile');
else {
const userData = isNaN(userId)
? await checkUser({
firstName: userId.split('-')[0].replace(/^\w/, (x) => x.toUpperCase()),
lastName: userId.split('-')[1].replace(/^\w/, (x) => x.toUpperCase()),
})
: await checkUser({ userId: userId });
// console.log(userId, userData);
if (userData.success && userData.isThereAUser)
res.render('user', { csrfToken: req.csrfToken() });
else next();
}
});
// ? ///////////////////////// Data GET and POST requests ////////////////////////////////////////
app.get('/data/search/:searchPhrase', async (req, res, next) => {
const searchPhrase = req.params.searchPhrase;
// console.log(searchPhrase);
const articleData = await requestData('articles', {
title: { $regex: new RegExp(`${searchPhrase}`, 'i') },
});
const categoryData = await requestData('categories', {
name: { $regex: new RegExp(`${searchPhrase}`, 'i') },
});
const userData = await checkUser(
{
username: { $regex: new RegExp(`${searchPhrase}`, 'i') },
},
{ _id: false, password: false }
);
if (articleData.success || categoryData.success || userData.success) {
if (
articleData.data.length !== 0 ||
categoryData.data.length !== 0 ||
userData.isThereAUser
) {
const results = {
articles: articleData.data || [],
users: userData.userData || [],
categories: categoryData.data || [],
};
// console.log(searchPhrase, results);
res.status(200).json({
success: true,
status: 200,
message: 'Request successful.',
results: results,
});
} else
res.status(404).json({
success: false,
status: 404,
message: 'Result cannot be found. Try searching using different keywords.',
});
} else
res.status(500).json({ success: false, message: 'Error occurred. Please try again later.' });
});
app.get(
'/data/articles',
// ? FOR ACCESSING ALL THE ARTICLES. ** CAN BE REMOVED IN THE FUTURE **
async (req, res, next) => {
if (Object.entries(req.query).length === 0) {
const articleData = await requestData('articles');
// Sorts the data from latest to oldest
articleData.data.sort(
(a, b) => new Date(b.releasedDate).getTime() - new Date(a.releasedDate).getTime()
);
if (articleData.success && articleData.data.length !== 0)
res.status(200).json({
success: true,
status: 200,
message: `Request successful.`,
data: articleData.data,
ipInfo: req.ipInfo,
});
else
res.status(404).json({
success: false,
status: 404,
message: 'No articles found. Please try again later.',
});
} else next();
},
// ? FOR ACCESSING ARTICLES FILTERED BY THE AUTHOR ID
async (req, res, next) => {
if (req.query.authorUserId) {
const authorUserId = isNaN(Number(req.query.authorUserId))
? req.query.authorUserId
: Number(req.query.authorUserId);
const articleData = isNaN(authorUserId)
? await requestData('articles', {
'author.name': `${authorUserId
.split('-')[0]
.replace(/^\w/, (x) => x.toUpperCase())} ${authorUserId
.split('-')[1]
.replace(/^\w/, (x) => x.toUpperCase())}`,
})
: await requestData('articles', {
'author.userId': Number(authorUserId),
});
if (articleData.success && articleData.data.length !== 0) {
res.status(200).json({
success: true,
status: 200,
message: `Request successful.`,
data: articleData.data,
});
} else
res.status(404).json({
success: false,
status: 404,
message: 'No articles found. Please try again later.',
});
} else next();
},
// ? FOR REQUESTING ARTICLES BOOKMARKED BY THE USER
async (req, res, next) => {
if (req.query.userBookmarked === 'true') {
const articleData = await requestData('articles', {
'reactions.bookmarks': req.session.userId,
});
if (articleData.success && articleData.data.length > 0) {
res.json({
success: true,
status: 200,
message: 'Request successful.',
data: articleData.data,
});
} else
res.json({ success: false, status: 404, message: 'No user bookmarked articles found' });
} else next();
},
// ? ARTICLES FILTERED BY ITS' RESPECTIVE TAG
async (req, res, next) => {
if (req.query.categoryId) {
const category = isNaN(Number(req.query.categoryId))
? req.query.categoryId
: await requestData(
'categories',
{ categoryId: 1 },
{ categoryId: false, pictureUrl: false }
).then((x) => x.data[0].name);
// console.log(category);
const articleData = await requestData('articles', {
categories: { $regex: RegExp(category, 'i') },
});
// console.log(category, articleData);
if (articleData.success && articleData.data.length !== 0) {
res.json({
success: true,
status: 200,
message: `Request successful.`,
category: category,
data: articleData,
});
} else next();
}
},
(req, res, next) => {
res.status(404).json({
success: false,
status: 404,
message: `We couldn't find find what you were looking for`,
});
}
);
// ? GET REQUEST TO REQUEST ARTICLE DATA, AND STORE LIKE, BOOKMARK, SHARE RESULTS.
app.get(
'/data/articles/:article',
// SHARE ARTICLE
async (req, res, next) => {
if (req.query.shareArticle === 'true') {
const article = await requestData('articles', { urlSafeTitle: req.params.article })
.then((res) => res.data[0])
.catch((err) => next(err));
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'reactions.shares': article.reactions.shares + 1 } }
);
res.json({ success: true, status: 200, message: `You shared ${req.params.article}` });
} else if (req.query.shareArticle === 'false') {
res.json({
success: false,
status: 400,
message: `Invalid request to share articles ${req.params.article}`,
});
} else next();
},
// SEND ARTICLE DATA
async (req, res) => {
const article = isNaN(Number(req.params.article))
? req.params.article
: Number(req.params.article);
const articleData = isNaN(article)
? await requestData('articles', { urlSafeTitle: article })
: await requestData('articles', { articleId: article });
if (
articleData.success &&
articleData.data.length !== 0 &&
(articleData.data[0].title
.replace(/[^a-zA-Z0-9\s]/gm, '')
.replace(/\s/gm, '-')
.replace(/-$/gm, '')
.toLowerCase() === article ||
articleData.data[0].articleId === article)
) {
const { updatedData: authorData } = await updateUserData(
{ userId: articleData.data[0].author.userId },
{
$set: {
authorData: {
allTimeViews: articleData.data[0].views.allTime + 1,
allTimeLikes: articleData.data[0].reactions.likes.length,
},
},
},
true
);
const { updatedData: updatedArticleData } = await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'views.allTime': articleData.data[0].views.allTime + 1 } },
true
);
// // ? FOR SORTING COMMENTS BY ITS CREATED DATE FROM LATEST TO OLDEST
// const comments = articleData.data[0].comments.sort(
// (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
// );
// updatedArticleData[0].comments = comments;
if (req.session.user) {
res.status(200).json({
success: true,
status: 200,
data: {
article: updatedArticleData[0],
author: {
userId: authorData.userId,
firstName: authorData.firstName,
lastName: authorData.lastName,
fullName: `${authorData.firstName}-${authorData.lastName}`,
profilePictureUrl: authorData.profilePictureUrl,
},
user: {
followers: req.session.user.followers || null,
followings: req.session.user.followings || null,
},
},
});
} else
res.status(200).json({
success: true,
status: 200,
data: {
article: updatedArticleData[0],
author: {
userId: authorData.userId,
firstName: authorData.firstName,
lastName: authorData.lastName,
fullName: `${authorData.firstName}-${authorData.lastName}`,
profilePictureUrl: authorData.profilePictureUrl,
},
user: undefined,
},
});
} else
res.status(404).json({
success: false,
message: `There is no article/articleId named ${req.params.article}`,
});
}
);
// ? POST REQUEST TO /DATA/ARTICLES/:ARTICLE FOR LIKING ARTICLES, BOOKMARKING ARTICLES, ADDING COMMENTS, LIKING COMMENTS.
app.post(
'/data/articles/:article',
authenticate,
// ? LIKE ARTICLE
async (req, res, next) => {
if (req.query.likeArticle) {
// ? IF YOU REQUEST TO LIKE THE ARTICLE
const article = await requestData('articles', { urlSafeTitle: req.params.article }).then(
(res) => res.data[0]
);
if (req.query.likeArticle === 'true' && req.session.userId !== undefined) {
if (!article.reactions.likes.includes(Number(req.session.userId))) {
// ? if you haven't liked the same article before
article.reactions.likes.push(req.session.userId);
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'reactions.likes': article.reactions.likes } }
);
res.json({ success: true, status: 200, message: `You liked ${req.params.article}` });
} else {
// ? if you have liked the same article before
res.json({
success: false,
status: 400,
message: `You have already liked ${req.params.article}`,
});
}
} else if (req.query.likeArticle === 'false' && req.session.userId !== undefined) {
if (article.reactions.likes.includes(Number(req.session.userId))) {
// ? if you haven't liked the same article before
const likedIdPosition = article.reactions.likes.indexOf(req.session.userId);
article.reactions.likes.splice(likedIdPosition, 1);
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'reactions.likes': article.reactions.likes } }
);
res.json({
success: true,
status: 200,
message: `You disliked ${req.params.article}`,
});
} else {
// ? if you have liked the same article before
res.json({
success: false,
status: 400,
message: `You have already disliked ${req.params.article}`,
});
}
} else
res.json({
success: false,
status: 400,
message: `Invalid request to like ${req.params.article}`,
});
} else next();
},
//? BOOKMARK ARTICLE
async (req, res, next) => {
if (req.query.bookmarkArticle) {
// ? If you request to share the article
const user = req.session.user;
const article = await requestData('articles', { urlSafeTitle: req.params.article }).then(
(res) => res.data[0]
);
if (req.query.bookmarkArticle === 'true' && req.session.userId !== undefined) {
if (!article.reactions.bookmarks.includes(Number(req.session.userId))) {
// ? if you haven't bookmarked the same article before
article.reactions.bookmarks.push(Number(req.session.userId));
user.bookmarks.push(Number(article.articleId));
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'reactions.bookmarks': article.reactions.bookmarks } }
);
await updateUserData(
{ userId: req.session.userId },
{ $set: { bookmarks: user.bookmarks } }
);
req.session.user.bookmarks = user.bookmarks;
res.json({ success: true, status: 200, message: `You liked ${req.params.article}` });
} else {
// ? if you have bookmarked the same article before
res.json({
success: false,
status: 400,
message: `You have already bookmarked ${req.params.article}`,
});
}
} else if (req.query.bookmarkArticle === 'false' && req.session.userId !== undefined) {
if (article.reactions.bookmarks.includes(Number(req.session.userId))) {
// ? if you haven't un-bookmarked the same article before
const userBookmarkedIdPosition = user.bookmarks.indexOf(article.articleId);
const bookmarkedIdPosition = article.reactions.bookmarks.indexOf(req.session.userId);
article.reactions.bookmarks.splice(bookmarkedIdPosition, 1);
user.bookmarks.splice(userBookmarkedIdPosition, 1);
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { 'reactions.bookmarks': article.reactions.bookmarks } }
);
await updateUserData(
{ userId: req.session.userId },
{ $set: { bookmarks: user.bookmarks } }
);
req.session.user.bookmarks = user.bookmarks;
res.json({
success: true,
status: 200,
message: `You un-bookmarked ${req.params.article}`,
});
} else {
// ? if you have un-bookmarked the same article before
res.json({
success: false,
status: 400,
message: `You have already un-bookmarked ${req.params.article}`,
});
}
} else
res.json({
success: false,
message: `Invalid request to bookmark on ${req.params.article}`,
});
} else next();
},
// ? FOR COMMENTING ON THE ARTICLE
async (req, res, next) => {
if (req.query.commentOnArticle && req.body.userId && req.body.commentContent) {
const { userId, commentContent } = req.body;
if (!isNaN(Number(userId)) && typeof commentContent === 'string') {
const article = await requestData('articles', {
urlSafeTitle: req.params.article,
}).then((res) => res.data[0]);
article.comments.push({
userId: Number(userId),
date: new Date(),
isEdited: false,
editedDate: null,
comment: commentContent,
likedUsers: [],
replies: [],
});
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { comments: article.comments } }
).then((result) => {
if (result.success) {
res.json({
success: true,
status: 200,
commentId: article.comments.length - 1,
message: `Commented on ${req.params.article}`,
});
}
});
} else
res.json({
success: false,
status: 400,
message: `Invalid request to comment to article ${req.paramas.article} without required parameters`,
});
} else next();
},
async (req, res, next) => {
// to like and unlike comments
if (req.query.likeComment) {
const { commentId, userId, likeComment } = req.query;
// console.log('commentId', commentId, 'userId', userId, 'likeComment', likeComment);
if (!isNaN(Number(commentId)) && !isNaN(Number(userId)) && likeComment !== null) {
const article = await requestData('articles', {
urlSafeTitle: req.params.article,
}).then((res) => res.data[0]);
if (likeComment === 'true') {
if (!article.comments[Number(commentId)].likedUsers.includes(Number(userId))) {
// if you haven't liked the same comment before
article.comments[Number(commentId)].likedUsers.push(Number(userId));
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { comments: article.comments } }
);
res.json({
success: true,
status: 200,
message: `Liked comment with id ${commentId} by user with id ${userId}`,
});
} else {
// if you have liked the same comment before
res.json({
success: false,
status: 400,
message: `You have already liked the comment with id ${commentId} on ${req.params.article}.`,
});
}
} else if (likeComment === 'false') {
if (article.comments[Number(commentId)].likedUsers.includes(Number(userId))) {
// if you haven't dis-liked this comment before
const userIdPosition = article.comments[Number(commentId)].likedUsers.indexOf(
Number(userId)
);
article.comments[Number(commentId)].likedUsers.splice(userIdPosition, 1);
await updateData(
'articles',
{ urlSafeTitle: req.params.article },
{ $set: { comments: article.comments } }
);
res.json({
success: true,
status: 200,
message: `Disliked comment with id ${commentId} by user with id ${userId}`,
});
} else {
res.json({
success: false,
status: 400,
message: `You have already disliked this comment before.`,
});
}
}
} else
res.json({
success: false,
status: 400,
message: `Invalid request to /data//articles/${req.params.article}?likeComment without required parameters.`,
});
} else
res.json({
success: false,
status: 400,
message: `Invalid request to /data/articles/${req.params.article}`,
});
}
);
app.get('/data/users/:user', async (req, res, next) => {
let user = isNaN(Number(req.params.user)) ? req.params.user : Number(req.params.user);
const userData = isNaN(Number(req.params.user))
? await checkUser(
{
firstName: user.split('-')[0].replace(/^\w/, (x) => x.toUpperCase()),
lastName: user.split('-')[1].replace(/^\w/, (x) => x.toUpperCase()),
},
{ password: false }
)
: await checkUser({ userId: user }, { email: false, password: false });
if (userData.isThereAUser)
res.status(200).json({
success: true,
status: 200,
message: 'Request successful.',
data: userData.userData[0],
});
else
res.status(404).json({
success: false,
message: `There is no user with the name/id ${req.params.user}`,
});
});
app.get('/data/categories', async (req, res) => {
const categoryData = await requestData('categories');
if (categoryData.success)
res.status(200).json({
success: true,
status: 200,
message: `Request successful.`,
data: categoryData.data,
});
else
res.json({
success: false,
status: 404,
message: 'No categories found. Please try again later.',
});
});
app.get('/data/categories/:category', async (req, res) => {
const category = isNaN(Number(req.params.category))
? req.params.category
: Number(req.params.category);
const categoryData = isNaN(category)
? await requestData('categories', { name: category.replace(/^\w/, (x) => x.toUpperCase()) })
: await requestData('categories', { categoryId: category });
if (categoryData.success && categoryData.data.length !== 0)
res.status(200).json({ success: true, status: 200, data: categoryData.data });
else
res.status(404).json({
success: false,
status: 404,
message: `There is no category/categoryId named ${req.params.category}`,
});
});
app.get(
'/data/profile',
authenticate,
async (req, res, next) => {
if (req.query.followUser !== undefined && req.query.followingUserId) {
// console.log(req.query.followUser, req.query.followingUserId);
let userData = await checkUser({ userId: req.session.userId });
const followingUserId = Number(req.query.followingUserId);
let followingUserData = await checkUser({ userId: followingUserId });
if (req.query.followUser === 'true') {
// ? If use wants to follow
if (followingUserData.success && followingUserData.isThereAUser && userData.success) {
if (!userData.userData[0].followings.includes(followingUserId)) {
userData.userData[0].followings.push(Number(followingUserId));
followingUserData.userData[0].followers.push(Number(req.session.userId));
// console.log(
// userData.userData[0].followings,
// followingUserData.userData[0].followers
// );
await updateUserData(
{ userId: req.session.userId },
{ $set: { followings: userData.userData[0].followings } }
);
await updateUserData(
{ userId: followingUserId },
{ $set: { followers: followingUserData.userData[0].followers } }
);
req.session.user = userData.userData[0];
//? if you haven't followed the same user before
// console.log(req.query.followUser, req.query.followingUserId);
res.json({
success: true,
status: 200,
message: `Followed ${followingUserData.userData[0].username} by ${req.session.username}`,
});
} else {
// ? if you have followed the same user before
res.status(400).json({
success: false,
status: 400,
message: `You have already followed ${followingUserData.userData[0].username}`,
});
}
} else {
res.json({ success: false, message: 'Follow request failed' });
}
} else {
//? If user wants to unfollow
if (followingUserData.success && followingUserData.isThereAUser && userData.success) {
// ? if you haven't unfollowed the same user before
if (userData.userData[0].followings.includes(followingUserId)) {
const positionUser = userData.userData[0].followings.indexOf(followingUserId);
const positionFollowing = followingUserData.userData[0].followers.indexOf(
Number(req.session.userId)
);
// console.log(userData.userData[0]);
userData.userData[0].followings.splice(positionUser, 1);
followingUserData.userData[0].followers.splice(positionFollowing, 1);
await updateUserData(
{ userId: req.session.userId },
{ $set: { followings: userData.userData[0].followings } }
);
await updateUserData(
{ userId: followingUserId },
{ $set: { followers: followingUserData.userData[0].followers } }
);
req.session.user = userData.userData[0];
res.json({
success: true,
status: 200,
message: `Unfollowed ${followingUserData.userData[0].username} by ${req.session.username}`,
});
} else {
// ? if you have unfollowed the same user before
res.status(400).json({
success: false,
status: 400,
message: `You have already unfollowed ${followingUserData.userData[0].username}`,
});
}
} else res.json({ success: false, message: 'Unfollow request failed' });
}
} else next();
},
// ? CHANGE USER TYPE
async (req, res, next) => {
if (req.query.changeUserType) {
const user = req.session.user;
if (req.query.changeUserType === 'author' && user.userType === 'reader') {
user.userType = 'author';
const { updatedData } = await updateUserData(
{ userId: req.session.userId },
{
$set: {
userType: 'author',
authorData: {
allTimeViews: 0,
allTimeLikes: 0,
},
},
},
true
);
// console.log(`updated data`, updatedData);
req.session.user = user;
res.json({
success: true,
status: 200,
message: `Success on becoming a ${req.query.changeUserType}.`,
});
} else if (req.query.changeUserType === 'reader' && user.userType === 'author') {
user.userType = 'reader';
// console.log(user);
const { updatedData } = await updateUserData(
{ userId: req.session.userId },
{
$set: { userType: 'reader' },
$unset: { authorData: 1 },
},
true
);
req.session.user = user;
res.json({
success: true,
status: 200,
message: `Success on becoming a ${req.query.changeUserType}.`,
});
} else
res.status(400).json({
success: false,
message: `You are already a ${req.session.user.userType}`,
});
} else next();
},
async (req, res) => {
const {
userId,
firstName,
lastName,
profilePictureUrl,
followers,
followings,
registeredDate,
userType,
country,
bookmarks,
} = req.session.user;
// const articlesPublished = async (userId) => {
// const articleData = await requestData('articles', { 'author.userId': userId });
// if (articleData.success && articleData.data.length !== 0) return articleData.data.length;
// else return 0;
// };
const articleData = await requestData('articles', { 'author.userId': userId });
if (articleData.success && articleData.data.length !== 0) {
const { data } = await articleData;
let allTimeViews = 0;
let allTimeLikes = 0;
data.forEach((article) => {
allTimeLikes += article.reactions.likes.length;
allTimeViews += article.views.allTime;
});
res.status(200).json({
success: true,
status: 200,
message: `Request successful.`,
data: {
userId: userId,
firstName: firstName,
lastName: lastName,
profilePictureUrl: profilePictureUrl,
followers: followers,
followings: followings,
registeredDate: registeredDate,
userType: userType,
country: country,
articlesPublished: data.length,
bookmarks: bookmarks,
allTimeViews: allTimeViews,
allTimeLikes: allTimeLikes,
},
});
} else {
res.status(200).json({
success: true,
status: 200,
message: `Request successful.`,
data: {
userId: userId,
firstName: firstName,
lastName: lastName,
profilePictureUrl: profilePictureUrl,
followers: followers,
followings: followings,
registeredDate: registeredDate,
userType: userType,
country: country,
articlesPublished: 0,
bookmarks: bookmarks,
},
});
}
}
);
app.post(
'/data/upload/write/add-new-article',
authenticate,
// For validating if the user is an author.
(req, res, next) => {
if (req.session.user.userType !== 'author') {
res.json({
success: false,
status: 401,
message: 'Unauthorized. You need to be an author to write articles.',
});
} else next();
},
fileUpload({
useTempFiles: true,
tempFileDir: path.join(__dirname, './temp/'),
createParentPath: true,
preserveFilename: true,
preserveExtension: true,
debug: true,
}),
// for validating if the uploaded files have accepted mimetypes/extensions.
validateFileExtensions(['image/jpeg', 'image/png', 'image/webp']),
async (req, res, next) => {
if (
req.body.articleTitle &&
req.body.articleDescription &&
req.body.articleFootnotes &&
req.body.articleBody
) {
let { articleTitle, articleDescription, articleFootnotes, articleBody } = req.body;
const articleId = await countDocuments('articles');
if (req.files) {
let imageLocations = {
articleCoverImg: '',
articleImages: [],
};
const location = `./public/images/articles/${articleId}`;
fs.mkdir(location, (err) => {
if (err) console.log(err);
});
if (req.files.articleCoverImg) {
const articleCoverImg = req.files.articleCoverImg;
articleCoverImg.mv(
`${location}/articleCoverImg.${articleCoverImg.name.split('.').at(-1)}`,
async (err) => {
if (err) return next(err);