-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
661 lines (579 loc) · 22.7 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
const path = require("path");
const http = require("http"); // create http server
const mysql = require("mysql");
const express = require("express");
const socketio = require("socket.io"); // create socket server
const bcrypt = require("bcrypt");
const formatMessage = require("./helpers/formatDate");
const app = express(); // create express app
const server = http.createServer(app); // create server
const socketioClient = require("socket.io-client");
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true,
timeout: 5000,
cert: "cert.pem",
key: "key.pem",
// allow headers
allowedHeaders: ["my-custom-header"],
// exposed headers
exposedHeaders: ["my-custom-header"],
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
withCredentials: true,
// Set to true if you want to pass the message to the next middleware
// if the origin is not allowed
preflightContinue: false,
},
});
const csp = require("content-security-policy");
const session = require("express-session");
const sessionStore = new session.MemoryStore();
const CryptoJS = require("crypto-js"); // encryption
const readline = require("readline"); // read input from console
let clientConnection = "";
// secret key for encryption
const secretKey = "secret key 123456789";
// xss middleware to prevent XSS attacks by sanitizing user input cross site scripting
const xss = require("xss-clean");
// Sanitize user input to prevent XSS attacks
app.use(xss());
// Enable rate limiting to prevent brute force attacks
const rateLimit = require("express-rate-limit"); // prevent brute force attacks
// Limit requests from the same IP
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 200, // limit each IP to 200 requests per windowMs
});
// apply to all requests
app.use(limiter);
// content security policy header to prevent cross site request forgery attacks
const cspPolicy = csp.getCSP({
directives: {
"default-src": csp.SRC_SELF,
"script-src": [csp.SRC_SELF, csp.SRC_UNSAFE_INLINE],
"style-src": [csp.SRC_SELF, csp.SRC_UNSAFE_INLINE],
"img-src": [csp.SRC_SELF, "data:"],
"font-src": [csp.SRC_SELF, "data:"],
"connect-src": [csp.SRC_SELF, "ws://localhost:3000"],
"frame-src": [csp.SRC_SELF],
"object-src": [csp.SRC_SELF],
"media-src": [csp.SRC_SELF],
"worker-src": [csp.SRC_SELF],
"child-src": [csp.SRC_SELF],
"form-action": [csp.SRC_SELF],
"frame-ancestors": [csp.SRC_NONE],
"base-uri": [csp.SRC_NONE],
"plugin-types": [csp.SRC_NONE],
sandbox: [csp.SANDBOX_ALLOW_FORMS, csp.SANDBOX_ALLOW_SCRIPTS],
"report-uri": "/report-violation",
"require-sri-for": csp.REQUIRE_SRI_FOR_SCRIPT_STYLE,
"block-all-mixed-content": true,
"upgrade-insecure-requests": true,
},
});
// This will apply this policy to all requests if no local policy is set
app.use(cspPolicy);
const {
getActiveUser,
exitRoom,
newUser,
getIndividualRoomUsers,
} = require("./helpers/userHelper");
const { get } = require("jquery");
// ********************************************************************************* //
// API Middleware
// ********************************************************************************* //
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Set public directory
app.use(express.static(path.join(__dirname, "public")));
// ********************************************************************************* //
// SESSION MIDDLEWARE
// ********************************************************************************* //
app.use(
session({
secret: "my-secret", // used to sign the session ID cookie
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
cookie: {
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: true, // only send session ID cookie if the request originated from the same site
secure: false, // only send session ID cookie over HTTPS
},
})
);
// sessionstore
app.use((req, res, next) => {
req.sessionStore = sessionStore;
next();
});
// ********************************************************************************* //
// connection to mysql database
// ********************************************************************************* //
// define database connection
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "live_chat",
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log("MySQL Connected...");
});
// ********************************************************************************* //
// Auth Routes
// ********************************************************************************* //
// register user
app.get("/registerForm", (req, res) => {
// get username, email and password from form
let user_name = req.query.user_name;
let user_email = req.query.user_email;
let user_password = req.query.user_password;
// check if user already exists
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `SELECT * FROM users_details WHERE user_email = ? or user_name = ?`;
let params = [user_email, user_name];
db.query(sql, params, (err, result) => {
if (err) throw err;
if (result.length > 0) {
res.redirect("/register?msg=user exists");
} else {
// check if email is valid
if (!user_email.includes("@") || !user_email.includes(".")) {
res.redirect("/register?msg=email not valid");
} else {
// check if password is strong
if (user_password.length < 8) {
res.redirect("/register?msg=password too short");
} else if (user_password.search(/[a-z]/i) < 0) {
res.redirect("/register?msg=password must contain letters");
} else if (user_password.search(/[0-9]/) < 0) {
res.redirect("/register?msg=password must contain numbers");
} else if (
user_password.search(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/) < 0
) {
res.redirect(
"/register?msg=password must contain special characters"
);
} else {
// hash user_password before storing in database
let saltRounds = 10;
let myPlaintextPassword = user_password;
let hashed_pass = bcrypt.hashSync(myPlaintextPassword, saltRounds);
// get random number for profile picture
let random_number = Math.floor(Math.random() * 5) + 1;
let profile_picture = `profile${random_number}.jpg`;
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `INSERT INTO users_details (user_name, user_email ,user_password,profile_img) VALUES (?, ?, ?, ?)`;
let params = [user_name, user_email, hashed_pass, profile_picture];
// execute the prepared statement
db.query(sql, params, (err, result) => {
if (err) throw err;
res.redirect("/?msg=registered successfully");
});
}
}
}
});
});
// login user
app.get("/loginForm", (req, res) => {
// get username,password and room from form
let user_name = req.query.username;
let user_password = req.query.password;
let room = req.query.room;
// check if user exists
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `SELECT * FROM users_details WHERE user_email = ? or user_name = ?`;
let params = [user_name, user_name];
// execute the prepared statement
db.query(sql, params, (err, result) => {
if (err) throw err;
if (result.length > 0) {
// check if password matches
let hashed_pass = result[0].user_password;
let match = bcrypt.compareSync(user_password, hashed_pass);
if (match) {
// check if user is already in room
let user = getActiveUser(user_name);
if (user) {
exitRoom(user);
} else {
// set session variables
req.session.user_name = user_name;
req.session.room = room;
req.session.image = result[0].profile_img;
req.session.id = result[0].id;
// if user status is 0 then proceed else redirect to index page
if (result[0].user_status == 0) {
let stats = 1;
// Set up the prepared statement and the parameters to prevent SQL injection
let statusUpdate = `UPDATE users_details SET user_status = ? WHERE user_name = ?`;
let params = [stats, user_name];
// execute the prepared statement
db.query(statusUpdate, params, (err, result_) => {
if (err) throw err;
// redirect to chat page
if (req.session.user_name && req.session.id && req.session.room) {
res.redirect(
`/chat?username=${user_name}&room=${room}&image=${result[0].profile_img}`
);
} else {
res.redirect("/");
}
});
} else {
res.redirect("/?loginerror= user already logged in");
}
}
} else {
res.redirect("/?loginerror= password is incorrect");
}
} else {
res.redirect("/?loginerror= user does not exist");
}
});
});
// ********************************************************************************* //
// define app routes
// ********************************************************************************* //
// index page
app.get("/", (req, res) => {
// check if user is logged in
if (req.session.user_name && req.session.id && req.session.room) {
res.redirect(
`/chat?username=${req.session.user_name}&room=${req.session.room}&image=${req.session.image}`
);
} else {
res.sendFile(path.join(__dirname + "/public/index.html"));
}
});
// chat page
app.get("/chat", (req, res) => {
// check if user is logged in
if (req.session.id) {
res.sendFile(path.join(__dirname + "/public/chat.html"));
} else {
// set status to offline
// Set up the prepared statement and the parameters to prevent SQL injection
let sql_ = `UPDATE users_details SET user_status = '0' WHERE user_name = ?`;
let params = [req.session.user_name];
// execute the prepared statement
db.query(sql_, params, (err, result) => {
if (err) throw err;
// destroy session
req.session.destroy();
// redirect to index page
res.redirect("/?loginerror=login to access chat");
});
}
});
// register page
app.get("/register", (req, res) => {
res.sendFile(path.join(__dirname + "/public/register.html"));
});
// logout
app.get("/logout", (req, res) => {
// set user_status to offline
let stats = 0;
// Set up the prepared statement and the parameters to prevent SQL injection
let sql_ = `UPDATE users_details SET user_status = ? WHERE user_name = ?`;
let params = [stats, req.session.user_name];
db.query(sql_, params, (err, result) => {
if (err) throw err;
// destroy session
req.session.destroy();
// redirect to index page
res.redirect("/");
});
});
// ********************************************************************************* //
// THIS BLOCK RUNS WHEN USER CONNECTS TO SOCKET
// ********************************************************************************* //
io.on("connection", (socket) => {
try {
// connect port
socket.on("connectPort", (port) => {
console.log("port entered");
clientConnection = port;
server2messages = "";
getPort(clientConnection, server2messages);
io.emit("success");
});
// emit message to client
socket.on("serverChatMessage", (msg) => {
io.emit("serverMessages", formatMessage("Server1", msg));
getPort(clientConnection, msg);
});
// ********************************************************************************* //
// JOIN ROOM
// ********************************************************************************* //
socket.on("joinRoom", ({ username, room }) => {
let stats = 1;
const user = newUser(socket.id, username, room);
socket.join(user.room);
socket.emit(
"messages",
formatMessage("CloudChat", "Messages are limited to this room! ")
);
// select all users in database
let all_Users = `SELECT * FROM users_details`;
// execute the prepared statement
db.query(all_Users, (err, result) => {
if (err) throw err;
// Current active users and room name
io.to(user.room).emit("roomUsers", {
room: user.room,
users: getIndividualRoomUsers(user.room),
data: result,
});
});
// Set up the prepared statement and the parameters to prevent SQL injection
let statusUpdate = `UPDATE users_details SET user_status = ? WHERE user_name = ?`;
let params = [stats, username];
// execute the prepared statement
db.query(statusUpdate, params, (err, result) => {
if (err) throw err;
});
// ********************************************************************************* //
// edit profile details
// ********************************************************************************* //
socket.on("editProfile", (data) => {
// Set up the prepared statement and the parameters to prevent SQL injection
let editProfile = `UPDATE users_details SET user_name = ?, user_email = ? WHERE user_name = ? or user_email = ?`;
let params = [data.username, data.email, username, data.email];
// upadate user details in messages table
// Set up the prepared statement and the parameters to prevent SQL injection
let updateMessages = `UPDATE messages SET user_id = ? WHERE user_id = ?`;
let params_1 = [data.username, username];
db.query(updateMessages, params_1, (err, result) => {
if (err) throw err;
});
// execute the prepared statement
db.query(editProfile, params, (err, result) => {
if (err) throw err;
// update user
user.username = data.username;
user.email = data.email;
// get all new details from database
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `SELECT * FROM users_details WHERE user_name = ? or user_email = ?`;
let params_1 = [data.username, data.email];
// execute the prepared statement
db.query(sql, params_1, (err, result) => {
// redirect to chat page with new details
redirect = `/chat?username=${data.username}&room=${user.room}&image=${result[0].profile_img}`;
socket.emit("redirect", redirect);
});
});
});
// edit password
socket.on("editPassword", (data) => {
// Set up the prepared statement and the parameters to prevent SQL injection
let checkPassword = `SELECT * FROM users_details WHERE user_name = ?`;
let params = [username];
// execute the prepared statement
db.query(checkPassword, params, (err, result) => {
if (err) throw err;
result.forEach((row) => {
let hashedPassword = row.user_password;
let match = bcrypt.compareSync(data.old_password, hashedPassword);
if (match) {
// hash password
let hashPassword = bcrypt.hashSync(data.new_password, 10);
// Set up the prepared statement and the parameters to prevent SQL injection
let editPassword = `UPDATE users_details SET user_password = ? WHERE user_name = ?`;
let params = [hashPassword, username];
// execute the prepared statement
db.query(editPassword, params, (err, result) => {
if (err) throw err;
// redirect to chat page with new details
socket.emit(
"passwordError",
formatMessage("Success", "Password changed successfully! ")
);
// redirect to chat page with new details
setTimeout(() => {
redirect = `/chat?username=${username}&room=${user.room}&image=${row.profile_img}`;
socket.emit("redirect", redirect);
}, 2000);
});
} else {
socket.emit(
"passwordError",
formatMessage("Error", "Incorrect password! ")
);
}
});
});
});
// display profile details to user
// Set up the prepared statement and the parameters to prevent SQL injection
let profile = `SELECT * FROM users_details WHERE user_name = ?`;
let preofileDetails = [username];
// execute the prepared statement
db.query(profile, preofileDetails, (err, result) => {
if (err) throw err;
socket.emit("profileDetails", result);
});
// broadcast chat history from database
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `SELECT * FROM messages WHERE chat_room = ?`;
let params_1 = [user.room];
// execute the prepared statement
db.query(sql, params_1, (err, result) => {
if (err) throw err;
// decrypt the message
for (let i = 0; i < result.length; i++) {
const decrypted = CryptoJS.AES.decrypt(result[i].message, secretKey);
result[i].message = decrypted.toString(CryptoJS.enc.Utf8);
}
socket.emit("chatHistory", result);
});
// Broadcast everytime users connects
socket.broadcast
.to(user.room)
.emit(
"messages",
formatMessage(
"CloudChat_join",
`${user.username} has joined the room`
)
);
});
// ********************************************************************************* //
// Listen for client message
// ********************************************************************************* //
socket.on("chatMessage", ({ msg, image }) => {
const user = getActiveUser(socket.id);
// select user profile image
// Set up the prepared statement and the parameters to prevent SQL injection
let sql_ = `SELECT profile_img FROM users_details WHERE user_name = ?`;
let params_2 = [user.username];
// execute the prepared statement
db.query(sql_, params_2, (err, result) => {
if (err) throw err;
image = result[0].profile_img;
io.to(user.room).emit(
"messages",
formatMessage(user.username, msg, image)
);
});
// Encrypt the message
let encrypted = CryptoJS.AES.encrypt(msg, secretKey).toString();
// save message to database with user id
// Set up the prepared statement and the parameters to prevent SQL injection
let sql = `INSERT INTO messages (user_id, message, chat_room,images) VALUES (?, ?, ?,?)`;
let params_3 = [user.username, encrypted, user.room, image];
// execute the prepared statement
db.query(sql, params_3, (err) => {
if (err) throw err;
});
});
// ********************************************************************************* //
// Runs when client disconnects
// ********************************************************************************* //
socket.on("disconnect", () => {
const user = exitRoom(socket.id);
// update user status to 0
let stats = 0;
// Set up the prepared statement and the parameters to prevent SQL injection
let statusUpdate = `UPDATE users_details SET user_status = ? WHERE user_name = ?`;
let params_4 = [stats, user.username];
db.query(statusUpdate, params_4, (err, result_) => {
if (err) throw err;
});
if (user) {
io.to(user.room).emit(
"messages",
formatMessage("cloudchat_left", `${user.username} has left the room`)
);
// select all users in database
let sql_ = `SELECT * FROM users_details`;
// execute the prepared statement
db.query(sql_, (err, result) => {
if (err) throw err;
// Current active users and room name
io.to(user.room).emit("roomUsers", {
room: user.room,
users: getIndividualRoomUsers(user.room),
pic: result,
});
});
}
});
} catch (error) {
if (error) {
console.log("There was an error processing your request");
}
}
});
// ********************************************************************************* //
// CONNECT TO OTHER SERVERS
// ********************************************************************************* //
function getPort(clientConnection, server2messages) {
const server1 = socketioClient(`${clientConnection}`);
server1.on("connect", () => {
// emit success connection
let msg = "connected to server on:" + clientConnection;
io.emit("serverprocess", formatMessage("SUCCESS", msg));
// SEND MESSAGE TO SERVER
// const rl = readline.createInterface({
// input: process.stdin,
// output: process.stdout,
// prompt: "CLOUDCHAT:",
// removeHistoryDuplicates: true,
// terminal: true,
// emitKeypressEvents: true,
// });
// rl.on("line", (input) => {
// io.emit("message", input);
// rl.prompt();
// });
// rl.prompt();
// rl.on("close", () => {
// msg = "Have a great day!";
// io.emit("sendServerMessaage", formatMessage("CHATSERVER2", msg));
// process.exit(0);
// });
// sends message to other server
io.emit("message", server2messages);
// receive message from other server
server1.on("message", (msg) => {
io.emit("serverMessages", formatMessage("CHATSERVER2", msg));
});
});
// connection timeout
server1.on("connect_timeout", (err) => {
if (err) {
// emit success connection
let msg = "Error connecting to server (connection timeout)";
io.emit("serverprocess", formatMessage("FAIL", msg));
}
});
// connection error
server1.on("connect_error", (err) => {
if (err) {
// emit success connection
let msg = "Error connecting to server ";
io.emit("serverprocess", formatMessage("FAIL", msg));
}
});
// message when disconnected from server
server1.on("disconnect", () => {
msg = "disconnected from server";
io.emit("serverprocess", formatMessage("FAIL", msg));
});
}
// ********************************************************************************* //
// PORT TO RUN SERVER
// ********************************************************************************* //
const PORT = 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));