2024-06-12 05:51:37 -04:00
|
|
|
const metrics = require('@overleaf/metrics')
|
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) {
|
2024-06-12 05:51:37 -04:00
|
|
|
metrics.inc('session.cookie', 1, {
|
|
|
|
// the cookie-parser middleware sets the signed cookie to false if the
|
|
|
|
// signature is invalid, so we can use this to detect bad signatures
|
|
|
|
status: sessionId === false ? 'bad-signature' : 'none',
|
|
|
|
})
|
2020-06-23 13:29:44 -04:00
|
|
|
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) {
|
2024-06-12 05:51:37 -04:00
|
|
|
metrics.inc('session.cookie', 1, { status: '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) {
|
2024-06-12 05:51:37 -04:00
|
|
|
metrics.inc('session.cookie', 1, { status: 'missing' })
|
2020-06-23 13:29:44 -04:00
|
|
|
return next(missingSessionError, socket)
|
|
|
|
}
|
2024-06-12 05:51:37 -04:00
|
|
|
metrics.inc('session.cookie', 1, { status: 'signed' })
|
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
|
|
|
|
}
|