SessionSockets.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS102: Remove unnecessary code created because of implicit returns
  6. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  7. */
  8. const { EventEmitter } = require('events')
  9. module.exports = function (io, sessionStore, cookieParser, cookieName) {
  10. const missingSessionError = new Error('could not look up session by key')
  11. const sessionSockets = new EventEmitter()
  12. const next = (error, socket, session) =>
  13. sessionSockets.emit('connection', error, socket, session)
  14. io.on('connection', function (socket) {
  15. const req = socket.handshake
  16. return cookieParser(req, {}, function () {
  17. const sessionId = req.signedCookies && req.signedCookies[cookieName]
  18. if (!sessionId) {
  19. return next(missingSessionError, socket)
  20. }
  21. return sessionStore.get(sessionId, function (error, session) {
  22. if (error) {
  23. return next(error, socket)
  24. }
  25. if (!session) {
  26. return next(missingSessionError, socket)
  27. }
  28. return next(null, socket, session)
  29. })
  30. })
  31. })
  32. return sessionSockets
  33. }