2020-08-20 13:05:50 +00:00
|
|
|
const OError = require('@overleaf/o-error')
|
2020-06-23 17:29:44 +00:00
|
|
|
const { EventEmitter } = require('events')
|
2020-08-20 10:38:10 +00:00
|
|
|
const { MissingSessionError } = require('./Errors')
|
2020-06-06 12:37:40 +00:00
|
|
|
|
2020-06-23 17:29:44 +00:00
|
|
|
module.exports = function (io, sessionStore, cookieParser, cookieName) {
|
2020-08-20 10:38:10 +00:00
|
|
|
const missingSessionError = new MissingSessionError()
|
2020-06-06 12:37:40 +00:00
|
|
|
|
2020-06-23 17:29:44 +00:00
|
|
|
const sessionSockets = new EventEmitter()
|
2020-07-07 10:06:02 +00:00
|
|
|
function next(error, socket, session) {
|
2020-06-23 17:29:44 +00:00
|
|
|
sessionSockets.emit('connection', error, socket, session)
|
2020-07-07 10:06:02 +00:00
|
|
|
}
|
2020-06-06 12:37:40 +00:00
|
|
|
|
2020-06-23 17:29:44 +00:00
|
|
|
io.on('connection', function (socket) {
|
|
|
|
const req = socket.handshake
|
2020-07-07 10:06:02 +00:00
|
|
|
cookieParser(req, {}, function () {
|
2020-06-23 17:29:44 +00:00
|
|
|
const sessionId = req.signedCookies && req.signedCookies[cookieName]
|
|
|
|
if (!sessionId) {
|
|
|
|
return next(missingSessionError, socket)
|
|
|
|
}
|
2020-07-07 10:06:02 +00:00
|
|
|
sessionStore.get(sessionId, function (error, session) {
|
2020-06-23 17:29:44 +00:00
|
|
|
if (error) {
|
2020-08-20 13:05:50 +00:00
|
|
|
OError.tag(error, 'error getting session from sessionStore', {
|
|
|
|
sessionId
|
|
|
|
})
|
2020-06-23 17:29:44 +00:00
|
|
|
return next(error, socket)
|
|
|
|
}
|
|
|
|
if (!session) {
|
|
|
|
return next(missingSessionError, socket)
|
|
|
|
}
|
2020-07-07 10:06:02 +00:00
|
|
|
next(null, socket, session)
|
2020-06-23 17:29:44 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
2020-06-06 12:37:40 +00:00
|
|
|
|
2020-06-23 17:29:44 +00:00
|
|
|
return sessionSockets
|
|
|
|
}
|