This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
'use strict';
const { Server } = require('socket.io');
const jwt = require('jsonwebtoken');
const logger = require('./logger');
let io;
function init(httpServer) {
io = new Server(httpServer, {
cors: {
origin: process.env.NODE_ENV === 'production'
? process.env.CORS_ORIGIN
: true,
credentials: true,
},
});
io.use((socket, next) => {
const token = socket.handshake.auth?.token;
if (!token) {
return next(new Error('Authentication required'));
}
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => {
if (err) return next(new Error('Invalid token'));
socket.data.user = decoded;
next();
});
});
io.on('connection', (socket) => {
logger.debug({ userId: socket.data.user?.id }, 'Socket connected');
socket.on('disconnect', (reason) => {
logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected');
});
});
logger.info('Socket.io initialized');
return io;
}
function getIo() {
if (!io) throw new Error('Socket.io not initialized — call init() first');
return io;
}
module.exports = { init, getIo };