File size: 646 Bytes
45323a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const jwt = require('jsonwebtoken');
function authenticateSocket(socket, next) {
// The token is sent in the 'auth' object during connection
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error('Authentication error: No token provided.'));
}
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
return next(new Error('Authentication error: Invalid token.'));
}
// Attach the decoded user payload to the socket object
socket.user = decoded;
next();
});
}
module.exports = authenticateSocket;
|