-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwshandler.js
69 lines (57 loc) · 2.13 KB
/
wshandler.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
import express from "express";
import jwt from "jsonwebtoken";
import WebSocket from "ws";
import { Server } from "./server.js";
export class WebSocketHandler {
constructor(server, SECRET_KEY = "super_secret_key") {
if (!(server instanceof Server)) {
throw new Error("Invalid server instance");
}
this.server = server;
this.app = express();
this.SECRET_KEY = SECRET_KEY;
this.wss = new WebSocket.Server({ port: 8081 });
this.app.use(express.json());
this.setupRoutes();
this.setupWebSocket();
}
setupRoutes() {
this.app.post("/login", (req, res) => {
const { username, password } = req.body;
const player = this.server.players.db.getPlayerByName(username);
if (player && player.password === password) {
const token = jwt.sign({ username }, this.SECRET_KEY, { expiresIn: "12h" });
return res.json({ token });
}
res.status(401).json({ error: "Invalid credentials" });
});
}
setupWebSocket() {
this.wss.on("connection", (ws, req) => {
const urlParams = new URLSearchParams(req.url.split("?")[1]);
const token = urlParams.get("token");
if (!token) {
ws.close();
return;
}
try {
const decoded = jwt.verify(token, this.SECRET_KEY);
ws.username = decoded.username;
console.log(`User ${ws.username} connected via WebSocket`);
ws.send(JSON.stringify({ message: "Welcome to OrbitComms Server!" }));
ws.on("message", (message) => {
this.server.processMessage(ws.username, message);
});
} catch (error) {
ws.close();
}
});
}
sendMessageToUser(username, data) {
this.wss.clients.forEach(client => {
if (client.username === username && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ username: "server", data }));
}
});
}
}