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