SessionSockets.js 949 B

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