-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
826 lines (660 loc) · 27.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
import Express from "express";
import cors from "cors";
import { MongoClient, ServerApiVersion, ObjectId } from "mongodb";
import dotenv from "dotenv";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";
import Stripe from "stripe";
dotenv.config();
const app = Express();
const port = process.env.PORT || 5000;
// const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
app.use(
cors({
origin: [
"http://localhost:5100",
"http://localhost:5173",
"http://localhost:5174",
"http://localhost:5175",
"https://technest-blog.web.app",
"https://technest-blog.firebaseapp.com",
], // The domains where the client side will run
credentials: true, // This will help to set cookies
})
);
app.use(Express.json());
app.use(cookieParser());
/*
*/
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.cx7zh4x.mongodb.net/?retryWrites=true&w=majority`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
function extractuserEmail(req, method) {
if (method === "GET" || method === "DELETE") {
return req.query.email || "";
} else if (method === "POST" || method === "PUT" || method === "PATCH") {
return req.body.email || "";
} else {
return "";
}
}
function extractuserId(req, method) {
if (method === "GET" || method === "DELETE") {
return req.query.userId || "";
} else if (method === "POST" || method === "PUT" || method === "PATCH") {
return req.body.userId || "";
} else {
return "";
}
}
// middlewares
const verifyToken = async (req, res, next) => {
const token = req.cookies?.token;
if (!token) {
return res.status(401).send({ message: "unauthorized" });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
// error
if (err) {
console.log(err);
return res.status(401).send({ message: "unauthorized" });
}
req.user = decoded;
// if its valid it will be decoded
next();
});
};
const requestValidate = async (req, res, next) => {
const method = req.method;
let decoded_Email = req.user?.userEmail;
let decoded_UserId = req.user?.userId;
const userEmail = extractuserEmail(req, method);
const userId = extractuserId(req, method);
const requestedUrl = req.originalUrl;
// console.log({
// method,
// requestedUrl,
// decoded: { decoded_Email, decoded_UserId },
// url: { userEmail, userId },
// });
if (decoded_Email !== userEmail && decoded_UserId !== userId) {
return res.status(401).send({ message: "unauthorized" });
}
// console.log(200, "Authorized successfully.");
next();
};
// validate the token with query info. If matched calls to
const validateAndWishlistData02 = async (req, res, next) => {
const token = req.cookies?.token;
// req.user = null;
const userEmail = extractuserEmail(req, method);
const userId = extractuserId(req, method);
if (token) {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log("Invalid token");
console.log(err);
} else {
if (decoded.userEmail !== userEmail && decoded.userId !== userId) {
return res.status(401).send({ message: "unauthorized" });
}
req.user = decoded;
next();
}
});
}
next();
};
// validate the token with query info. If matched calls to
const validateAndWishlistData = async (req, res, next) => {
/*
Ekhane token theke info extract kora hocche.
Token valid hole ota req.user e set kora hbe, otherwise null theke jabe.
Tarpor req.user theke sohoje wishlist er jnno user id fetch kore show kora jabe.
*/
const token = req.cookies?.token;
req.user = null;
// console.log("tokeeen ", token);
if (token) {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log("Invalid token");
console.log(err);
} else {
req.user = decoded;
}
});
}
next();
};
async function mainProcess() {
try {
// await client.connect();
// await client.db("admin").command({ ping: 1 });
// console.log("Pinged your deployment. You successfully connected to MongoDB!");
const allBlogs = client.db("a11-technest").collection("blogs");
const editorsPick = client.db("a11-technest").collection("editors-pick");
const wishlist = client.db("a11-technest").collection("wishlist");
const comments = client.db("a11-technest").collection("comments");
const categoryNames = client.db("a11-technest").collection("category-names");
const users = client.db("a11-technest").collection("users");
// Admin verify middleware
const verifyAdmin = async (req, res, next) => {
let decoded_Email = req.user?.userEmail;
const query = { email: decoded_Email };
const userInfoResult = await users.findOne(query);
if (userInfoResult.role === "admin") {
next();
} else {
return res.status(403).send({ message: "forbidden access" });
}
};
// Authenticating
app.post("/authenticate", async (req, res) => {
const userEmail = req.body.email;
const userId = req.body.userId;
// console.log("from authenticate body email ", { userEmail, userId });
const token = jwt.sign({ userEmail, userId }, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "24h",
});
// For localhost
const cookieOptionsLocal = {
httpOnly: true, // jehetu localhost tai http only
secure: false, // localhost tai secure false
sameSite: false, // localhost and server er port different tai none
};
// const cookieOptionsProd = {
// httpOnly: true,
// secure: true,
// sameSite: "none",
// maxAge: 24 * 60 * 60 * 1000,
// };
// production
const cookieOptionsProd = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
};
res.cookie("token", token, cookieOptionsProd);
res.send({ success: true });
});
// Logout
app.post("/logout", async (req, res) => {
// res.clearCookie("token", { maxAge: 0 });
res.clearCookie("token", {
maxAge: 0,
secure: process.env.NODE_ENV === "production" ? true : false,
sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
});
res.send({ success: true });
});
// Payment intent api
app.post("/create-payment-intent", async (req, res) => {
const price = req.body.price;
const amount = parseInt(price * 100);
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: "usd",
payment_method_types: ["card"],
});
console.log(paymentIntent);
res.send({ clientSecret: paymentIntent.clientSecret });
});
// return user role
// verification is not mandatory!
// admin verified not added because its checking the admin role!
app.get("/role-check", verifyToken, requestValidate, async (req, res) => {
const targetedUserEmail = req.query.email;
const query = { email: targetedUserEmail };
const userInfoResult = await users.findOne(query);
let adminStatus = false;
if (userInfoResult.role === "admin") {
adminStatus = true;
}
res.send({ isAdmin: adminStatus });
});
// Admin request
// return all users
// Admin Verification required
app.get("/allUsers", verifyToken, requestValidate, verifyAdmin, async (req, res) => {
const query = {};
const allUsers = await users.find(query).toArray();
res.send(allUsers);
});
// Eta kivabe secure korbo bujhtesi na.
// user register, google/github login hole etay request ashe.
// Users insertion
app.post("/adduser", async (req, res) => {
const userInfo = req.body?.userInfo;
userInfo.role = "user"; // first register/login e shbai user e thakbe.
const query = { email: userInfo?.email };
const userExistence = await users.findOne(query);
if (!userExistence) {
// insert the user
const insertResult = await users.insertOne(userInfo);
if (insertResult.acknowledged) {
userInfo.newUser = true;
userInfo.insertion = true;
return res.send(userInfo);
} else {
userInfo.newUser = false;
userInfo.insertion = false;
return res.send(userInfo);
}
} else {
userInfo.newUser = false;
userInfo.insertion = false;
return res.send(userInfo);
}
});
// Admin request
// Make ADMIN api
// Admin Verification required
app.patch(
"/user/makeadmin",
verifyToken,
requestValidate,
verifyAdmin,
async (req, res) => {
const targetedUserEmail = req.query.targetedUserEmail;
const query = { email: targetedUserEmail };
const updateInformation = {
$set: {
role: "admin",
},
};
const updateResult = await users.updateOne(query, updateInformation);
console.log(updateResult);
res.send(updateResult);
}
);
// Admin request
// user DELETE
// Admin Verification required
app.delete("/userdelete", verifyToken, requestValidate, verifyAdmin, async (req, res) => {
const targetedUserEmail = req.query.targetedUserEmail;
const query = { email: targetedUserEmail };
const deleteResult = await users.deleteOne(query);
res.send(deleteResult);
});
// all blog Data Fetch
// open api
// sort and return
app.get("/allblogs", validateAndWishlistData, async (req, res) => {
// For testing purpose
console.log("All blogs requested");
// Search Data Collecting
const searchTitle = req.query.searchTitle;
let searchCategories = req.query.categories;
let sort_Date = req.query.sort_Date || "descending";
const sortTimeOrder =
sort_Date === "descending" ? -1 : sort_Date === "ascending" ? 1 : -1;
let allBlogsList = [];
let searchedBlogs = true;
if (!searchTitle && !searchCategories) {
// Return all data.
const query = {};
const cursor = allBlogs.find(query);
cursor.sort({ creationTime: sortTimeOrder });
allBlogsList = await cursor.toArray();
searchedBlogs = false;
} else {
// return search data
let query = {};
const options = {
sort: {
creationTime: sortTimeOrder,
},
};
if (searchTitle) {
query.title = { $regex: searchTitle, $options: "i" };
}
if (searchCategories) {
query.category = { $in: searchCategories.split(",") };
}
allBlogsList = await allBlogs.find(query, options).toArray();
}
// if user logged in there must be a token and it has been verified previously
// But if the user is not logged in, there will be no token and no data in req.user
// so the user id will be available in req.user and its simple to fetch wishlist data using that user id.
if (req.user) {
const userId = req.user.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
// No wishlist data available for that user, thats why its null
if (!wishListData) {
// console.log("No wishlist data available");
return res.send({ searchedBlogs, allBlogs: allBlogsList });
// return res.send(allBlogsList);
} else {
const wishLists = wishListData.wishLists;
// console.log("wishLists", wishLists);
// Now wishlists data will merge with the blogs data
let updatedAllBlogsList = [];
allBlogsList.forEach((blogData) => {
wishLists.forEach((wishlistBlogId) => {
if (blogData._id.equals(wishlistBlogId)) {
blogData.wishlist = true;
}
});
if (!blogData.wishlist) {
blogData.wishlist = false;
}
updatedAllBlogsList.push(blogData);
});
return res.send({ searchedBlogs, allBlogs: updatedAllBlogsList });
}
} else {
return res.send({ searchedBlogs, allBlogs: allBlogsList });
}
});
// recent blog Data Fetch
// open api
// sort and return
app.get("/recent-blogs", validateAndWishlistData, async (req, res) => {
// fetching recent blogs
const query = {};
const cursor = allBlogs.find(query);
cursor.sort({ creationTime: -1 });
cursor.limit(6);
const allBlogsList = await cursor.toArray();
// if user logged in there must be a token and it has been verified previously
// But if the user is not logged in, there will be no token and no data in req.user
// so the user id will be available in req.user and its simple to fetch wishlist data using that user id.
if (req.user) {
const userId = req.user.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
// No wishlist data available for that user, thats why its null
if (!wishListData) {
return res.send(allBlogsList);
} else {
const wishLists = wishListData.wishLists;
// Now wishlists data will merge with the blogs data
let updatedAllBlogsList = [];
allBlogsList.forEach((blogData) => {
wishLists.forEach((wishlistBlogId) => {
if (blogData._id.equals(wishlistBlogId)) {
blogData.wishlist = true;
}
});
if (!blogData.wishlist) {
blogData.wishlist = false;
}
updatedAllBlogsList.push(blogData);
});
return res.send(updatedAllBlogsList);
}
} else {
return res.send(allBlogsList);
}
});
// Editors pick blog data fetch
// open api
app.get("/editors-pick", validateAndWishlistData, async (req, res) => {
const query = {}; // fetching all data, thats's why no query
const cursor = editorsPick.find(query);
const editorsPick_ids_raw = await cursor.toArray();
// As the data return in array of object, taken only post_ids array.
const editorsPick_postId = editorsPick_ids_raw[0].editorsPick_postId;
// converted blog_id to ObjectId for find
const idsToFind = editorsPick_postId.map((blogId) => new ObjectId(blogId));
// fetching editors choice blogs from all blogs
const allBlogsList = await allBlogs.find({ _id: { $in: idsToFind } }).toArray();
// if user logged in there must be a token and it has been verified previously
// But if the user is not logged in, there will be no token and no data in req.user
// so the user id will be available in req.user and its simple to fetch wishlist data using that user id.
if (req.user) {
const userId = req.user.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
// No wishlist data available for that user, thats why its null
if (!wishListData) {
return res.send(allBlogsList);
} else {
const wishLists = wishListData.wishLists;
// Now wishlists data will merge with the blogs data
let updatedAllBlogsList = [];
allBlogsList.forEach((blogData) => {
wishLists.forEach((wishlistBlogId) => {
if (blogData._id.equals(wishlistBlogId)) {
blogData.wishlist = true;
}
});
if (!blogData.wishlist) {
blogData.wishlist = false;
}
updatedAllBlogsList.push(blogData);
});
return res.send(updatedAllBlogsList);
}
} else {
return res.send(allBlogsList);
}
});
// Wishlist blog data fetch
// Protected api
app.get("/wishlist", validateAndWishlistData, async (req, res) => {
if (req.user) {
const userId = req.user.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
// No wishlist data available for that user, thats why its null
if (!wishListData) {
return res.send([]);
} else {
const wishLists = wishListData.wishLists;
if (wishLists.length === 0) {
return res.send([]);
} else {
// converted blog_id to ObjectId for find
const idsToFind = wishLists.map((blogId) => new ObjectId(blogId));
// fetching wishlist blogs from all blogs
let wishlist_blogs = await allBlogs
.find({ _id: { $in: idsToFind } })
.toArray();
wishlist_blogs = wishlist_blogs.map((wishlistBlog) => {
wishlistBlog.wishlist = true;
return wishlistBlog;
});
res.send(wishlist_blogs);
}
}
} else {
return res.send([]);
}
});
// Featured List Data Fetch
// open api
app.get("/featured-blogs", async (req, res) => {
const query = {};
const cursor = allBlogs.find(query);
const allBlogsList = await cursor.toArray();
let largestBlogs = allBlogsList.sort((b, a) => {
if (a.longDescription.length < b.longDescription.length) {
return -1;
}
if (a.longDescription.length > b.longDescription.length) {
return 1;
}
return 0;
});
let topTenBlog = largestBlogs.slice(0, 10);
res.send(topTenBlog);
});
// Single Blog Data Fetch
// open api
app.get("/blogDetails/:blog_id", validateAndWishlistData, async (req, res) => {
// getting blog details
const blog_id = req.params.blog_id;
const blogDetailsQuery = { _id: new ObjectId(blog_id) };
const blogData = await allBlogs.findOne(blogDetailsQuery);
/* NEW DATA */
if (req.user) {
const userId = req.user.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
// No wishlist data available for that user, thats why its null
if (!wishListData) {
blogData.wishlist = false;
return res.send(blogData);
} else {
const wishLists = wishListData.wishLists;
wishLists.forEach((wishlistBlogId) => {
if (blogData._id.equals(wishlistBlogId)) {
blogData.wishlist = true;
}
});
if (!blogData.wishlist) {
blogData.wishlist = false;
}
return res.send(blogData);
}
} else {
blogData.wishlist = false;
return res.send(blogData);
}
});
// Send comments of that blog.
app.get("/comment-list/:blog_id", async (req, res) => {
const blog_id = req.params.blog_id;
const query = { blog_id: blog_id };
const commentList = await comments.findOne(query);
res.send(commentList);
});
// Open api
// name of the categories
app.get("/category-names", async (req, res) => {
const query = { collection: "categoryNames" };
const categoryCollection = await categoryNames.findOne(query);
// const editorsPick_ids_raw = await cursor.toArray();
let categoryListObj = categoryCollection.categoryList;
res.send(categoryListObj);
});
// Post comments.
// Protected Api
app.post("/comment", verifyToken, requestValidate, async (req, res) => {
const commentData = req.body;
const query = { blog_id: commentData.blog_id };
const commentList = await comments.findOne(query);
if (!commentList) {
const newCommentStructure = {
blog_id: commentData.blog_id,
commentInfo: [commentData.commentInfo],
};
const result = await comments.insertOne(newCommentStructure);
return res.send(result);
} else {
const options = { upsert: false };
let oldCommentStructure;
if (Array.isArray(commentList.commentInfo)) {
oldCommentStructure = [commentData.commentInfo, ...commentList.commentInfo];
} else {
oldCommentStructure = [commentData.commentInfo, commentList.commentInfo];
}
const updatedData = {
$set: {
commentInfo: oldCommentStructure,
},
};
const result_update = await comments.updateOne(query, updatedData, options);
res.send(result_update);
}
});
// Post blog to db
// Protected Api
app.post("/addBlog", verifyToken, requestValidate, async (req, res) => {
const blogData = req.body.blogData;
const result = await allBlogs.insertOne(blogData);
res.send(result);
});
// Update blog
// Protected Api
app.put("/updateBlog/:blog_id", verifyToken, requestValidate, async (req, res) => {
const blog_id = req.params.blog_id;
const blogData = req.body.blogData;
const query = { _id: new ObjectId(blog_id) };
const options = { upsert: false };
const updatedData = {
$set: {
bannerUrl: blogData.bannerUrl,
title: blogData.title,
category: blogData.category,
shortDescription: blogData.shortDescription,
longDescription: blogData.longDescription,
},
};
const result = await allBlogs.updateOne(query, updatedData, options);
res.send(result);
});
// Wishlist add.
// protected api.
app.patch("/addWishlist", verifyToken, requestValidate, async (req, res) => {
const blogId = req.body.blogId;
const userId = req.body.userId;
const query = { userId: userId };
const wishListData = await wishlist.findOne(query);
// as userId is not added in db, theres no data in it
if (!wishListData) {
let newWishListData = {
userId: userId,
wishLists: [blogId],
};
const insertResult = await wishlist.insertOne(newWishListData);
return res.send(insertResult);
}
const tempWishLists = wishListData.wishLists;
// Add blogId to wishlists
tempWishLists.push(blogId);
// written condition
const updatedWishlists = {
$set: {
wishLists: tempWishLists,
},
};
const options = { upsert: false };
// updating data
const result = await wishlist.updateOne(query, updatedWishlists, options);
return res.send(result);
});
// Wishlist remove.
// protected api.
app.patch("/removeWishlist", verifyToken, requestValidate, async (req, res) => {
const blogId = req.body.blogId;
const userId = req.body.userId;
const wishlistQuery = { userId: userId };
const wishListData = await wishlist.findOne(wishlistQuery);
const wishLists = wishListData.wishLists;
// Remove blog id from tempWishLists
let filteredWishlist = wishLists.filter((id) => id !== blogId);
// written condition
const updatedWishlists = {
$set: {
wishLists: filteredWishlist,
},
};
const options = { upsert: false };
// updating data
const result = await wishlist.updateOne(wishlistQuery, updatedWishlists, options);
return res.send(result);
});
} finally {
// await client.close();
}
}
// Started mainProcess() function
mainProcess().catch(console.dir);
app.get("/", (req, res) => {
res.send("Technest Server Running");
});
app.listen(port, () => {
console.log(`Running on port http://localhost:${port}
------------------------------------`);
});