forked from Levizar/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
231 lines (193 loc) · 9.01 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
"use strict";
/**
* @author Louis Wicket
*/
const fs = require("fs");
const crypto = require("crypto");
const mysql = require("mysql");
const dbLogin = JSON.parse(fs.readFileSync("login.json"));
const sessionManager = require("./src/sessionManager.js"); // A custom module to handle sessions
const { sanitize } = require("./src/sanitize.js"); // A custom module to sanitize inputs
let guestUsersCounter = 0;
// ----------------- EXPRESS: set up ------------------ \\
const express = require("express");
const app = express();
const http = require("http").createServer(app);
app.disable("x-powered-by"); // Prevent express-targeted attacks
// ----------------- EXPRESS: routage ----------------- \\
app.get(/\/(index)?$/i, (req, res) => {
const session = sessionManager.checkSession(req.headers.cookie);
// Change the connection button with a logout button if the user is already connected
if (session && session.isConnected) {
fs.readFile(__dirname + "/public/index.html", "UTF-8", (err, data) => {
if (err) console.error(err);
else res.status(200).send(data.replace('connection">Connecte-toi !', 'logout">Déconnexion'));
});
} else res.status(200).sendFile(__dirname + "/public/index.html");
});
app.get("/chat", (req, res) => {
const session = sessionManager.checkSession(req.headers.cookie) || sessionManager.newSession(res, {
"userId" : ++guestUsersCounter,
"username" : "Guest " + guestUsersCounter,
"isConnected" : false
});
fs.readFile(__dirname + "/public/chat.html", "UTF-8", (err, data) => {
if (err) console.error(err);
else if (session.isConnected) {
// Change the connection button with a logout button if the user is already connected
res.status(200).send(data.replace('connection">Connecte-toi !', 'logout">Déconnexion'));
} else {
res.status(200).send(data.replace('Ton message ici"', 'Connecte-toi pour pouvoir écrire !" DISABLED').replace(">Envoyer", "DISABLED>Envoyer"));
}
});
});
app.get("/connection", (req, res) => {
// If the user is already connected, redirect him to the chat room
const session = sessionManager.checkSession(req.headers.cookie); // (Waiting for optional chaining ToT)
session && session.isConnected ? res.status(301).redirect("/chat") : res.status(200).sendFile(__dirname + "/public/connection.html");
});
app.get("/logout", (req, res) => {
// If a related session exists, delete it
if (sessionManager.checkSession(req.headers.cookie) !== null)
delete sessionManager.sessions[sessionManager.getSid(req.headers.cookie)];
res.status(301).redirect("/");
});
app.use(express.static(__dirname + "/public")); // Serve assets
app.get("*", (_, res) => res.status(404).send("error 404"));
// Handle sign up requests
app.post("/signup", (req, res) => {
// Receive the posted data
let data = "";
req.on("data", chunk => {
data += chunk;
if (data.length > 1e3) {
req.destroy();
res.status(413).send("REQUEST ENTITY TOO LARGE");
}
});
req.on("end", () => {
// Parse the received data
try {
var { username, password, email } = JSON.parse(data);
} catch {
console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: failed to parse data`);
return res.status(400).send("INVALID DATA");
}
username = sanitize("username", username);
password = sanitize("password", password);
email = sanitize("email", email);
if (username instanceof Error || password instanceof Error || email instanceof Error) {
res.status(400).send("INVALID DATA");
return console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: invalid data`);
} else password = crypto.createHash("sha256").update(password).digest("base64"); // Hash the password
// PROCESS
const db = mysql.createConnection(dbLogin);
db.connect();
// Check that the username is available
db.query(`SELECT id FROM users WHERE username = ? LIMIT 1`, username, (err, rows) => {
if (err) {
console.error(err);
res.status(500).send();
} else if (rows.length !== 0) {
console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: unavailable username`);
res.status(403).send("UNAVAILABLE USERNAME");
} else {
// Create a new user account
const userId = crypto.randomBytes(16).toString("hex");
db.query(
`INSERT INTO users (id, username, sha256_password, email) VALUES (?, ?, ?, ?)`,
[
userId,
username,
password,
email
],
(err, _) => {
if (err) {
console.error(err);
res.status(500).send();
}
else {
console.log("\x1b[1m\x1b[32m%s\x1b[0m", `New account created: ${username}.`);
sessionManager.newSession(res, {
"userId" : userId,
"username" : username,
"isConnected" : true
});
res.status(200).send("Account successfully created");
}
}
);
db.end();
}
});
});
});
// Handle sign in requests
app.post("/login", (req, res) => {
// Receive the posted data
let data = "";
req.on("data", chunk => {
data += chunk;
if (data.length > 1e3) {
req.destroy();
res.status(413).send("REQUEST ENTITY TOO LARGE");
}
});
req.on("end", () => {
const ip = sessionManager.getIp(req);
// An IP can be blacklisted after too many failed login attempts
if (sessionManager.isBlacklisted(ip)) return res.status(429).send("TOO MANY REQUESTS");
// Parse the received data
try {
var { username, password } = JSON.parse(data);
} catch {
console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: failed to parse data`);
return res.status(400).send("INVALID DATA");
}
// SANITIZE
username = sanitize("username", username);
password = sanitize("password", password);
if (username instanceof Error || password instanceof Error) {
res.status(400).send("INVALID DATA");
return console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: invalid data`);
} else password = crypto.createHash("sha256").update(password).digest("base64"); // Hash the password
// PROCESS
const db = mysql.createConnection(dbLogin);
db.connect();
db.query(`SELECT sha256_password, id FROM users WHERE username = ? LIMIT 1`, username, (err, rows) => {
if (err) {
console.error(err);
res.status(500).send();
} else if (rows.length !== 0) {
const userData = rows[0];
if (userData["sha256_password"] === password) {
// The user is authenticated: create a new related session
sessionManager.newSession(res, {
"userId" : userData["id"],
"username" : username,
"isConnected" : true
});
res.status(200).send("USER SUCCESSFULLY AUTHENTICATED");
console.log(`%s${username} %sconnected`, "\x1b[1m\x1b[34m", "\x1b[1m\x1b[32m", "\x1b[0m");
// Reset the counter of failed login attempts
delete sessionManager.failedAttempts[ip];
} else {
console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: the password doesn't match`);
res.status(403).send("WRONG LOGIN DETAILS");
// If the password doesn't match, increment a counter which blocks the IP when a defined amount of failed attempts is reached
sessionManager.failedAttempts[ip] ? sessionManager.failedAttempts[ip]++ : sessionManager.failedAttempts[ip] = 1;
}
} else {
console.error("\x1b[1m\x1b[31m%s\x1b[0m", `${req.method} ${req.url}: failed to authenticate the user`);
res.status(403).send("WRONG LOGIN DETAILS");
}
});
db.end();
});
});
const port = 8080;
http.listen(port, () => console.log("\x1b[1m\x1b[32m%s\x1b[0m", `Listening on port ${port}.`));
// ---------------- SOCKET.IO ---------------- \\
const io = require("socket.io")(http);
require("./src/ws-server.js").init(io, sessionManager);