-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
530 lines (493 loc) · 17.1 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
let origin;
let secrets;
process.env.NODE_ENV === "production"
? (origin = "http://sesamebook-social-network.herokuapp.com:*")
: (origin = "localhost:8080");
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server, { origins: origin });
// origins: "localhost:8080"
const compression = require("compression"); //to compress the bundle server before response to client
const bodyParser = require("body-parser");
const queryFunction = require("./queryFunction");
const chalk = require("chalk");
const { hashPass, checkPass, passRestrictions } = require("./hashFunctions");
const cookieSession = require("cookie-session");
const { uploadS3 } = require("./s3");
const multer = require("multer");
const uidSafe = require("uid-safe");
const { s3Url } = require("./config");
const path = require("path");
process.env.NODE_ENV === "production"
? (secrets = process.env)
: (secrets = require("./secrets.json"));
app.use(bodyParser.json());
const cookieSessionMiddleware = cookieSession({
secret: secrets.cookieSecret,
maxAge: 1000 * 60 * 60 * 24 * 90
});
app.use(cookieSessionMiddleware);
io.use(function(socket, next) {
cookieSessionMiddleware(socket.request, socket.request.res, next);
});
var diskStorage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, __dirname + "/uploads");
},
filename: function(req, file, callback) {
uidSafe(24).then(function(uid) {
callback(null, uid + path.extname(file.originalname));
});
}
});
var uploader = multer({
storage: diskStorage,
limits: {
fileSize: 2097152
}
});
//PURPOSE: VULNERABILITIES
const csurf = require("csurf");
app.use(csurf()); // use after cookie/body middleware, CSRF attack prevention
app.use(function(req, res, next) {
res.cookie("mytoken", req.csrfToken()); //responds with a cookie "mytoken" for every request done to server
next();
});
app.use(function(req, res, next) {
res.setHeader("x-frame-options", "DENY");
next();
});
app.disable("x-powered-by");
//END VULNERABILITIES
app.use(compression());
app.use(express.static("./public"));
if (process.env.NODE_ENV != "production") {
app.use(
"/bundle.js",
require("http-proxy-middleware")({
target: "http://localhost:8081/"
})
);
} else {
app.use("/bundle.js", (req, res) => res.sendFile(`${__dirname}/bundle.js`));
}
//////////////////////////////ROUTE RESTRICTIONS///////////////////////////
//////////////////////////////////////////////////////////////////////////
function checkIfLoggedIn(req, res, next) {
if (!req.session.loggedIn && req.url != "/welcome") {
res.redirect("/welcome");
} else if (req.session.loggedIn && req.url == "/welcome") {
res.redirect("/");
} else {
next();
}
}
//////////////////////////////ROUTE RESTRICTIONS///////////////////////////
//////////////////////////////////////////////////////////////////////////
app.post("/submit-registration", (req, res) => {
if (!req.body.password) {
res.json({ error: true });
} else {
if (passRestrictions(req.body.password) == false) {
return res.json({ weakPassword: true });
}
hashPass(req.body.password)
.then(hashedPassword => {
return queryFunction.createUser(
req.body.firstname,
req.body.lastname,
req.body.email,
hashedPassword
);
})
.then(useridResponse => {
req.session.loggedIn = useridResponse.rows[0].id; //sets cookie based on the users ID
res.json({
loggedIn: true
});
})
.catch(e => {
console.log(chalk.red("CREATEUSER/REGISTER ERROR: "), e);
res.json({
error: true
});
});
}
});
app.post("/login-check", (req, res) => {
if (!req.body.email || !req.body.password) {
res.json({ blankFieldsError: true });
} else {
queryFunction
.fetchPassword(req.body.email)
.then(passwordResponse => {
return checkPass(
req.body.password,
passwordResponse.rows[0].password
).then(passwordMatch => {
if (passwordMatch) {
queryFunction
.fetchId(req.body.email)
.then(fetchedId => {
req.session.loggedIn = fetchedId.rows[0].id; //set cookie based on fetched ID
res.json({
loggedIn: true
});
});
} else {
console.log("MEEP MERP!", req.session);
res.json({
error: true
});
}
});
})
.catch(e => {
console.log(chalk.red("FETCH PASSWORD ERROR: "), e);
res.json({
errorType: "general"
});
});
}
});
app.get("/sign-out", (req, res) => {
req.session = null;
res.redirect("/welcome");
});
app.get("/user-data", (req, res) => {
let id = req.session.loggedIn;
queryFunction
.fetchUserData(id)
.then(userData => {
const {
id,
firstname,
lastname,
avatar,
user_bio
} = userData.rows[0];
res.json({ id, firstname, lastname, avatar, user_bio });
})
.catch(e => {
console.log("GET USERDATA QUERRY ERROR: ", e);
res.status(500).json({ error: true });
});
});
app.post("/avatar-uploads", uploader.single("file"), uploadS3, (req, res) => {
const avatarUrl = s3Url + req.file.filename;
if (req.file) {
queryFunction
.updateAvatar(req.session.loggedIn, s3Url + req.file.filename)
.then(() => {
res.json({ avatar: avatarUrl });
});
} else {
res.status(500).json({ errorUploadingImage: true });
}
});
app.post("/post-bio", (req, res) => {
queryFunction
.postBio(req.session.loggedIn, req.body.user_bio)
.then(() => {
res.json({ user_bio: req.body.user_bio });
})
.catch(e => {
console.log("ERROR POSTING USERBIO: ", e);
res.status(500).json({ errorPostingUserBio: true });
});
});
app.get("/get-other-users-data/:otherUserId", async (req, res) => {
try {
const otherUsersData = await queryFunction.fetchOtherUsersData(
req.params.otherUserId
);
const {
id,
firstname,
lastname,
avatar,
user_bio
} = otherUsersData.rows[0];
res.json({ id, firstname, lastname, avatar, user_bio });
} catch (e) {
console.log("ERROR FETCHING OTHER USERS DATA: ", e);
res.status(500).json({ errorGettingOtherUserData: true });
}
});
app.post("/friend-status", async (req, res) => {
try {
const friendStatus = await queryFunction.checkFriendStatus(
req.session.loggedIn,
req.body.otherUserId
);
if (friendStatus.rows[0]) {
if (req.session.loggedIn == friendStatus.rows[0].sender_id) {
res.json({
friendReqSent: true,
friendStatus: friendStatus.rows[0].status
});
} else if (
req.session.loggedIn == friendStatus.rows[0].receiver_id
) {
res.json({
friendReqReceived: true,
friendStatus: friendStatus.rows[0].status
});
}
} else {
res.json({
friendReqSent: false,
friendReqReceived: false,
friendStatus: null
});
}
} catch (e) {
console.log("ERROR CHECKING FRIENDSHIP STATUS: ", e);
res.status(500).json({ errorCheckingFriendStatus: true });
}
});
app.post("/add-friend", async (req, res) => {
try {
const addFriend = await queryFunction.addFriend(
req.session.loggedIn,
req.body.otherUserId,
1
);
res.json({ friendReqSent: true, friendStatus: 1 });
} catch (e) {
console.log("ERROR ADDING FRIEND QUERY: ", e);
res.status(500).json({ errorAddingFriend: true });
}
});
app.post("/accept-friend-req", async (req, res) => {
try {
const acceptFriendReq = await queryFunction.acceptFriendReq(
req.session.loggedIn,
req.body.otherUserId
);
res.json({ friendReqAccepted: true, friendStatus: 2 });
} catch (e) {
console.log("ERROR ACCEPTING FRIEND REQ QUERY: ", e);
res.status(500).json({ errorAcceptingFriend: true });
}
});
app.post("/cancel-friend-req", async (req, res) => {
try {
const cancelFriendReq = await queryFunction.deleteFriendRow(
req.session.loggedIn,
req.body.otherUserId
);
res.json({
friendReqReceived: false,
friendReqSent: false,
friendStatus: null
});
} catch (e) {
console.log("ERROR CANCELLING FRIEND REQ QUERY: ", e);
res.status(500).json({ errorCancellingFriend: true });
}
});
app.post("/unfriend", async (req, res) => {
try {
const unfriend = await queryFunction.deleteFriendRow(
req.session.loggedIn,
req.body.otherUserId
);
res.json({
friendReqReceived: false,
friendReqSent: false,
friendStatus: null
});
} catch (e) {
console.log("ERROR CANCELLING FRIEND REQ QUERY: ", e);
res.status(500).json({ errorUnfriending: true });
}
});
app.get("/fetchall-friends-wannabes", async (req, res) => {
try {
const allFriendsWannabes = await queryFunction.fetchFriendsWannabes(
req.session.loggedIn
);
res.json({ allFriendsWannabes: allFriendsWannabes.rows });
} catch (e) {
console.log("ERROR FETCHING ALL FRIENDS WANNABEES: ", e);
res.status(500).json({ errorFetchingFriendsWannabees: true });
}
});
app.post("/search-users", async (req, res) => {
try {
const searchedUsers = await queryFunction.fetchSearchedUsers(
req.body.search
);
res.json({ searchedUsersArray: searchedUsers.rows });
} catch (e) {
console.log("ERROR FETCHING SEARCHED USERS FROM DB: ", e);
res.status(500).json({ errorSearchingUsers: true });
}
});
app.post("/post-wall", async (req, res) => {
try {
console.log("WALL POST DATA ->", req.body);
const senderData = await queryFunction.fetchUserData(
req.session.loggedIn
);
const { firstname, lastname, avatar } = senderData.rows[0];
const postWall = await queryFunction.postWall(
req.session.loggedIn,
req.body.otherUserId || req.session.loggedIn,
req.body.text,
firstname,
lastname,
avatar
);
// do wallposts fetch to update state immediately on hitting enter.
const wallPosts = await queryFunction.fetchWallPosts(
req.body.otherUserId || req.session.loggedIn
);
res.json({
wallPostsReceived: wallPosts.rows,
postsOnWall: true
});
} catch (e) {
console.log("ERROR POSTINGon WALL TO DB: ", e);
res.status(500).json({ errorPostingWall: true });
}
});
app.get("/get-wallposts/:otherUserId", async (req, res) => {
try {
if (!isNaN(req.params.otherUserId)) {
const wallPosts = await queryFunction.fetchWallPosts(
req.params.otherUserId
);
const userData = await queryFunction.fetchUserData(
req.params.otherUserId
);
const { firstname } = userData.rows[0];
res.json({
wallPostsReceived: wallPosts.rows,
postsOnWall: true,
firstname
});
} else if (isNaN(req.params.otherUserId)) {
const wallPosts = await queryFunction.fetchWallPosts(
req.session.loggedIn
);
const userData = await queryFunction.fetchUserData(
req.session.loggedIn
);
const { firstname } = userData.rows[0];
res.json({
wallPostsReceived: wallPosts.rows,
postsOnWall: true,
firstname
});
}
} catch (e) {
console.log("ERROR FETCHING WALLPOSTS FROM DB: ", e);
res.status(500).json({ errorGetWallPosts: true });
}
});
//order here MATTERS
app.get("*", checkIfLoggedIn, (req, res) => {
res.sendFile(__dirname + "/index.html");
});
//server listening- (only http requests)
server.listen(process.env.PORT || 8080, function() {
console.log("I'm listening: ");
});
////////////////////////////////////////////////////////////////////////////
//////////////////////////SOCKETS COMMUNICATION BELOW///////////////////////
////////////////////////////////////////////////////////////////////////////
//websockets listening- (order doesnt matter, listens in parallel)
let onlineUsersObj = {};
io.on("connection", function(socket) {
if (!socket.request.session || !socket.request.session.loggedIn) {
return socket.disconnect(true);
}
const loggedIn = socket.request.session.loggedIn;
console.log(
`socket with the id ${
socket.id
} and USERID ${loggedIn} is now connected`
);
////////////////////////////////JOIN AND LEAVE/////////////////////////
//create array of loggedin users
onlineUsersObj[socket.id] = loggedIn;
let arrayUserIds = Object.values(onlineUsersObj);
queryFunction.getOnlineUsers(arrayUserIds).then(onlineUsers => {
const onlineUsersMapped = onlineUsers.rows.map(user => {
if (user.id == loggedIn) {
return { ...user, mainUser: true };
} else {
return user;
}
});
socket.emit("onlineUsersResponse", {
onlineUsers: onlineUsersMapped
});
});
let allSocketIds = arrayUserIds.filter(id => id == loggedIn);
if (allSocketIds.length == 1) {
queryFunction.fetchUserData(loggedIn).then(userJoined => {
const { id, firstname, lastname, avatar } = userJoined.rows[0];
socket.broadcast.emit("userJoined", {
//broadcast sends to all except main user
userJoined: { id, firstname, lastname, avatar }
});
});
}
///////////////////////////////CHAT COMMENT/////////////////////////////
socket.on("getChatMessages", () => {
queryFunction
.fetchChatDataMounted()
.then(chatData => {
let chatDataSorted = chatData.rows.sort(function(a, b) {
return a.id - b.id;
});
const chatSortedMapped = chatDataSorted.map(message => {
if (message.sender_id == loggedIn) {
return { ...message, mainUser: true };
} else {
return message;
}
});
socket.emit("allChatResponse", chatSortedMapped);
})
.catch(e => console.log("error getting chat data: ", e));
});
socket.on("sendChatMessage", message => {
queryFunction
.postChatMessage(loggedIn, message)
.then(lastIdReturned => {
const lastId = lastIdReturned.rows[0].id;
queryFunction.fetchLastMessage(lastId).then(lastMessage => {
socket.emit("messageResp", {
...lastMessage.rows[0],
mainUser: true
});
socket.broadcast.emit("messageResp", lastMessage.rows[0]);
});
})
.catch(e => console.log("error posting chat message to server", e));
});
///////////////////////////////DISCONNECT///////////////////////////////
socket.on("disconnect", function() {
console.log(
`socket with the id ${
socket.id
} and user id ${loggedIn} is now disconnected`
);
delete onlineUsersObj[socket.id];
arrayUserIds = Object.values(onlineUsersObj);
//create if to find out if really left before querying
if (!arrayUserIds.includes(loggedIn)) {
queryFunction.fetchUserData(loggedIn).then(userLeft => {
const { id, firstname, lastname, avatar } = userLeft.rows[0];
io.sockets.emit("userLeft", {
userLeft: { id, firstname, lastname, avatar }
});
});
}
});
});