Initial commit
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
// Clients join a room per campaign (`campaign:<id>`) after authenticating with
|
||||
// the same JWT issued by /auth/login. Server-side route handlers emit into
|
||||
// these rooms (see character:updated, encounter:*-updated, character:created).
|
||||
function attachSockets(io) {
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth && socket.handshake.auth.token;
|
||||
if (!token) return next(new Error('Missing auth token'));
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET);
|
||||
socket.user = { id: payload.sub, email: payload.email };
|
||||
return next();
|
||||
} catch (err) {
|
||||
return next(new Error('Invalid or expired token'));
|
||||
}
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
socket.on('campaign:join', (campaignId) => {
|
||||
if (typeof campaignId === 'string') socket.join(`campaign:${campaignId}`);
|
||||
});
|
||||
socket.on('campaign:leave', (campaignId) => {
|
||||
if (typeof campaignId === 'string') socket.leave(`campaign:${campaignId}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { attachSockets };
|
||||
Reference in New Issue
Block a user