SessionSockets.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. const OError = require('@overleaf/o-error')
  2. const { EventEmitter } = require('events')
  3. module.exports = function (io, sessionStore, cookieParser, cookieName) {
  4. const missingSessionError = new Error('could not look up session by key')
  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. OError.tag(error, 'error getting session from sessionStore', {
  19. sessionId
  20. })
  21. return next(error, socket)
  22. }
  23. if (!session) {
  24. return next(missingSessionError, socket)
  25. }
  26. next(null, socket, session)
  27. })
  28. })
  29. })
  30. return sessionSockets
  31. }