SessionSockets.js 917 B

12345678910111213141516171819202122232425262728293031
  1. const { EventEmitter } = require('events')
  2. module.exports = function (io, sessionStore, cookieParser, cookieName) {
  3. const missingSessionError = new Error('could not look up session by key')
  4. const sessionSockets = new EventEmitter()
  5. function next(error, socket, session) {
  6. sessionSockets.emit('connection', error, socket, session)
  7. }
  8. io.on('connection', function (socket) {
  9. const req = socket.handshake
  10. cookieParser(req, {}, function () {
  11. const sessionId = req.signedCookies && req.signedCookies[cookieName]
  12. if (!sessionId) {
  13. return next(missingSessionError, socket)
  14. }
  15. sessionStore.get(sessionId, function (error, session) {
  16. if (error) {
  17. return next(error, socket)
  18. }
  19. if (!session) {
  20. return next(missingSessionError, socket)
  21. }
  22. next(null, socket, session)
  23. })
  24. })
  25. })
  26. return sessionSockets
  27. }