-
Notifications
You must be signed in to change notification settings - Fork 10
/
app.ts
481 lines (458 loc) · 15.3 KB
/
app.ts
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
/*
Copyright 2017-2018 James V. Craster
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
//import config from JSON
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("games/games.json", "utf-8"));
let configGameList: any = [];
//dynamically import game classes and add their constructors to configGameList
for (let i = 0; i < config.games.length; i++) {
import(config.games[i].location)
.then(module => {
configGameList.push({
constructor: module[config.games[i].name],
name: config.games[i].name,
});
})
.catch(e => {
console.log(e);
console.log(
"Non-critical warning, a game is missing: " + config.games[i].name,
);
});
}
import { Server } from "./core/server";
import { Socket } from "./node_modules/@types/socket.io";
import { Colors } from "./core/core";
const myArgs = process.argv.splice(2);
export const DEBUGMODE = myArgs[0];
//register if app is in debug mode
if (DEBUGMODE == "debug") {
process.env.NODE_ENV = "development";
} else {
process.env.NODE_ENV = "production";
}
//register if app is in database mode
let DATABASE: boolean = false;
if (myArgs[0] == "database" || myArgs[1] == "database") {
console.log("database enabled");
DATABASE = true;
} else {
console.log("** DATABASE **");
console.log(
'The database is disabled by default because the game is playable without it. Run "node app.js database" to enable the database.',
);
console.log("Enabling the database would require mysql to be running.");
}
const express = require("express");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const expressSession = require("express-session");
const RedisStore = require("connect-redis")(expressSession);
const redis = require("redis-server");
const redisServer = new redis(6379);
const grawlix = require("grawlix");
const mysql = require("mysql");
const bcrypt = require("bcrypt");
const saltNumber = 10;
let uGameid = 0;
let uPlayerid = 0;
let con: any = undefined;
redisServer.open((err: string) => {});
function connectDatabase() {
//Details of your MySQL server go here (don't worry, these aren't my production details.)
con = mysql.createConnection({
host: "localhost",
user: "jcraster",
password: "password",
database: "OPENWEREWOLF",
});
//if database fails to connect, try to reconnect
con.connect((err: any) => {
if (err) {
console.log("Database error:", err);
setTimeout(connectDatabase, 3000);
}
});
//if database times out due to inactivity, try to reconnect
con.on("error", (err: any) => {
console.log("Database error:", err);
if (err.code == "PROTOCOL_CONNECTION_LOST") {
connectDatabase();
} else {
throw err;
}
});
}
if (DATABASE) {
connectDatabase();
}
//create a new server
let server = new Server();
if (myArgs[0] == "debug") {
server.setDebug();
console.log("debug mode active");
}
//create a session cookie
let session = expressSession({
store: new RedisStore({ host: "localhost", port: 6379 }),
secret: "sakhasdjhasdkjhadkjahsd",
resave: false,
saveUninitialized: true,
});
//log the player into their account
function loginUser(req: any) {
req.session.loggedIn = true;
req.session.username = req.body.username;
req.session.save(() => {});
}
//use session cookie in sockets
io.use(function(socket: any, next: any) {
session(socket.request, socket.request.res, next);
});
app.use(express.json());
//serve static content
app.use("/mobile", express.static(__dirname + "/Mobile/build"));
app.use("/static", express.static(__dirname + "/Mobile/build/static"));
app.use("/", express.static(__dirname + "/client"));
app.use(
"/semantic/dist/semantic.min.js",
express.static(__dirname + "/semantic/dist/semantic.min.js"),
);
app.use(
"/semantic/dist/semantic.min.css",
express.static(__dirname + "/semantic/dist/semantic.min.css"),
);
app.use(
"/semantic/dist/themes/default/assets/fonts/icons.woff",
express.static(
__dirname + "/semantic/dist/themes/default/assets/fonts/icons.woff",
),
);
app.set("view engine", "pug");
app.use(session);
app.get("/imprint", function(req: any, res: any) {
res.render("imprint");
});
app.get("/about", function(req: any, res: any) {
res.render("about");
});
app.get("/mobile", function(req: any, res: any) {
res.render("mobile");
});
app.get("/", function(req: any, res: any) {
let gameNames = [];
for (let i = 0; i < server.games.length; i++) {
gameNames.push(server.games[i].name);
}
let uids = [];
for (let i = 0; i < server.games.length; i++) {
uids.push(server.games[i].uid);
}
//add logic with pug to generate correct lobby
let gameCheckboxesArray: Array<string> = [];
for (let i = 0; i < configGameList.length; i++) {
gameCheckboxesArray.push(configGameList[i].name);
}
res.render("index", {
numberOfGames: server.numberOfGames,
gameNames: gameNames,
players: server.usernameColorPairs,
gameInPlay: server.inPlayArray,
gameTypes: server.gameTypes,
loggedIn: req.session.loggedIn,
username: req.session.username,
uids: uids,
gameCheckboxesArray: gameCheckboxesArray,
});
});
if (DATABASE && con) {
app.post("/register", function(req: any, res: any) {
let status = "success";
//run validation
let letters = /^[A-Za-z]+$/;
if (
typeof req.body.username == "string" ||
req.body.username instanceof String
) {
if (req.body.username.length > 0 && req.body.username.length <= 10) {
if (letters.test(req.body.username)) {
if (!grawlix.isObscene(req.body.username)) {
let sql =
"SELECT username FROM USERS where username=" +
mysql.escape(req.body.username);
con.query(sql, function(err: any, results: any) {
if (results.length == 0) {
if (
typeof req.body.email == "string" ||
req.body.email instanceof String
) {
if (
req.body.email.length > 0 &&
req.body.email.length <= 256
) {
} else {
status = "Your email must be between 1 and 256 characters";
}
}
if (
typeof req.body.password == "string" ||
req.body.email instanceof String
) {
if (
req.body.password.length > 0 &&
req.body.password.length <= 256
) {
if (
typeof req.body.repeatPassword == "string" ||
req.body.repeatPassword instanceof String
) {
if (req.body.password === req.body.repeatPassword) {
} else {
status =
"Your password and repeated password don't match";
}
}
} else {
status =
"Your password must be between 1 and 256 characters";
}
}
if (status == "success") {
bcrypt.genSalt(saltNumber, function(err: any, salt: any) {
bcrypt.hash(req.body.password, salt, function(
err: any,
hash: any,
) {
let sql =
"INSERT INTO USERS VALUES (" +
mysql.escape(req.body.username) +
"," +
mysql.escape(req.body.email) +
"," +
mysql.escape(hash) +
"," +
mysql.escape(salt) +
")";
con.query(sql, function(err: any, result: any) {
if (err) throw err;
});
});
});
//log the player into their new account automatically
loginUser(req);
}
res.send('{ "result":' + JSON.stringify(status) + "}");
} else {
status =
"This username is already taken. Please change your username";
res.send('{ "result":' + JSON.stringify(status) + "}");
}
});
} else {
status =
"Usernames cannot contain profanity. Please change your username";
}
} else {
status =
"Usernames can only contain letters (no numbers or punctuation)";
}
} else {
status = "Your username must be between 1 and 10 characters";
}
}
if (status != "success") {
res.send('{ "result":' + JSON.stringify(status) + "}");
}
});
app.post("/login", function(req: any, res: any) {
let status = "failure";
if (
typeof req.body.username == "string" &&
typeof req.body.password == "string"
) {
let sql =
"SELECT encrypted_password FROM USERS WHERE username=" +
mysql.escape(req.body.username);
con.query(sql, function(err: any, result: any) {
if (result.length != 0) {
bcrypt.compare(
req.body.password,
result[0].encrypted_password,
function(err: any, comparisonResult: any) {
if (comparisonResult == true) {
status = "success";
loginUser(req);
} else {
status = "Your username or password is incorrect.";
}
res.send('{"result":' + JSON.stringify(status) + "}");
},
);
} else {
status = "Your username or password is incorrect.";
res.send('{"result":' + JSON.stringify(status) + "}");
}
});
} else {
res.send('{"result":' + JSON.stringify(status) + "}");
}
});
}
app.post("/logout", function(req: any, res: any) {
req.session.loggedIn = false;
req.session.username = "";
res.send("{}");
});
app.post("/newGame", function(req: any, res: any) {
let result = "success";
if (
typeof req.body.name == "string" &&
typeof req.body.type == "string" &&
req.body.name.length > 0 &&
req.body.name.length < 100
) {
if (grawlix.isObscene(req.body.name)) {
result = "Game names cannot contain profanity.";
}
for (let i = 0; i < server.games.length; i++) {
if (server.games[i].name == req.body.name) {
result =
"This game name is already taken. Please choose a different one.";
}
}
if (result == "success") {
for (let i = 0; i < config.games.length; i++) {
if (config.games[i].name == req.body.type) {
//increase unique game id (used on frontend to distinguish between games)
uGameid++;
server.addGame(
new configGameList[i].constructor(
server,
req.body.name,
uGameid.toString(),
),
);
break;
}
}
}
}
res.send('{"result":' + JSON.stringify(result) + "}");
});
app.post("/forgottenPassword", function(req: any, res: any) {
if (typeof req.body.username == "string") {
//find email in the database matching username 'req.body.username'
let sql =
"SELECT email FROM USERS WHERE username=" +
mysql.escape(req.body.username);
con.query(sql, function(err: any, result: any) {
if (result.length == 0) {
res.send('{"result":"Your username is incorrect"}');
} else {
console.log('{"result":' + JSON.stringify(result[0].email) + "}");
res.send('{"result":"success"}');
}
});
//send the corresponding email address a randomly generated validation link:
//first generate the validation link:
//then send the email:
}
});
app.get("*.png", function() {});
app.get("*", function(req: any, res: any) {
res.render("404");
});
//handle socket requests
io.on("connection", function(socket: Socket) {
//set the session unless it is already set
if (!socket.request.session.socketID) {
socket.request.session.socketID = socket.id;
socket.request.session.save();
}
let time = 0;
uPlayerid++;
let thisPlayerId = uPlayerid.toString();
let oldPlayerId = server.addUser(
socket,
socket.request.session.socketID,
thisPlayerId,
);
//if the player is already playing on a different tab, their playerId changes to
//forward their messages as if they came from the first tab
if (oldPlayerId != undefined) {
thisPlayerId = oldPlayerId;
}
socket.on("reloadClient", function() {
server.reloadClient(thisPlayerId);
});
socket.on("message", function(msg: string) {
if (typeof msg === "string") {
//exclude commands from filtering (they start with a forward slash):
if (msg[0] === "/") {
server.receive(thisPlayerId, msg);
}
//filter for spam(consecutive messages within 1/2 a second)
else if (Date.now() - time < 500) {
socket.emit("message", [{ text: "Please do not spam the chat" }]);
time = Date.now();
} else {
time = Date.now();
server.receive(thisPlayerId, msg);
}
}
});
socket.on("leaveGame", function() {
server.leaveGame(thisPlayerId);
});
socket.on("disconnect", function() {
server.removeSocketFromPlayer(thisPlayerId, socket);
server.kick(thisPlayerId);
});
socket.on("gameClick", function(gameId: string) {
if (parseInt(gameId) != NaN) {
server.gameClick(thisPlayerId, gameId);
}
});
socket.on("localGameClick", function(name: string, gameId: string) {
server.receive(thisPlayerId, name);
if (
server.getUser(thisPlayerId) != undefined &&
server.getGameById(gameId) != undefined
) {
server.gameClick(thisPlayerId, gameId);
}
});
socket.on("lobbyMessage", function(msg: string) {
if (typeof msg === "string") {
if (Date.now() - time < 500) {
time = Date.now();
socket.emit("lobbyMessage", [
{
text: "Chat: Please do not spam the chat",
color: Colors.standardWhite,
},
]);
} else {
time = Date.now();
server.receiveLobbyMessage(thisPlayerId, msg);
}
}
});
});
//listen on port
let port = 8081;
http.listen(port, function() {
console.log("Port is:" + port);
});