safetySocks.js
1 // Zen - Dec. 9th 2024 2 // This library replaces the socketio-auth library. 3 4 // Eventually it will be obsolete in favor of futr-based 5 // authentication strategies, but I still want it to work. 6 7 const socketAuth = (io, config) => { 8 config = config || {}; 9 let timeout = config.timeout || 1000; 10 let postAuthenticate = config.postAuthenticate || function () {}; 11 let disconnect = config.disconnect || function () {}; 12 13 // Removed 'forbid all namespace connections' 14 15 io.on('connection', (socket) => { 16 socket.auth = false 17 socket.on('authentication', (data) => { 18 config.authenticate(socket, data, (err, success) => { 19 if (success) { 20 console.log('Authenticated socket', socket.id) 21 socket.auth = true 22 23 // Removed 'restore all namespace connections' 24 25 socket.emit('authenticated', success) 26 return postAuthenticate(socket, data) 27 } else if (err) { 28 console.log('Authentication error: ', err.message) 29 socket.emit('unauthorized', { message: err.message }, () => { 30 socket.disconnect() 31 }) 32 } else { 33 console.log('Authentication failed.') 34 socket.emit('unauthorized', { message: 'general failure' }, () => { 35 socket.disconnect() 36 }) 37 } 38 }) 39 }) 40 41 socket.on('disconnect', () => disconnect(socket)) 42 43 if (timeout !== 'none') { 44 setTimeout(() => { 45 if (!socket.auth) { 46 console.log('disconnecting socket', socket.id) 47 socket.disconnect('unauthorized') 48 } 49 }, timeout) 50 } 51 }) 52 } 53 54 export default socketAuth