-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (58 loc) · 2.03 KB
/
Copy pathserver.js
File metadata and controls
71 lines (58 loc) · 2.03 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
const WebSocket = require('ws');
const jwt = require('jsonwebtoken');
const { text } = require('express');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
const wss = new WebSocket.Server({ port: PORT });
const clients = new Map();
const userPastes = {};
wss.on('connection', (ws, req) => {
console.log('Client connected!');
const urlParams = new URLSearchParams(req.url.slice(1));
const token = urlParams.get('token');
if (!token) {
ws.send(JSON.stringify({ status: 1, msg: 'ERROR: missing token' }));
ws.close();
return;
}
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
console.log('Invalid JWT: ', err.message);
ws.send(JSON.stringify({ status: 1, msg: 'Error invalid or expired token' }));
ws.close();
return;
}
const userId = decoded.id;
console.log('Authenticated user: ', userId);
clients.set(ws, userId);
ws.send(JSON.stringify({
type: 'init',
text: userPastes[userId] || ''
}));
ws.on('message', (msg) => {
console.log(`Message from ${userId}:`, msg.toString());
let parsed;
try {
parsed = JSON.parse(msg);
} catch {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
return;
}
if (parsed.type == 'update') {
userPastes[userId] = parsed.text;
for (const [client, id] of clients.entries()) {
if (id === userId && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'update',
text: parsed.text
}));
}
}
}
});
ws.on('close', () => {
console.log(`User ${userId} disconnected`);
clients.delete(ws);
})
});
});