-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (68 loc) · 2.05 KB
/
server.js
File metadata and controls
75 lines (68 loc) · 2.05 KB
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
const app = require("express")();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
let currentUsers = 0;
let userDB = [];
let usersOnline = [];
let authenticateKey = (name, key) => {
let authenticated = false;
const account = usersOnline.find(acc => acc.user === name);
if (account !== undefined) {
authenticated = key === account.key;
}
return authenticated;
};
io.on("connection", function(socket) {
currentUsers += 1;
console.log(`${currentUsers} online now`);
socket.on("disconnect", () => {
currentUsers -= 1;
console.log(`${currentUsers} online now`);
});
socket.on("register", info => {
const regiStasus = { username: false };
if (info.username.length > 0 && info.username.match(/^[a-zA-Z0-9_]*$/)) {
let userRegistering = userDB.find(
user => user.username.toLowerCase() === info.username.toLowerCase()
);
if (userRegistering == null) {
regiStasus.username = true;
userDB.push({ username: info.username, password: info.password });
}
}
socket.emit("registerStatus", regiStasus);
});
socket.on("login", info => {
let userLoggingIn = userDB.find(
user => user.username.toLowerCase() === info.username.toLowerCase()
);
if (userLoggingIn == null) {
socket.emit("loginStatus", { success: false });
} else {
if (userLoggingIn.password === info.password) {
const userKey = Math.floor(100000 + Math.random() * 900000);
usersOnline.push({
user: userLoggingIn.username,
key: userKey
});
socket.emit("loginStatus", {
success: true,
user: userLoggingIn.username,
key: userKey
});
console.log(usersOnline);
} else {
socket.emit("loginStatus", { success: false });
}
}
});
socket.on("chatMessage", msg => {
if (authenticateKey(msg.user, msg.key)) {
console.log(msg);
io.emit("chatMessage", msg);
}
});
});
http.listen(4000, function() {
console.log("listening on *:4000");
});