SessionSockets.js 1.1 KB

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