-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
712 lines (613 loc) · 22.2 KB
/
server.js
File metadata and controls
712 lines (613 loc) · 22.2 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
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const { MongoClient } = require("mongodb");
const path = require("path");
const crypto = require("crypto");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const bcrypt = require("bcrypt");
const multer = require("multer");
const fs = require("fs");
const uploadDir = "./uploads";
const { ObjectId } = require("mongodb");
const dotenv = require("dotenv");
const app = express();
const port = 3000;
const secretKey = crypto.randomBytes(20).toString("hex");
dotenv.config();
app.use(cors());
app.use(bodyParser.json());
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.use("/proj", express.static(path.join(__dirname, "proj")));
// MongoDB connection configuration
const mongoURI = process.env.mongoURI;
const dbName = process.env.dbName;
const client = new MongoClient(mongoURI);
async function connectToMongoDB() {
try {
await client.connect();
console.log("Connected to MongoDB.");
} catch (err) {
console.error("Error connecting to MongoDB:", err);
}
}
app.use(
session({
secret: secretKey,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: mongoURI, dbName: "querit" }),
cookie: { maxAge: 60 * 60 * 24 * 1000 }, // 1 day
})
);
// Connect to MongoDB
connectToMongoDB();
// Middleware to check if user is authenticated
function isAuthenticated(req, res, next) {
// Exclude login and register routes from authentication check
if (req.path === "/login.html" || (req.session && req.session.isLoggedIn)) {
// If the user is logged in and trying to access the login page, redirect to home
if (req.session.isLoggedIn && req.path === "/login.html") {
return res.redirect("/home.html");
}
return next();
}
// If not authenticated and not accessing login or register page, redirect to login
res.redirect("/login.html");
}
// Serve login page only if user is not authenticated
app.get("/login.html", (req, res, next) => {
if (req.session.isLoggedIn) {
return res.redirect("/home.html"); // Redirect logged-in users to home page
}
// Set headers to prevent caching
res.set({
"Cache-Control": "no-store, no-cache, must-revalidate, private",
Pragma: "no-cache",
Expires: "-1",
});
next(); // Serve login page to non-authenticated users
});
// Protect pages and serve static files after applying authentication middleware
app.get(
[
"/home.html",
"/thread.html",
"/posts.html",
"/notifications.html",
"/profile.html",
"/edit_profile.html",
],
isAuthenticated,
(req, res) => {
res.sendFile(path.join(__dirname, "proj", req.path));
}
);
// Serve static files after applying authentication middleware
app.use(express.static("proj"));
app.use(express.static("uploads"));
// Route handler for the root path
app.get("/", (req, res) => {
res.send("Server is running.");
});
app.get("/checkSession", (req, res) => {
if (req.session.isLoggedIn) {
res.json({ isLoggedIn: true });
} else {
res.json({ isLoggedIn: false });
}
});
// Legacy code to enter user data into the database
// async function insertUserToDatabase(user) {
// const db = client.db(dbName);
// const collection = db.collection("users");
// await collection.insertOne(user);
// }
// Route handler for user registration
app.post("/register", async (req, res) => {
const { name, email, password } = req.body;
console.log(`Received registration request for email: ${email}`); // Debugging log
// Simple validation for required fields
if (!name || !email || !password) {
console.log("Missing required fields."); // Debugging log
return res.status(400).json({
message: "All fields (name, email, password) are required.",
});
}
try {
// Access the MongoDB collection from the database client
const db = client.db(dbName);
const collection = db.collection("users");
// Check if the user already exists
const existingUser = await collection.findOne({ email });
if (existingUser) {
console.log("User already exists."); // Debugging log
return res.status(400).json({ message: "User already exists." });
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10); // 10 is the salt rounds
// Insert user into the database with hashed password
await collection.insertOne({
name,
email,
password: hashedPassword,
});
console.log("User registration successful."); // Debugging log
res.status(200).json({ message: "User registration successful." });
} catch (error) {
console.error("Error during registration:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for user login
app.post("/login", async (req, res) => {
const { email, password, captchaInput, captchaResult } = req.body;
console.log(`Received login request for email: ${email}`); // Debugging log
// Simple email validation
if (!email || !password) {
console.log("Missing email or password."); // Debugging log
return res
.status(400)
.json({ message: "Email and password are required." });
}
// Verify CAPTCHA response
if (captchaInput !== captchaResult) {
console.log("CAPTCHA verification failed."); // Debugging log
return res.status(401).json({ message: "CAPTCHA verification failed." });
}
try {
// Fetch user from the database
const db = client.db(dbName);
const collection = db.collection("users");
const user = await collection.findOne({ email });
if (user) {
// Compare hashed password
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (isPasswordCorrect) {
console.log("Login successful."); // Debugging log
// Inside the /login route handler, after successful login, set the session flag to indicate that the user is logged in and store the user's email in the session.
req.session.isLoggedIn = true;
req.session.email = email; // Store email in session
// Set session cookie with user's email
res.cookie("userEmail", email, { maxAge: 60 * 60 * 24 * 1000 }); // 1 day
res.status(200).json({
message: "Login successful.",
redirect: "/home.html",
});
} else {
console.log("Login failed. Incorrect email or password."); // Debugging log
res
.status(401)
.json({ message: "Login failed. Incorrect email or password." });
}
} else {
console.log("User not found."); // Debugging log
res.status(404).json({ message: "User not found." });
}
} catch (error) {
console.error("Error during login:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for updating user profile
app.post("/updateProfile", async (req, res) => {
// Extract user profile data from the request body
const { name, dob, email, password, phone } = req.body;
// Extract the email of the logged-in user from the session
const userEmail = req.session.email;
// Retrieve the user document from the database using the email
const db = client.db(dbName);
const collection = db.collection("users");
const user = await collection.findOne({ email: userEmail });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Extract the ObjectId of the user document
const userId = user._id;
// Construct the update query
const updateQuery = {};
// Allow all fields to be updated
if (name) updateQuery.name = name;
if (dob) updateQuery.dob = dob;
if (password) updateQuery.password = password;
if (phone) updateQuery.phone = phone;
// If the email is being updated, handle it separately to avoid errors
if (email && email !== userEmail) {
// Check if the new email already exists in the database
const existingUser = await collection.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: "Email already exists" });
}
// Update the email field in the document
updateQuery.email = email;
}
try {
// Update the user document in the database
await collection.updateOne({ _id: userId }, { $set: updateQuery });
// Send a JSON response indicating a successful update
res.status(200).json({ message: "Profile updated successfully" });
} catch (error) {
console.error("Error updating profile:", error);
// Send a JSON response with error details
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for user logout
app.post("/logout", function (req, res, next) {
console.log("Received logout request..."); // Debugging log
req.session.destroy(function (err) {
if (err) {
console.error("Error destroying session:", err); // Debugging log
return next(err);
}
console.log("Session destroyed successfully."); // Debugging log
res.clearCookie("connect.sid"); // Clear the session cookie
// Send the response immediately after session destruction
res
.status(200)
.json({ message: "Logged out successfully", redirectToLogin: true });
});
});
// Route handler for fetching user name in the profile page
app.get("/getUserName", async (req, res) => {
// Extract the email of the logged-in user from the session
const userEmail = req.session.email;
// Retrieve the user document from the database using the email
const db = client.db(dbName);
const collection = db.collection("users");
const user = await collection.findOne({ email: userEmail });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Send the user's name in the response
res.status(200).json({ name: user.name, email: user.email });
});
// Route handler for fetching user name in the profile page
app.get("/getUserBio", async (req, res) => {
// Extract the email of the logged-in user from the session
const userEmail = req.session.email;
// Retrieve the user document from the database using the email
const db = client.db(dbName);
const collection = db.collection("users");
const user = await collection.findOne({ email: userEmail });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Send the user's name in the response
res.status(200).json({ bio: user.bio });
});
// Route handler for saving a post to the database
app.post("/savePost", async (req, res) => {
try {
// Extract post data from the request body
const {
postTitle,
postContent,
topic,
timestamp,
userEmail,
userName,
filePath,
} = req.body;
// Ensure all required fields are present
if (
!postTitle ||
!postContent ||
!timestamp ||
!userEmail ||
!userName ||
!topic
) {
return res.status(400).json({ message: "All fields are required." });
}
// Insert the post data into the database
const db = client.db(dbName);
const collection = db.collection("posts");
await collection.insertOne({
title: postTitle,
content: postContent,
topic: topic,
timestamp: timestamp,
userEmail: userEmail,
userName: userName,
filePath: filePath, // Store file path in the database
commentCount: 0,
viewCount: 0,
comments: [],
});
console.log("Post saved successfully."); // Debugging log
res.status(200).json({ message: "Post saved successfully." });
} catch (error) {
console.error("Error saving post:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for fetching posts created by the logged-in user
app.get("/getUserPosts", async (req, res) => {
try {
// Extract the email of the logged-in user from the session
const userEmail = req.session.email;
// Retrieve posts from the database based on the user's email
const db = client.db(dbName);
const collection = db.collection("posts");
const userPosts = await collection
.find({ userEmail: userEmail })
.sort({ timestamp: -1 })
.toArray();
// Send the user's posts in the response
res.status(200).json({ userPosts });
} catch (error) {
console.error("Error fetching user posts:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for resetting user password
app.post("/resetPassword", async (req, res) => {
const { email, newPassword } = req.body;
// Validate request body
if (!email || !newPassword) {
return res.status(400).json({
success: false,
message: "Email and new password are required.",
});
}
try {
const db = client.db(dbName);
const collection = db.collection("users");
// Hash the new password
const hashedPassword = await bcrypt.hash(newPassword, 10);
// Update the user's password
const result = await collection.updateOne(
{ email: email },
{ $set: { password: hashedPassword } }
);
// Check if the update was successful
if (result.modifiedCount === 0) {
return res.status(404).json({
success: false,
message: "User not found or password not updated.",
});
}
console.log("Password reset successful for:", email);
res.status(200).json({ success: true });
} catch (error) {
console.error("Error resetting password:", error);
res.status(500).json({ success: false, message: "Server error" });
}
});
// Route handler for fetching posts
app.post("/getPosts", async (req, res) => {
try {
// Fetch posts from the database
const db = client.db(dbName);
const collection = db.collection("posts");
// Find all posts and sort them by timestamp in descending order
const allPosts = await collection.find().sort({ timestamp: -1 }).toArray();
// Send the sorted posts to the client
res.status(200).json({ allPosts });
} catch (error) {
console.error("Error fetching posts:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for fetching user bio
app.get("/getUserBio", async (req, res) => {
// Extract the email of the logged-in user from the session
const userEmail = req.session.email;
// Retrieve the user document from the database using the email
const db = client.db(dbName);
const collection = db.collection("users");
const user = await collection.findOne({ email: userEmail });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Send the user's bio in the response
res.status(200).json({ bio: user.bio });
});
// Set up Multer storage
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads"); // Destination folder for uploaded files
},
filename: function (req, file, cb) {
cb(null, file.originalname); // Use original file name
},
});
// Middleware function to log image requests
app.use((req, res, next) => {
if (
req.url.endsWith(".jpg") ||
req.url.endsWith(".png") ||
req.url.endsWith(".mp4")
) {
// Adjust file extensions as needed
console.log("Image fetched by client:", req.url);
}
next();
});
// Create Multer instance with defined storage
const upload = multer({ storage: storage });
// Route handler for file upload
app.post("/uploadFile", upload.single("file"), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: "No file uploaded" });
}
// File uploaded successfully, return file path
const filePath = req.file.path;
res.status(200).json({ filePath: filePath });
} catch (error) {
console.error("Error uploading file:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler to fetch posts by ID
app.post("/getPostByID", async (req, res) => {
try {
const { postID } = req.body;
const database = client.db(dbName);
const postsCollection = database.collection("posts");
const post = await postsCollection.findOne({ _id: new ObjectId(postID) });
if (post) {
res.json([post]);
} else {
res.status(404).send("Post not found");
}
} catch (error) {
console.error("Error fetching post by ID:", error);
res.status(500).send("Internal server error");
}
});
// Increment view count
app.post("/incrementViewCount", async (req, res) => {
const postID = req.body.postID;
try {
const db = client.db(dbName);
const collection = db.collection("posts");
const result = await collection.updateOne(
{ _id: new ObjectId(postID) },
{ $inc: { viewCount: 1 } }
);
if (result.modifiedCount === 1) {
res.status(200).json({ message: "View count incremented successfully" });
} else {
res.status(404).json({ message: "Post not found" });
}
} catch (error) {
console.error("Error incrementing view count:", error);
res.status(500).json({ message: "Error incrementing view count" });
}
});
// Route handler for adding a comment to a post
app.post("/addComment", async (req, res) => {
const { postID, comment } = req.body;
try {
const db = client.db(dbName);
const collection = db.collection("posts");
const result = await collection.updateOne(
{ _id: new ObjectId(postID) },
{
$push: {
comments: {
text: comment.text,
email: comment.userEmail,
name: comment.userName,
topic: comment.topic,
},
},
$inc: { commentCount: 1 },
}
);
if (result.modifiedCount === 1) {
res.status(200).json({ message: "Comment added successfully" });
} else {
res.status(404).json({ message: "Post not found" });
}
} catch (error) {
console.error("Error adding comment:", error);
res.status(500).json({ message: "Error adding comment" });
}
});
// Route handler for fetching posts sorted by comments count
app.post("/sortComment", async (req, res) => {
try {
// Fetch posts from the database
const db = client.db(dbName);
const collection = db.collection("posts");
// Find all posts and sort them by comments in descending order
const allPosts = await collection
.find()
.sort({ commentCount: -1 })
.toArray();
// Send the sorted posts to the client
res.status(200).json({ allPosts });
} catch (error) {
console.error("Error fetching posts:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Route handler for fetching posts sorted by view count
app.post("/sortView", async (req, res) => {
try {
// Fetch posts from the database
const db = client.db(dbName);
const collection = db.collection("posts");
// Find all posts and sort them by views in descending order
const allPosts = await collection.find().sort({ viewCount: -1 }).toArray();
// Send the sorted posts to the client
res.status(200).json({ allPosts });
} catch (error) {
console.error("Error fetching posts:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Server-side code to fetch user comments
app.post("/userComments", async (req, res) => {
const userEmail = req.body.userEmail; // Extract the user email from the request body
try {
const db = client.db(dbName);
const collection = db.collection("posts");
const userComments = await collection
.aggregate([
{ $unwind: "$comments" }, // Unwind the comments array
{ $match: { "comments.email": userEmail } }, // Match comments by user email
{ $project: { _id: 0, comments: 1 } }, // Project only the comments
])
.toArray();
res.status(200).json(userComments);
} catch (error) {
console.error("Error fetching user comments:", error);
res.status(500).json({ message: "Error fetching user comments" });
}
});
// Route to handle search requests
app.get("/search", async (req, res) => {
const keywords = req.query.keywords; // Keywords entered by the user
try {
// Search for posts containing the keywords in title or content
const db = client.db(dbName);
const collection = db.collection("posts");
const posts = await collection
.find({
$or: [
{ title: { $regex: keywords, $options: "i" } }, // Case-insensitive search in title
{ content: { $regex: keywords, $options: "i" } }, // Case-insensitive search in content
],
})
.toArray();
res.json(posts);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });
}
});
// Route handler for fetching posts by topic
app.get("/getPostByTopic", async (req, res) => {
try {
// Extract the topic from the query parameters
const topic = req.query.topic;
// Validate if the topic parameter is provided
if (!topic) {
return res.status(400).json({ message: "Topic parameter is missing" });
}
// Retrieve posts from the database based on the specified topic
const db = client.db(dbName);
const collection = db.collection("posts");
const posts = await collection.find({ topic: topic }).toArray();
// Send the retrieved posts back as a JSON response
res.json(posts);
} catch (error) {
console.error("Error fetching posts by topic:", error);
res.status(500).json({ message: "Server error", error: error.message });
}
});
// Serve static files
const projDir = path.join(__dirname, "./proj");
app.use(express.static(projDir));
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});