-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
312 lines (260 loc) · 9.25 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
const express = require("express");
const session = require("express-session");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const multer = require("multer");
const fs = require("fs");
const path = require("path"); // Import path module for file paths
const app = express();
const crypto = require("crypto");
const generateSecretKey = () => {
return crypto.randomBytes(32).toString("hex");
};
app.use(
session({
secret: generateSecretKey(),
resave: true,
saveUninitialized: true,
})
);
app.set("view engine", "ejs");
app.use(express.static("public/data"));
app.use(express.static("public"));
app.use(bodyParser.json({ limit: "10mb" }));
app.use(bodyParser.urlencoded({ extended: false }));
// Create a schema for the images
const imageSchema = new mongoose.Schema({
data: String,
});
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// Serve mainpage.html when the root path is accessed
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "mainpage.html"));
});
// Serve mainpage.html when /mainpage.html path is accessed
app.get("/mainpage.html", (req, res) => {
res.sendFile(path.join(__dirname, "public", "mainpage.html"));
});
app.get("/login.html", (req, res) => {
const errorMessage = req.query.error; // Get the error message from the query parameters
res.sendFile("/login.html", { errorMessage });
});
// MongoDB connection and User model
mongoose.connect("mongodb://localhost:27017/SnapIT", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", () => console.log("Error in Connecting to Database"));
db.once("open", () => console.log("Connected to Database"));
const User = mongoose.model("User", {
username: String,
phone: String,
email: String,
password: String,
dob: String,
gender: String,
location: String,
image: {
data: String,
},
friends: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
});
app.get("/finalInterface", (req, res) => {
const userID = req.session.user ? req.session.user._id : null;
res.render("finalInterface", { userID });
});
app.get("/chat", (req, res) => {
const userID = req.session.user ? req.session.user._id : null;
res.render("chat", { userID });
});
app.post("/saveSnapshot", async (req, res) => {
try {
const { image } = req.body;
const userID = req.session.user ? req.session.user._id : null;
// Fetch the username from the user session
const username = req.session.user ? req.session.user.username : null;
// Decode base64 image data
const imageData = Buffer.from(
image.replace(/^data:image\/\w+;base64,/, ""),
"base64"
);
// Get the data folder path
const dataFolderPath = path.join(__dirname, "public/data");
console.log(dataFolderPath);
// Create the data folder if it doesn't exist
if (!fs.existsSync(dataFolderPath)) {
fs.mkdirSync(dataFolderPath);
}
// Save the image with the user-specified name
const filePath = path.join(dataFolderPath, `${username}.png`);
fs.writeFileSync(filePath, imageData);
console.log(`Snapshot saved for user ${username} at ${filePath}`);
res.status(200).send("Snapshot saved successfully.");
} catch (error) {
console.error("Error saving snapshot:", error);
res.status(500).send("Internal Server Error");
}
});
app.get(
"D:/YEAR 2/SEM 3/Web Technologies/SnapIT/finalcodeez/data/username",
(req, res) => {
// Add this route to serve images
const { username } = req.params;
// Get the data folder path
const dataFolderPath = path.join(__dirname, "data");
const filePath = path.join(dataFolderPath, `${username}.png`);
// Check if the file exists
if (fs.existsSync(filePath)) {
// Read the file and send it as a response
const image = fs.readFileSync(filePath);
res.writeHead(200, { "Content-Type": "image/png" });
res.end(image, "binary");
} else {
// Return a placeholder image or a 404 response
res.status(404).send("Image not found");
}
}
);
app.post("/login.html", (req, res) => {
const { username, password } = req.body;
// Find a user with the provided username and password
User.findOne({ username, password })
.then((user) => {
if (user) {
console.log("User logged in:", user);
// Set the user property in the session
req.session.user = user;
return res.redirect("/finalInterface.html"); // Redirect to mainpage.html
} else {
console.error("Invalid username or password");
// Redirect with error message as a query parameter
return res.redirect("/login.html?error=Invalid username or password");
}
})
.catch((err) => {
console.error(err);
return res.status(500).send("Error occurred while validating user data.");
});
});
app.get("/getFriends", async (req, res) => {
const userID = req.session.user ? req.session.user._id : null;
try {
// Fetch the user data from the database, including the populated friends field
const user = await User.findById(userID).populate("friends");
// Extract the friend data from the user object
const friends = user.friends.map((friend) => ({
username: friend.username,
_id: friend._id,
}));
// Return the list of friends
console.log("Friends fetched hehe:", friends);
res.json({ friends });
} catch (error) {
console.error("Error fetching friends:", error);
res.status(500).send("Internal Server Error");
}
});
// Handle the /addFriends endpoint
app.post("/addFriends", (req, res) => {
const { friendList } = req.body;
const userID = req.session.user ? req.session.user._id : null;
// Update the friends array for the current user (replace 'currentUserId' with the actual user ID)
User.updateOne(
{ _id: userID },
{ $addToSet: { friends: { $each: friendList } } }
)
.then(() => {
console.log("Friends added successfully", friendList);
res.status(200).send("Friends added successfully");
})
.catch((error) => {
console.error("Error adding friends:", error);
res.status(500).send("Internal Server Error");
});
});
app.post("/signup.html", async (req, res) => {
const { username, phone, email, password, dob, gender, location } = req.body;
try {
// Check if the username already exists
const existingUser = await User.findOne({ username });
if (existingUser) {
console.log("username already taken");
return res.redirect("/signup.html");
// Username is already taken, send a response to the client
}
// Create a new user
const user = new User({
username,
phone,
email,
password,
dob,
gender,
location,
});
// Save the user data
const savedUser = await user.save();
console.log("User data saved:", savedUser);
return res.redirect("/login.html"); // Redirect to login page
} catch (error) {
console.log("username already taken");
console.error("Error occurred while saving user data:", error);
return res.redirect("/signup.html");
}
});
app.get("/viewprofile", async (req, res) => {
const userID = req.session.user ? req.session.user._id : null;
if (!userID) {
// Redirect to login if the user is not authenticated
return res.redirect("/login.html");
}
try {
// Fetch the user data from the database
const user = await User.findById(userID);
if (!user) {
// Redirect to login if the user is not found
return res.redirect("/login.html");
}
// Render the viewprofile page with the user data
res.render("viewprofile", { user });
} catch (error) {
console.error("Error fetching user data:", error);
res.status(500).send("Internal Server Error");
}
});
app.get("/searchresults", async (req, res) => {
try {
const { name } = req.query;
// Perform a case-insensitive search for users with the provided name
const users = await User.find({
username: { $regex: new RegExp(name, "i") },
});
// Render the search results page with the list of users
res.render("searchresults", { users, searchQuery: name });
} catch (error) {
console.error("Error searching for users:", error);
res.status(500).send("Internal Server Error");
}
});
app.get("/getFriends", async (req, res) => {
const userID = req.session.user ? req.session.user._id : null;
try {
// Fetch the user data from the database, including the populated friends field
const user = await User.findById(userID).populate("friends");
// Extract the friend data from the user object
const friends = user.friends.map((friend) => ({
username: friend.username,
}));
// Return the list of friends
res.json({ friends });
} catch (error) {
console.error("Error fetching friends:", error);
res.status(500).send("Internal Server Error");
}
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on PORT ${port}`);
});