r2
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user