-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
77 lines (66 loc) · 2.62 KB
/
Copy pathserver.cjs
File metadata and controls
77 lines (66 loc) · 2.62 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
76
77
const WebSocket = require('ws');
const jwt = require('jsonwebtoken');
class WebSocketServer {
constructor() {
this.JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
this.authenticatedClients = new Map();
this.server = new WebSocket.Server({
port: 8080,
verifyClient: this.verifyClient.bind(this)
});
this.initialize();
}
verifyClient(info, callback) {
console.log('Новое подключение, заголовки:', info.req.headers);
callback(true);
}
verifyToken(token) {
try {
console.log('Проверка токена:', token);
return jwt.verify(token, this.JWT_SECRET);
} catch (error) {
console.error('Ошибка проверки токена:', error.message);
return null;
}
}
initialize() {
this.server.on('connection', (ws, req) => {
const userId = req.url.split('/').pop();
console.log(`Попытка подключения пользователя: ${userId}`);
let isAuthenticated = false;
ws.on('message', (message) => {
try {
const data = JSON.parse(message.toString());
if (data.type === 'auth') {
const decoded = this.verifyToken(data.token);
if (decoded && decoded.userId === userId) {
isAuthenticated = true;
this.authenticatedClients.set(userId, ws);
ws.send(JSON.stringify({
type: 'auth',
status: 'success'
}));
} else {
ws.send(JSON.stringify({
type: 'auth',
status: 'error',
message: 'Неверный токен'
}));
ws.close();
}
}
} catch (error) {
console.error('Ошибка обработки сообщения:', error);
console.trace(error); // Вывод стека вызовов
}
});
ws.on('close', () => {
if (isAuthenticated) {
this.authenticatedClients.delete(userId);
}
});
});
}
}
// Создаем экземпляр сервера
const wsServer = new WebSocketServer();