diff --git a/services/web/app/src/Features/Analytics/AnalyticsController.js b/services/web/app/src/Features/Analytics/AnalyticsController.js index 8c4d69a8e7..30329616f0 100644 --- a/services/web/app/src/Features/Analytics/AnalyticsController.js +++ b/services/web/app/src/Features/Analytics/AnalyticsController.js @@ -1,6 +1,6 @@ const metrics = require('@overleaf/metrics') const AnalyticsManager = require('./AnalyticsManager') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const GeoIpLookup = require('../../infrastructure/GeoIpLookup') const Features = require('../../infrastructure/Features') @@ -9,7 +9,7 @@ module.exports = { if (!Features.hasFeature('analytics')) { return res.sendStatus(202) } - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { projectId } = req.params let countryCode = null @@ -31,7 +31,7 @@ module.exports = { return res.sendStatus(202) } const userId = - AuthenticationController.getLoggedInUserId(req) || req.sessionID + SessionManager.getLoggedInUserId(req.session) || req.sessionID AnalyticsManager.recordEvent(userId, req.params.event, req.body) res.sendStatus(202) }, diff --git a/services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js b/services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js index ffd95fc26c..19b7c96619 100644 --- a/services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js +++ b/services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js @@ -1,7 +1,7 @@ const logger = require('logger-sharelatex') const OError = require('@overleaf/o-error') const AnalyticsRegistrationSourceHelper = require('./AnalyticsRegistrationSourceHelper') -const AuthenticationController = require('../../Features/Authentication/AuthenticationController') +const SessionManager = require('../../Features/Authentication/SessionManager') function setSource(source) { return function (req, res, next) { @@ -25,7 +25,7 @@ function setInbound() { return next() // don't overwrite referrer } - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { return next() // don't store referrer if user is alread logged in } diff --git a/services/web/app/src/Features/Authentication/AuthenticationController.js b/services/web/app/src/Features/Authentication/AuthenticationController.js index 31c07acdb5..bbd0d4c543 100644 --- a/services/web/app/src/Features/Authentication/AuthenticationController.js +++ b/services/web/app/src/Features/Authentication/AuthenticationController.js @@ -1,4 +1,5 @@ const AuthenticationManager = require('./AuthenticationManager') +const SessionManager = require('./SessionManager') const OError = require('@overleaf/o-error') const LoginRateLimiter = require('../Security/LoginRateLimiter') const UserUpdater = require('../User/UserUpdater') @@ -185,58 +186,16 @@ const AuthenticationController = { }) }, - setInSessionUser(req, props) { - const sessionUser = AuthenticationController.getSessionUser(req) - if (!sessionUser) { - return - } - for (const key in props) { - const value = props[key] - sessionUser[key] = value - } - return null - }, - - isUserLoggedIn(req) { - const userId = AuthenticationController.getLoggedInUserId(req) - return ![null, undefined, false].includes(userId) - }, - - // TODO: perhaps should produce an error if the current user is not present - getLoggedInUserId(req) { - const user = AuthenticationController.getSessionUser(req) - if (user) { - return user._id - } else { - return null - } - }, - - getLoggedInUserV1Id(req) { - const user = AuthenticationController.getSessionUser(req) - if ((user != null ? user.v1_id : undefined) != null) { - return user.v1_id - } else { - return null - } - }, - - getSessionUser(req) { - const sessionUser = _.get(req, ['session', 'user']) - const sessionPassportUser = _.get(req, ['session', 'passport', 'user']) - return sessionUser || sessionPassportUser || null - }, - requireLogin() { const doRequest = function (req, res, next) { if (next == null) { next = function () {} } - if (!AuthenticationController.isUserLoggedIn(req)) { + if (!SessionManager.isUserLoggedIn(req.session)) { if (acceptsJson(req)) return send401WithChallenge(res) return AuthenticationController._redirectToLoginOrRegisterPage(req, res) } else { - req.user = AuthenticationController.getSessionUser(req) + req.user = SessionManager.getSessionUser(req.session) return next() } } @@ -320,7 +279,7 @@ const AuthenticationController = { if (req.headers.authorization != null) { AuthenticationController.requirePrivateApiAuth()(req, res, next) - } else if (AuthenticationController.isUserLoggedIn(req)) { + } else if (SessionManager.isUserLoggedIn(req.session)) { next() } else { logger.log( @@ -341,7 +300,7 @@ const AuthenticationController = { ) { return next() } - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) if (!(user && user.isAdmin)) { return next() } diff --git a/services/web/app/src/Features/Authentication/SessionManager.js b/services/web/app/src/Features/Authentication/SessionManager.js new file mode 100644 index 0000000000..a64ee98fe1 --- /dev/null +++ b/services/web/app/src/Features/Authentication/SessionManager.js @@ -0,0 +1,46 @@ +const _ = require('lodash') + +const SessionManager = { + getSessionUser(session) { + const sessionUser = _.get(session, ['user']) + const sessionPassportUser = _.get(session, ['passport', 'user']) + return sessionUser || sessionPassportUser || null + }, + + setInSessionUser(session, props) { + const sessionUser = SessionManager.getSessionUser(session) + if (!sessionUser) { + return + } + for (const key in props) { + const value = props[key] + sessionUser[key] = value + } + return null + }, + + isUserLoggedIn(session) { + const userId = SessionManager.getLoggedInUserId(session) + return ![null, undefined, false].includes(userId) + }, + + getLoggedInUserId(session) { + const user = SessionManager.getSessionUser(session) + if (user) { + return user._id + } else { + return null + } + }, + + getLoggedInUserV1Id(session) { + const user = SessionManager.getSessionUser(session) + if (user != null && user.v1_id != null) { + return user.v1_id + } else { + return null + } + }, +} + +module.exports = SessionManager diff --git a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js index c10b48a6c1..ef9a234d40 100644 --- a/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js +++ b/services/web/app/src/Features/Authorization/AuthorizationMiddleware.js @@ -6,6 +6,7 @@ const { ObjectId } = require('mongodb') const Errors = require('../Errors/Errors') const HttpErrorHandler = require('../Errors/HttpErrorHandler') const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler') module.exports = AuthorizationMiddleware = { @@ -244,7 +245,7 @@ module.exports = AuthorizationMiddleware = { _getUserId(req, callback) { const userId = - AuthenticationController.getLoggedInUserId(req) || + SessionManager.getLoggedInUserId(req.session) || (req.oauth_user && req.oauth_user._id) || null callback(null, userId) @@ -258,7 +259,7 @@ module.exports = AuthorizationMiddleware = { }, restricted(req, res, next) { - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { return res.render('user/restricted', { title: 'restricted' }) } const { from } = req.query diff --git a/services/web/app/src/Features/BetaProgram/BetaProgramController.js b/services/web/app/src/Features/BetaProgram/BetaProgramController.js index 4f0f8c5ea8..b8d8d3c49f 100644 --- a/services/web/app/src/Features/BetaProgram/BetaProgramController.js +++ b/services/web/app/src/Features/BetaProgram/BetaProgramController.js @@ -3,11 +3,11 @@ const OError = require('@overleaf/o-error') const UserGetter = require('../User/UserGetter') const Settings = require('@overleaf/settings') const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const BetaProgramController = { optIn(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) logger.log({ userId }, 'user opting in to beta program') if (userId == null) { return next(new Error('no user id in session')) @@ -21,7 +21,7 @@ const BetaProgramController = { }, optOut(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) logger.log({ userId }, 'user opting out of beta program') if (userId == null) { return next(new Error('no user id in session')) @@ -35,7 +35,7 @@ const BetaProgramController = { }, optInPage(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) logger.log({ user_id: userId }, 'showing beta participation page for user') UserGetter.getUser(userId, function (err, user) { if (err) { diff --git a/services/web/app/src/Features/Chat/ChatController.js b/services/web/app/src/Features/Chat/ChatController.js index 78243ae310..4b900a3b0f 100644 --- a/services/web/app/src/Features/Chat/ChatController.js +++ b/services/web/app/src/Features/Chat/ChatController.js @@ -16,8 +16,7 @@ let ChatController const ChatApiHandler = require('./ChatApiHandler') const EditorRealTimeController = require('../Editor/EditorRealTimeController') -const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const UserInfoManager = require('../User/UserInfoManager') const UserInfoController = require('../User/UserInfoController') const async = require('async') @@ -26,7 +25,7 @@ module.exports = ChatController = { sendMessage(req, res, next) { const { project_id } = req.params const { content } = req.body - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) if (user_id == null) { const err = new Error('no logged-in user') return next(err) diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsController.js b/services/web/app/src/Features/Collaborators/CollaboratorsController.js index 9cd8a47e82..31159162a6 100644 --- a/services/web/app/src/Features/Collaborators/CollaboratorsController.js +++ b/services/web/app/src/Features/Collaborators/CollaboratorsController.js @@ -4,7 +4,7 @@ const { ObjectId } = require('mongodb') const CollaboratorsHandler = require('./CollaboratorsHandler') const CollaboratorsGetter = require('./CollaboratorsGetter') const OwnershipTransferHandler = require('./OwnershipTransferHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const TagsHandler = require('../Tags/TagsHandler') const Errors = require('../Errors/Errors') @@ -31,7 +31,7 @@ async function removeUserFromProject(req, res, next) { async function removeSelfFromProject(req, res, next) { const projectId = req.params.Project_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) await _removeUserIdFromProject(projectId, userId) res.sendStatus(204) } @@ -74,7 +74,7 @@ async function setCollaboratorInfo(req, res, next) { } async function transferOwnership(req, res, next) { - const sessionUser = AuthenticationController.getSessionUser(req) + const sessionUser = SessionManager.getSessionUser(req.session) const projectId = req.params.Project_id const toUserId = req.body.user_id try { diff --git a/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js b/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js index a7fbb6fdd3..9a5383f5f7 100644 --- a/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js +++ b/services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js @@ -24,7 +24,7 @@ const Settings = require('@overleaf/settings') const EmailHelper = require('../Helpers/EmailHelper') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const AnalyticsManager = require('../Analytics/AnalyticsManager') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const rateLimiter = require('../../infrastructure/RateLimiter') module.exports = CollaboratorsInviteController = { @@ -99,7 +99,7 @@ module.exports = CollaboratorsInviteController = { inviteToProject(req, res, next) { const projectId = req.params.Project_id let { email } = req.body - const sendingUser = AuthenticationController.getSessionUser(req) + const sendingUser = SessionManager.getSessionUser(req.session) const sendingUserId = sendingUser._id if (email === sendingUser.email) { logger.log( @@ -230,7 +230,7 @@ module.exports = CollaboratorsInviteController = { const projectId = req.params.Project_id const inviteId = req.params.invite_id logger.log({ projectId, inviteId }, 'resending invite') - const sendingUser = AuthenticationController.getSessionUser(req) + const sendingUser = SessionManager.getSessionUser(req.session) return CollaboratorsInviteController._checkRateLimit( sendingUser._id, function (error, underRateLimit) { @@ -270,7 +270,7 @@ module.exports = CollaboratorsInviteController = { return res.render('project/invite/not-valid', { title: 'Invalid Invite' }) } // check if the user is already a member of the project - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) return CollaboratorsGetter.isUserInvitedMemberOfProject( currentUser._id, projectId, @@ -355,7 +355,7 @@ module.exports = CollaboratorsInviteController = { acceptInvite(req, res, next) { const projectId = req.params.Project_id const { token } = req.params - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) logger.log( { projectId, userId: currentUser._id, token }, 'got request to accept invite' diff --git a/services/web/app/src/Features/Compile/CompileController.js b/services/web/app/src/Features/Compile/CompileController.js index 607077eefc..5ff2ef98c0 100644 --- a/services/web/app/src/Features/Compile/CompileController.js +++ b/services/web/app/src/Features/Compile/CompileController.js @@ -21,8 +21,7 @@ const ClsiManager = require('./ClsiManager') const logger = require('logger-sharelatex') const request = require('request') const Settings = require('@overleaf/settings') -const AuthenticationController = require('../Authentication/AuthenticationController') -const UserGetter = require('../User/UserGetter') +const SessionManager = require('../Authentication/SessionManager') const RateLimiter = require('../../infrastructure/RateLimiter') const ClsiCookieManager = require('./ClsiCookieManager')( Settings.apis.clsi != null ? Settings.apis.clsi.backendGroupName : undefined @@ -45,7 +44,7 @@ module.exports = CompileController = { const project_id = req.params.Project_id const isAutoCompile = !!req.query.auto_compile const enablePdfCaching = !!req.query.enable_pdf_caching - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) const options = { isAutoCompile, enablePdfCaching, @@ -111,7 +110,7 @@ module.exports = CompileController = { next = function (error) {} } const project_id = req.params.Project_id - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return CompileManager.stopCompile(project_id, user_id, function (error) { if (error != null) { return next(error) @@ -174,7 +173,7 @@ module.exports = CompileController = { _compileAsUser(req, callback) { // callback with user_id if per-user, undefined otherwise if (!Settings.disablePerUserCompiles) { - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return callback(null, user_id) } else { return callback() @@ -184,7 +183,7 @@ module.exports = CompileController = { _downloadAsUser(req, callback) { // callback with user_id if per-user, undefined otherwise if (!Settings.disablePerUserCompiles) { - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return callback(null, user_id) } else { return callback() diff --git a/services/web/app/src/Features/Contacts/ContactController.js b/services/web/app/src/Features/Contacts/ContactController.js index f77d886495..292578cdae 100644 --- a/services/web/app/src/Features/Contacts/ContactController.js +++ b/services/web/app/src/Features/Contacts/ContactController.js @@ -13,7 +13,7 @@ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let ContactsController -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const ContactManager = require('./ContactManager') const UserGetter = require('../User/UserGetter') const logger = require('logger-sharelatex') @@ -21,7 +21,7 @@ const Modules = require('../../infrastructure/Modules') module.exports = ContactsController = { getContacts(req, res, next) { - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return ContactManager.getContactIds( user_id, { limit: 50 }, diff --git a/services/web/app/src/Features/Contacts/ContactRouter.js b/services/web/app/src/Features/Contacts/ContactRouter.js index e1a73eba8b..2c5236edb0 100644 --- a/services/web/app/src/Features/Contacts/ContactRouter.js +++ b/services/web/app/src/Features/Contacts/ContactRouter.js @@ -1,4 +1,5 @@ const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const ContactController = require('./ContactController') const Settings = require('@overleaf/settings') @@ -7,7 +8,7 @@ function contactsAuthenticationMiddleware() { return AuthenticationController.requireLogin() } else { return (req, res, next) => { - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { next() } else { res.send({ contacts: [] }) diff --git a/services/web/app/src/Features/Editor/EditorHttpController.js b/services/web/app/src/Features/Editor/EditorHttpController.js index ce164539c8..549a69bcac 100644 --- a/services/web/app/src/Features/Editor/EditorHttpController.js +++ b/services/web/app/src/Features/Editor/EditorHttpController.js @@ -9,7 +9,7 @@ const CollaboratorsInviteHandler = require('../Collaborators/CollaboratorsInvite const CollaboratorsHandler = require('../Collaborators/CollaboratorsHandler') const PrivilegeLevels = require('../Authorization/PrivilegeLevels') const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const Errors = require('../Errors/Errors') const HttpErrorHandler = require('../Errors/HttpErrorHandler') const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler') @@ -160,7 +160,7 @@ async function addDoc(req, res, next) { const projectId = req.params.Project_id const { name } = req.body const parentFolderId = req.body.parent_folder_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (!_nameIsAcceptableLength(name)) { return res.sendStatus(400) @@ -188,7 +188,7 @@ async function addFolder(req, res, next) { const projectId = req.params.Project_id const { name } = req.body const parentFolderId = req.body.parent_folder_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (!_nameIsAcceptableLength(name)) { return res.sendStatus(400) } @@ -220,7 +220,7 @@ async function renameEntity(req, res, next) { if (!_nameIsAcceptableLength(name)) { return res.sendStatus(400) } - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) await EditorController.promises.renameEntity( projectId, entityId, @@ -236,7 +236,7 @@ async function moveEntity(req, res, next) { const entityId = req.params.entity_id const entityType = req.params.entity_type const folderId = req.body.folder_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) await EditorController.promises.moveEntity( projectId, entityId, @@ -266,7 +266,7 @@ async function deleteEntity(req, res, next) { const projectId = req.params.Project_id const entityId = req.params.entity_id const entityType = req.params.entity_type - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) await EditorController.promises.deleteEntity( projectId, entityId, diff --git a/services/web/app/src/Features/Errors/ErrorController.js b/services/web/app/src/Features/Errors/ErrorController.js index c9864f49d4..d223abbf3c 100644 --- a/services/web/app/src/Features/Errors/ErrorController.js +++ b/services/web/app/src/Features/Errors/ErrorController.js @@ -1,7 +1,7 @@ let ErrorController const Errors = require('./Errors') const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const SamlLogHandler = require('../SamlLog/SamlLogHandler') const HttpErrorHandler = require('./HttpErrorHandler') @@ -22,7 +22,7 @@ module.exports = ErrorController = { }, handleError(error, req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) // log errors related to SAML flow if (req.session && req.session.saml) { SamlLogHandler.log(req.session.saml.universityId, req.sessionID, { diff --git a/services/web/app/src/Features/Exports/ExportsController.js b/services/web/app/src/Features/Exports/ExportsController.js index 30b8baf2f1..7d31f479aa 100644 --- a/services/web/app/src/Features/Exports/ExportsController.js +++ b/services/web/app/src/Features/Exports/ExportsController.js @@ -11,13 +11,13 @@ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const ExportsHandler = require('./ExportsHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const logger = require('logger-sharelatex') module.exports = { exportProject(req, res, next) { const { project_id, brand_variation_id } = req.params - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) const export_params = { project_id, brand_variation_id, @@ -111,7 +111,7 @@ module.exports = { exportDownload(req, res, next) { const { type, export_id } = req.params - AuthenticationController.getLoggedInUserId(req) + SessionManager.getLoggedInUserId(req.session) return ExportsHandler.fetchDownload( export_id, type, diff --git a/services/web/app/src/Features/History/HistoryController.js b/services/web/app/src/Features/History/HistoryController.js index 9b10c312e8..00f97e33d8 100644 --- a/services/web/app/src/Features/History/HistoryController.js +++ b/services/web/app/src/Features/History/HistoryController.js @@ -4,7 +4,7 @@ const async = require('async') const logger = require('logger-sharelatex') const request = require('request') const settings = require('@overleaf/settings') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const UserGetter = require('../User/UserGetter') const Errors = require('../Errors/Errors') const HistoryManager = require('./HistoryManager') @@ -40,7 +40,7 @@ module.exports = HistoryController = { }, proxyToHistoryApi(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const url = HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url @@ -59,7 +59,7 @@ module.exports = HistoryController = { }, proxyToHistoryApiAndInjectUserDetails(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const url = HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url HistoryController._makeRequest( @@ -111,7 +111,7 @@ module.exports = HistoryController = { restoreFileFromV2(req, res, next) { const { project_id: projectId } = req.params const { version, pathname } = req.body - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) RestoreManager.restoreFileFromV2( userId, projectId, @@ -132,7 +132,7 @@ module.exports = HistoryController = { restoreDocFromDeletedDoc(req, res, next) { const { project_id: projectId, doc_id: docId } = req.params const { name } = req.body - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (name == null) { return res.sendStatus(400) // Malformed request } @@ -175,7 +175,7 @@ module.exports = HistoryController = { createLabel(req, res, next) { const projectId = req.params.Project_id const { comment, version } = req.body - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) HistoryController._makeRequest( { method: 'POST', @@ -268,7 +268,7 @@ module.exports = HistoryController = { deleteLabel(req, res, next) { const { Project_id: projectId, label_id: labelId } = req.params - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) HistoryController._makeRequest( { method: 'DELETE', diff --git a/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js b/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js index dea030e43a..76f065a628 100644 --- a/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js +++ b/services/web/app/src/Features/LinkedFiles/LinkedFilesController.js @@ -13,7 +13,7 @@ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let LinkedFilesController -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const EditorController = require('../Editor/EditorController') const ProjectLocator = require('../Project/ProjectLocator') const Settings = require('@overleaf/settings') @@ -65,7 +65,7 @@ module.exports = LinkedFilesController = { createLinkedFile(req, res, next) { const { project_id } = req.params const { name, provider, data, parent_folder_id } = req.body - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) const Agent = LinkedFilesController._getAgent(provider) if (Agent == null) { @@ -91,7 +91,7 @@ module.exports = LinkedFilesController = { refreshLinkedFile(req, res, next) { const { project_id, file_id } = req.params - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return LinkedFilesHandler.getFileById( project_id, diff --git a/services/web/app/src/Features/Notifications/NotificationsController.js b/services/web/app/src/Features/Notifications/NotificationsController.js index 68d920fcfe..50c43c150e 100644 --- a/services/web/app/src/Features/Notifications/NotificationsController.js +++ b/services/web/app/src/Features/Notifications/NotificationsController.js @@ -1,10 +1,10 @@ const NotificationsHandler = require('./NotificationsHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const _ = require('underscore') module.exports = { getAllUnreadNotifications(req, res) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) NotificationsHandler.getUserNotifications( userId, function (err, unreadNotifications) { @@ -24,7 +24,7 @@ module.exports = { }, markNotificationAsRead(req, res) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { notificationId } = req.params NotificationsHandler.markAsRead(userId, notificationId, () => res.sendStatus(200) diff --git a/services/web/app/src/Features/PasswordReset/PasswordResetController.js b/services/web/app/src/Features/PasswordReset/PasswordResetController.js index 5484e5f98b..a9a9f8119e 100644 --- a/services/web/app/src/Features/PasswordReset/PasswordResetController.js +++ b/services/web/app/src/Features/PasswordReset/PasswordResetController.js @@ -1,5 +1,6 @@ const PasswordResetHandler = require('./PasswordResetHandler') const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const UserGetter = require('../User/UserGetter') const UserUpdater = require('../User/UserUpdater') const UserSessionsManager = require('../User/UserSessionsManager') @@ -16,7 +17,7 @@ async function setNewUserPassword(req, res, next) { passwordResetToken = passwordResetToken.trim() delete req.session.resetToken - const initiatorId = AuthenticationController.getLoggedInUserId(req) + const initiatorId = SessionManager.getLoggedInUserId(req.session) // password reset via tokens can be done while logged in, or not const auditLog = { initiatorId, diff --git a/services/web/app/src/Features/Project/ProjectController.js b/services/web/app/src/Features/Project/ProjectController.js index 663e059a48..47cc292062 100644 --- a/services/web/app/src/Features/Project/ProjectController.js +++ b/services/web/app/src/Features/Project/ProjectController.js @@ -23,7 +23,7 @@ const InactiveProjectManager = require('../InactiveData/InactiveProjectManager') const ProjectUpdateHandler = require('./ProjectUpdateHandler') const ProjectGetter = require('./ProjectGetter') const PrivilegeLevels = require('../Authorization/PrivilegeLevels') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const Sources = require('../Authorization/Sources') const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler') const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') @@ -141,7 +141,7 @@ const ProjectController = { deleteProject(req, res) { const projectId = req.params.Project_id - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const cb = err => { if (err != null) { res.sendStatus(500) @@ -158,7 +158,7 @@ const ProjectController = { archiveProject(req, res, next) { const projectId = req.params.Project_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ProjectDeleter.archiveProject(projectId, userId, function (err) { if (err != null) { @@ -171,7 +171,7 @@ const ProjectController = { unarchiveProject(req, res, next) { const projectId = req.params.Project_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ProjectDeleter.unarchiveProject(projectId, userId, function (err) { if (err != null) { @@ -184,7 +184,7 @@ const ProjectController = { trashProject(req, res, next) { const projectId = req.params.project_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ProjectDeleter.trashProject(projectId, userId, function (err) { if (err != null) { @@ -197,7 +197,7 @@ const ProjectController = { untrashProject(req, res, next) { const projectId = req.params.project_id - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ProjectDeleter.untrashProject(projectId, userId, function (err) { if (err != null) { @@ -246,10 +246,10 @@ const ProjectController = { const projectId = req.params.Project_id const { projectName } = req.body logger.log({ projectId, projectName }, 'cloning project') - if (!AuthenticationController.isUserLoggedIn(req)) { + if (!SessionManager.isUserLoggedIn(req.session)) { return res.send({ redir: '/register' }) } - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) const { first_name: firstName, last_name: lastName, email } = currentUser ProjectDuplicator.duplicate( currentUser, @@ -279,7 +279,7 @@ const ProjectController = { }, newProject(req, res, next) { - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) const { first_name: firstName, last_name: lastName, @@ -330,7 +330,7 @@ const ProjectController = { }, userProjectsJson(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ProjectGetter.findAllUsersProjects( userId, 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens', @@ -377,8 +377,8 @@ const ProjectController = { projectListPage(req, res, next) { const timer = new metrics.Timer('project-list') - const userId = AuthenticationController.getLoggedInUserId(req) - const currentUser = AuthenticationController.getSessionUser(req) + const userId = SessionManager.getLoggedInUserId(req.session) + const currentUser = SessionManager.getSessionUser(req.session) async.parallel( { tags(cb) { @@ -617,9 +617,9 @@ const ProjectController = { } let anonymous, userId, sessionUser - if (AuthenticationController.isUserLoggedIn(req)) { - sessionUser = AuthenticationController.getSessionUser(req) - userId = AuthenticationController.getLoggedInUserId(req) + if (SessionManager.isUserLoggedIn(req.session)) { + sessionUser = SessionManager.getSessionUser(req.session) + userId = SessionManager.getLoggedInUserId(req.session) anonymous = false } else { sessionUser = null diff --git a/services/web/app/src/Features/Referal/ReferalController.js b/services/web/app/src/Features/Referal/ReferalController.js index 5ee754f50b..8ca733305d 100644 --- a/services/web/app/src/Features/Referal/ReferalController.js +++ b/services/web/app/src/Features/Referal/ReferalController.js @@ -1,9 +1,9 @@ const ReferalHandler = require('./ReferalHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') module.exports = { bonus(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) ReferalHandler.getReferedUsers( userId, (err, referedUsers, referedUserCount) => { diff --git a/services/web/app/src/Features/Security/RateLimiterMiddleware.js b/services/web/app/src/Features/Security/RateLimiterMiddleware.js index 01a236976c..bf6f175c45 100644 --- a/services/web/app/src/Features/Security/RateLimiterMiddleware.js +++ b/services/web/app/src/Features/Security/RateLimiterMiddleware.js @@ -1,6 +1,6 @@ const RateLimiter = require('../../infrastructure/RateLimiter') const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const LoginRateLimiter = require('./LoginRateLimiter') const settings = require('@overleaf/settings') @@ -17,7 +17,7 @@ const settings = require('@overleaf/settings') */ function rateLimit(opts) { return function (req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) || req.ip + const userId = SessionManager.getLoggedInUserId(req.session) || req.ip if ( settings.smokeTest && settings.smokeTest.userId && diff --git a/services/web/app/src/Features/Spelling/SpellingController.js b/services/web/app/src/Features/Spelling/SpellingController.js index 9495ccf6df..baf0a29d83 100644 --- a/services/web/app/src/Features/Spelling/SpellingController.js +++ b/services/web/app/src/Features/Spelling/SpellingController.js @@ -1,7 +1,7 @@ const request = require('request') const Settings = require('@overleaf/settings') const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const TEN_SECONDS = 1000 * 10 @@ -28,7 +28,7 @@ module.exports = { } } - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) url = `/user/${userId}${url}` req.headers.Host = Settings.apis.spelling.host return request({ diff --git a/services/web/app/src/Features/StaticPages/HomeController.js b/services/web/app/src/Features/StaticPages/HomeController.js index ac88f9f600..afc7d9638d 100644 --- a/services/web/app/src/Features/StaticPages/HomeController.js +++ b/services/web/app/src/Features/StaticPages/HomeController.js @@ -20,7 +20,7 @@ const Path = require('path') const fs = require('fs') const ErrorController = require('../Errors/ErrorController') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const homepageExists = fs.existsSync( Path.resolve(__dirname + '/../../../views/external/home/v2.pug') @@ -28,7 +28,7 @@ const homepageExists = fs.existsSync( module.exports = HomeController = { index(req, res) { - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { if (req.query.scribtex_path != null) { return res.redirect(`/project?scribtex_path=${req.query.scribtex_path}`) } else { diff --git a/services/web/app/src/Features/Subscription/SubscriptionController.js b/services/web/app/src/Features/Subscription/SubscriptionController.js index 148eb073fd..d13059cfb1 100644 --- a/services/web/app/src/Features/Subscription/SubscriptionController.js +++ b/services/web/app/src/Features/Subscription/SubscriptionController.js @@ -1,4 +1,4 @@ -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const SubscriptionHandler = require('./SubscriptionHandler') const PlansLocator = require('./PlansLocator') const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder') @@ -45,7 +45,7 @@ async function plansPage(req, res) { // get to show the recurly.js page async function paymentPage(req, res) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode) if (!plan) { return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found') @@ -95,7 +95,7 @@ async function paymentPage(req, res) { } async function userSubscriptionPage(req, res) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const results = await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel( user ) @@ -172,7 +172,7 @@ async function userSubscriptionPage(req, res) { } function createSubscription(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const recurlyTokenIds = { billing: req.body.recurly_token_id, threeDSecureActionResult: @@ -224,7 +224,7 @@ function createSubscription(req, res, next) { } function successfulSubscription(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel( user, function (error, { personalSubscription }) { @@ -244,7 +244,7 @@ function successfulSubscription(req, res, next) { } function cancelSubscription(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) logger.log({ user_id: user._id }, 'canceling subscription') SubscriptionHandler.cancelSubscription(user, function (err) { if (err) { @@ -266,7 +266,7 @@ function canceledSubscription(req, res, next) { } function cancelV1Subscription(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) logger.log({ userId }, 'canceling v1 subscription') V1SubscriptionManager.cancelV1Subscription(userId, function (err) { if (err) { @@ -281,7 +281,7 @@ function cancelV1Subscription(req, res, next) { function updateSubscription(req, res, next) { const origin = req && req.query ? req.query.origin : null - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const planCode = req.body.plan_code if (planCode == null) { const err = new Error('plan_code is not defined') @@ -304,7 +304,7 @@ function updateSubscription(req, res, next) { } function cancelPendingSubscriptionChange(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) logger.log({ user_id: user._id }, 'canceling pending subscription change') SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) { if (err) { @@ -322,7 +322,7 @@ function cancelPendingSubscriptionChange(req, res, next) { } function updateAccountEmailAddress(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) RecurlyWrapper.updateAccountEmailAddress( user._id, user.email, @@ -336,7 +336,7 @@ function updateAccountEmailAddress(req, res, next) { } function reactivateSubscription(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) logger.log({ user_id: user._id }, 'reactivating subscription') SubscriptionHandler.reactivateSubscription(user, function (err) { if (err) { @@ -391,7 +391,7 @@ function recurlyCallback(req, res, next) { } function renderUpgradeToAnnualPlanPage(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) LimitationsManager.userHasV2Subscription( user, function (err, hasSubscription, subscription) { @@ -424,7 +424,7 @@ function renderUpgradeToAnnualPlanPage(req, res, next) { } function processUpgradeToAnnualPlan(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const { planName } = req.body const couponCode = Settings.coupon_codes.upgradeToAnnualPromo[planName] const annualPlanName = `${planName}-annual` @@ -449,7 +449,7 @@ function processUpgradeToAnnualPlan(req, res, next) { } async function extendTrial(req, res) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const { subscription, } = await LimitationsManager.promises.userHasV2Subscription(user) diff --git a/services/web/app/src/Features/Subscription/SubscriptionGroupController.js b/services/web/app/src/Features/Subscription/SubscriptionGroupController.js index 033c6531fd..2985acbfbd 100644 --- a/services/web/app/src/Features/Subscription/SubscriptionGroupController.js +++ b/services/web/app/src/Features/Subscription/SubscriptionGroupController.js @@ -15,7 +15,7 @@ const SubscriptionGroupHandler = require('./SubscriptionGroupHandler') const OError = require('@overleaf/o-error') const logger = require('logger-sharelatex') const SubscriptionLocator = require('./SubscriptionLocator') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const _ = require('underscore') const async = require('async') @@ -45,7 +45,7 @@ module.exports = { removeSelfFromGroup(req, res, next) { const subscriptionId = req.query.subscriptionId - const userToRemove_id = AuthenticationController.getLoggedInUserId(req) + const userToRemove_id = SessionManager.getLoggedInUserId(req.session) return SubscriptionLocator.getSubscription( subscriptionId, function (error, subscription) { diff --git a/services/web/app/src/Features/Subscription/TeamInvitesController.js b/services/web/app/src/Features/Subscription/TeamInvitesController.js index 515674d08c..bff6cd6d5c 100644 --- a/services/web/app/src/Features/Subscription/TeamInvitesController.js +++ b/services/web/app/src/Features/Subscription/TeamInvitesController.js @@ -13,14 +13,14 @@ const settings = require('@overleaf/settings') const logger = require('logger-sharelatex') const TeamInvitesHandler = require('./TeamInvitesHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const SubscriptionLocator = require('./SubscriptionLocator') const ErrorController = require('../Errors/ErrorController') const EmailHelper = require('../Helpers/EmailHelper') module.exports = { createInvite(req, res, next) { - const teamManagerId = AuthenticationController.getLoggedInUserId(req) + const teamManagerId = SessionManager.getLoggedInUserId(req.session) const subscription = req.entity const email = EmailHelper.parseEmail(req.body.email) if (email == null) { @@ -63,7 +63,7 @@ module.exports = { viewInvite(req, res, next) { const { token } = req.params - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) return TeamInvitesHandler.getInvite( token, @@ -105,7 +105,7 @@ module.exports = { acceptInvite(req, res, next) { const { token } = req.params - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) return TeamInvitesHandler.acceptInvite( token, @@ -122,7 +122,7 @@ module.exports = { revokeInvite(req, res, next) { const subscription = req.entity const email = EmailHelper.parseEmail(req.params.email) - const teamManagerId = AuthenticationController.getLoggedInUserId(req) + const teamManagerId = SessionManager.getLoggedInUserId(req.session) if (email == null) { return res.sendStatus(400) } diff --git a/services/web/app/src/Features/SystemMessages/SystemMessageController.js b/services/web/app/src/Features/SystemMessages/SystemMessageController.js index 2489347ca7..2c22e97850 100644 --- a/services/web/app/src/Features/SystemMessages/SystemMessageController.js +++ b/services/web/app/src/Features/SystemMessages/SystemMessageController.js @@ -1,10 +1,10 @@ const Settings = require('@overleaf/settings') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const SystemMessageManager = require('./SystemMessageManager') const ProjectController = { getMessages(req, res, next) { - if (!AuthenticationController.isUserLoggedIn(req)) { + if (!SessionManager.isUserLoggedIn(req.session)) { // gracefully handle requests from anonymous users return res.json([]) } diff --git a/services/web/app/src/Features/Tags/TagsController.js b/services/web/app/src/Features/Tags/TagsController.js index 20669c4682..93def0564e 100644 --- a/services/web/app/src/Features/Tags/TagsController.js +++ b/services/web/app/src/Features/Tags/TagsController.js @@ -1,5 +1,5 @@ const TagsHandler = require('./TagsHandler') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const Errors = require('../Errors/Errors') const TagsController = { @@ -21,12 +21,12 @@ const TagsController = { }, getAllTags(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) TagsController._getTags(userId, req, res, next) }, createTag(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { name } = req.body TagsHandler.createTag(userId, name, function (error, tag) { if (error != null) { @@ -37,7 +37,7 @@ const TagsController = { }, addProjectToTag(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { tagId, projectId } = req.params TagsHandler.addProjectToTag(userId, tagId, projectId, function (error) { if (error) { @@ -48,7 +48,7 @@ const TagsController = { }, removeProjectFromTag(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { tagId, projectId } = req.params TagsHandler.removeProjectFromTag( userId, @@ -64,7 +64,7 @@ const TagsController = { }, deleteTag(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { tagId } = req.params TagsHandler.deleteTag(userId, tagId, function (error) { if (error) { @@ -75,7 +75,7 @@ const TagsController = { }, renameTag(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { tagId } = req.params const name = req.body != null ? req.body.name : undefined if (!name) { diff --git a/services/web/app/src/Features/Templates/TemplatesController.js b/services/web/app/src/Features/Templates/TemplatesController.js index 2c74eb28ed..27c7f14fc0 100644 --- a/services/web/app/src/Features/Templates/TemplatesController.js +++ b/services/web/app/src/Features/Templates/TemplatesController.js @@ -13,7 +13,7 @@ */ let TemplatesController const path = require('path') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const TemplatesManager = require('./TemplatesManager') const ProjectHelper = require('../Project/ProjectHelper') const logger = require('logger-sharelatex') @@ -47,7 +47,7 @@ module.exports = TemplatesController = { }, createProjectFromV1Template(req, res, next) { - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return TemplatesManager.createProjectFromV1Template( req.body.brandVariationId, req.body.compiler, diff --git a/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js b/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js index 4409edf800..30741ee823 100644 --- a/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js +++ b/services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js @@ -7,7 +7,7 @@ const logger = require('logger-sharelatex') const Path = require('path') const metrics = require('@overleaf/metrics') const NotificationsBuilder = require('../Notifications/NotificationsBuilder') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const TpdsQueueManager = require('./TpdsQueueManager').promises module.exports = { @@ -111,7 +111,7 @@ module.exports = { }, async getQueues(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) try { res.json(await TpdsQueueManager.getQueues(userId)) } catch (err) { diff --git a/services/web/app/src/Features/TokenAccess/TokenAccessController.js b/services/web/app/src/Features/TokenAccess/TokenAccessController.js index 56b3135e9b..aa0cb6e894 100644 --- a/services/web/app/src/Features/TokenAccess/TokenAccessController.js +++ b/services/web/app/src/Features/TokenAccess/TokenAccessController.js @@ -1,4 +1,5 @@ const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const TokenAccessHandler = require('./TokenAccessHandler') const Errors = require('../Errors/Errors') const logger = require('logger-sharelatex') @@ -213,7 +214,7 @@ async function checkAndGetProjectOrResponseAction( async function grantTokenAccessReadAndWrite(req, res, next) { const { token } = req.params - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (!TokenAccessHandler.isReadAndWriteToken(token)) { return res.sendStatus(400) } @@ -254,7 +255,7 @@ async function grantTokenAccessReadAndWrite(req, res, next) { async function grantTokenAccessReadOnly(req, res, next) { const { token } = req.params - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (!TokenAccessHandler.isReadOnlyToken(token)) { return res.sendStatus(400) } diff --git a/services/web/app/src/Features/Uploads/ProjectUploadController.js b/services/web/app/src/Features/Uploads/ProjectUploadController.js index 8cf6569f36..69de196eb9 100644 --- a/services/web/app/src/Features/Uploads/ProjectUploadController.js +++ b/services/web/app/src/Features/Uploads/ProjectUploadController.js @@ -18,7 +18,7 @@ const fs = require('fs') const Path = require('path') const FileSystemImportManager = require('./FileSystemImportManager') const ProjectUploadManager = require('./ProjectUploadManager') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const Settings = require('@overleaf/settings') const { InvalidZipFileError } = require('./ArchiveErrors') const multer = require('multer') @@ -33,7 +33,7 @@ const upload = multer({ module.exports = ProjectUploadController = { uploadProject(req, res, next) { const timer = new metrics.Timer('project-upload') - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) const { originalname, path } = req.file const name = Path.basename(originalname, '.zip') return ProjectUploadManager.createProjectFromZipArchive( @@ -82,7 +82,7 @@ module.exports = ProjectUploadController = { error: 'invalid_filename', }) } - const user_id = AuthenticationController.getLoggedInUserId(req) + const user_id = SessionManager.getLoggedInUserId(req.session) return FileSystemImportManager.addEntity( user_id, diff --git a/services/web/app/src/Features/User/UserController.js b/services/web/app/src/Features/User/UserController.js index 08df1f9d5e..4be2977624 100644 --- a/services/web/app/src/Features/User/UserController.js +++ b/services/web/app/src/Features/User/UserController.js @@ -7,7 +7,7 @@ const UserRegistrationHandler = require('./UserRegistrationHandler') const logger = require('logger-sharelatex') const metrics = require('@overleaf/metrics') const AuthenticationManager = require('../Authentication/AuthenticationManager') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const Features = require('../../infrastructure/Features') const UserAuditLogHandler = require('./UserAuditLogHandler') const UserSessionsManager = require('./UserSessionsManager') @@ -64,7 +64,7 @@ async function _ensureAffiliation(userId, emailData) { async function changePassword(req, res, next) { metrics.inc('user.password-change') - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const user = await AuthenticationManager.promises.authenticate( { _id: userId }, @@ -119,7 +119,7 @@ async function changePassword(req, res, next) { async function clearSessions(req, res, next) { metrics.inc('user.clear-sessions') - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const user = await UserGetter.promises.getUser(userId, { email: 1 }) const sessions = await UserSessionsManager.promises.getAllUserSessions(user, [ req.sessionID, @@ -165,7 +165,7 @@ async function ensureAffiliationMiddleware(req, res, next) { if (!Features.hasFeature('affiliations') || !req.query.ensureAffiliation) { return next() } - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) try { user = await UserGetter.promises.getUser(userId) } catch (error) { @@ -183,7 +183,7 @@ const UserController = { clearSessions: expressify(clearSessions), tryDeleteUser(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const { password } = req.body if (password == null || password === '') { @@ -256,7 +256,7 @@ const UserController = { }, unsubscribe(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) UserGetter.getUser(userId, (err, user) => { if (err != null) { return next(err) @@ -274,7 +274,7 @@ const UserController = { }, updateUserSettings(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) User.findById(userId, (err, user) => { if (err != null || user == null) { logger.err({ err, userId }, 'problem updaing user settings') @@ -341,7 +341,7 @@ const UserController = { req.externalAuthenticationSystemUsed() ) { // end here, don't update email - AuthenticationController.setInSessionUser(req, { + SessionManager.setInSessionUser(req.session, { first_name: user.first_name, last_name: user.last_name, }) @@ -382,7 +382,7 @@ const UserController = { ) return res.sendStatus(500) } - AuthenticationController.setInSessionUser(req, { + SessionManager.setInSessionUser(req.session, { email: user.email, first_name: user.first_name, last_name: user.last_name, @@ -403,7 +403,7 @@ const UserController = { doLogout(req, cb) { metrics.inc('user.logout') - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) logger.log({ user }, 'logging out') const sessionId = req.sessionID if (typeof req.logout === 'function') { diff --git a/services/web/app/src/Features/User/UserEmailsController.js b/services/web/app/src/Features/User/UserEmailsController.js index 5a88d08ece..cff626fb0d 100644 --- a/services/web/app/src/Features/User/UserEmailsController.js +++ b/services/web/app/src/Features/User/UserEmailsController.js @@ -1,5 +1,5 @@ const logger = require('logger-sharelatex') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const UserGetter = require('./UserGetter') const UserUpdater = require('./UserUpdater') const UserSessionsManager = require('./UserSessionsManager') @@ -24,7 +24,7 @@ async function _sendSecurityAlertEmail(user, email) { } async function add(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(422) @@ -62,7 +62,7 @@ async function add(req, res, next) { } function resendConfirmation(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(422) @@ -88,7 +88,7 @@ function resendConfirmation(req, res, next) { } function sendReconfirmation(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(400) @@ -115,7 +115,7 @@ function sendReconfirmation(req, res, next) { const UserEmailsController = { list(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) UserGetter.getUserFullEmails(userId, function (error, fullEmails) { if (error) { return next(error) @@ -127,7 +127,7 @@ const UserEmailsController = { add: expressify(add), remove(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(422) @@ -142,7 +142,7 @@ const UserEmailsController = { }, setDefault(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(422) @@ -161,8 +161,8 @@ const UserEmailsController = { if (err) { return UserEmailsController._handleEmailError(err, req, res, next) } - AuthenticationController.setInSessionUser(req, { email: email }) - const user = AuthenticationController.getSessionUser(req) + SessionManager.setInSessionUser(req.session, { email: email }) + const user = SessionManager.getSessionUser(req.session) UserSessionsManager.revokeAllUserSessions( user, [req.sessionID], @@ -180,7 +180,7 @@ const UserEmailsController = { }, endorse(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const email = EmailHelper.parseEmail(req.body.email) if (!email) { return res.sendStatus(422) diff --git a/services/web/app/src/Features/User/UserInfoController.js b/services/web/app/src/Features/User/UserInfoController.js index a1142872ed..8de15065c7 100644 --- a/services/web/app/src/Features/User/UserInfoController.js +++ b/services/web/app/src/Features/User/UserInfoController.js @@ -1,11 +1,11 @@ let UserController const UserGetter = require('./UserGetter') -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const { ObjectId } = require('mongodb') module.exports = UserController = { getLoggedInUsersPersonalInfo(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (!userId) { return next(new Error('User is not logged in')) } diff --git a/services/web/app/src/Features/User/UserPagesController.js b/services/web/app/src/Features/User/UserPagesController.js index d775b58ef9..975f13ac1b 100644 --- a/services/web/app/src/Features/User/UserPagesController.js +++ b/services/web/app/src/Features/User/UserPagesController.js @@ -4,6 +4,7 @@ const UserSessionsManager = require('./UserSessionsManager') const logger = require('logger-sharelatex') const Settings = require('@overleaf/settings') const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const _ = require('lodash') const UserPagesController = { @@ -63,7 +64,7 @@ const UserPagesController = { }, settingsPage(req, res, next) { - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) const reconfirmationRemoveEmail = req.query.remove // SSO const ssoError = req.session.ssoError @@ -134,7 +135,7 @@ const UserPagesController = { }, sessionsPage(req, res, next) { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) logger.log({ userId: user._id }, 'loading sessions page') UserSessionsManager.getAllUserSessions( user, diff --git a/services/web/app/src/Features/UserMembership/UserMembershipController.js b/services/web/app/src/Features/UserMembership/UserMembershipController.js index 8495b91b06..050b235509 100644 --- a/services/web/app/src/Features/UserMembership/UserMembershipController.js +++ b/services/web/app/src/Features/UserMembership/UserMembershipController.js @@ -10,7 +10,7 @@ * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ -const AuthenticationController = require('../Authentication/AuthenticationController') +const SessionManager = require('../Authentication/SessionManager') const UserMembershipHandler = require('./UserMembershipHandler') const Errors = require('../Errors/Errors') const EmailHelper = require('../Helpers/EmailHelper') @@ -104,7 +104,7 @@ module.exports = { return next(new Errors.NotFoundError('Cannot remove users from entity')) } - const loggedInUserId = AuthenticationController.getLoggedInUserId(req) + const loggedInUserId = SessionManager.getLoggedInUserId(req.session) if (loggedInUserId === userId) { return res.status(400).json({ error: { diff --git a/services/web/app/src/infrastructure/ExpressLocals.js b/services/web/app/src/infrastructure/ExpressLocals.js index 58cd558e1c..c28d265c26 100644 --- a/services/web/app/src/infrastructure/ExpressLocals.js +++ b/services/web/app/src/infrastructure/ExpressLocals.js @@ -10,7 +10,7 @@ const pug = require('pug-runtime') const IS_DEV_ENV = ['development', 'test'].includes(process.env.NODE_ENV) const Features = require('./Features') -const AuthenticationController = require('../Features/Authentication/AuthenticationController') +const SessionManager = require('../Features/Authentication/SessionManager') const PackageVersions = require('./PackageVersions') const Modules = require('./Modules') const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution') @@ -62,7 +62,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { const cdnAvailable = Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked - const userId = AuthenticationController.getLoggedInUserId(req) + const userId = SessionManager.getLoggedInUserId(req.session) if (cdnBlocked && req.session.cdnBlocked == null) { logger.log( { user_id: userId, ip: req != null ? req.ip : undefined }, @@ -222,7 +222,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { webRouter.use(function (req, res, next) { res.locals.getUserEmail = function () { - const user = AuthenticationController.getSessionUser(req) + const user = SessionManager.getSessionUser(req.session) const email = (user != null ? user.email : undefined) || '' return email } @@ -237,7 +237,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { webRouter.use(function (req, res, next) { res.locals.buildReferalUrl = function (referalMedium) { let url = Settings.siteUrl - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) if ( currentUser != null && (currentUser != null ? currentUser.referal_id : undefined) != null @@ -247,7 +247,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { return url } res.locals.getReferalId = function () { - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) if ( currentUser != null && (currentUser != null ? currentUser.referal_id : undefined) != null @@ -277,7 +277,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { }) webRouter.use(function (req, res, next) { - const currentUser = AuthenticationController.getSessionUser(req) + const currentUser = SessionManager.getSessionUser(req.session) if (currentUser != null) { res.locals.user = { email: currentUser.email, @@ -290,9 +290,8 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) { webRouter.use(function (req, res, next) { res.locals.getLoggedInUserId = () => - AuthenticationController.getLoggedInUserId(req) - res.locals.getSessionUser = () => - AuthenticationController.getSessionUser(req) + SessionManager.getLoggedInUserId(req.session) + res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session) next() }) diff --git a/services/web/app/src/infrastructure/Server.js b/services/web/app/src/infrastructure/Server.js index 6c9ece4216..7e30f77237 100644 --- a/services/web/app/src/infrastructure/Server.js +++ b/services/web/app/src/infrastructure/Server.js @@ -37,6 +37,7 @@ const ErrorController = require('../Features/Errors/ErrorController') const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler') const UserSessionsManager = require('../Features/User/UserSessionsManager') const AuthenticationController = require('../Features/Authentication/AuthenticationController') +const SessionManager = require('../Features/Authentication/SessionManager') const STATIC_CACHE_AGE = Settings.cacheStaticAssets ? oneDayInMilliseconds * 365 @@ -164,9 +165,9 @@ webRouter.use(translations.setLangBasedOnDomainMiddleware) webRouter.use(function (req, res, next) { if (!req.session.noSessionCallback) { req.session.touch() - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { UserSessionsManager.touch( - AuthenticationController.getSessionUser(req), + SessionManager.getSessionUser(req.session), err => { if (err) { logger.err({ err }, 'error extending user session') @@ -187,8 +188,8 @@ webRouter.use(function (req, res, next) { if (Settings.siteIsOpen) { next() } else if ( - AuthenticationController.getSessionUser(req) && - AuthenticationController.getSessionUser(req).isAdmin + SessionManager.getSessionUser(req.session) && + SessionManager.getSessionUser(req.session).isAdmin ) { next() } else { @@ -211,7 +212,7 @@ webRouter.use(AuthenticationController.validateAdmin) // add security headers using Helmet const noCacheMiddleware = require('nocache')() webRouter.use(function (req, res, next) { - const isLoggedIn = AuthenticationController.isUserLoggedIn(req) + const isLoggedIn = SessionManager.isUserLoggedIn(req.session) const isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$') if (isLoggedIn || isProjectPage) { noCacheMiddleware(req, res, next) diff --git a/services/web/app/src/router.js b/services/web/app/src/router.js index 0e5657c85e..88c4f423a9 100644 --- a/services/web/app/src/router.js +++ b/services/web/app/src/router.js @@ -11,6 +11,7 @@ const UploadsRouter = require('./Features/Uploads/UploadsRouter') const metrics = require('@overleaf/metrics') const ReferalController = require('./Features/Referal/ReferalController') const AuthenticationController = require('./Features/Authentication/AuthenticationController') +const SessionManager = require('./Features/Authentication/SessionManager') const TagsController = require('./Features/Tags/TagsController') const NotificationsController = require('./Features/Notifications/NotificationsController') const CollaboratorsRouter = require('./Features/Collaborators/CollaboratorsRouter') @@ -923,7 +924,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) { webRouter.get('/chrome', function (req, res, next) { // Match v1 behaviour - this is used for a Chrome web app - if (AuthenticationController.isUserLoggedIn(req)) { + if (SessionManager.isUserLoggedIn(req.session)) { res.redirect('/project') } else { res.redirect('/register') diff --git a/services/web/modules/launchpad/app/src/LaunchpadController.js b/services/web/modules/launchpad/app/src/LaunchpadController.js index 522709cd05..008c252765 100644 --- a/services/web/modules/launchpad/app/src/LaunchpadController.js +++ b/services/web/modules/launchpad/app/src/LaunchpadController.js @@ -24,6 +24,7 @@ const _ = require('underscore') const UserGetter = require('../../../../app/src/Features/User/UserGetter') const { User } = require('../../../../app/src/models/User') const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController') +const SessionManager = require('../../../../app/src/Features/Authentication/SessionManager') module.exports = LaunchpadController = { _getAuthMethod() { @@ -39,7 +40,7 @@ module.exports = LaunchpadController = { launchpadPage(req, res, next) { // TODO: check if we're using external auth? // * how does all this work with ldap and saml? - const sessionUser = AuthenticationController.getSessionUser(req) + const sessionUser = SessionManager.getSessionUser(req.session) const authMethod = LaunchpadController._getAuthMethod() return LaunchpadController._atLeastOneAdminExists(function ( err, diff --git a/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js b/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js index f854812970..632c8788fa 100644 --- a/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js +++ b/services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js @@ -38,6 +38,7 @@ describe('LaunchpadController', function () { '../../../../app/src/Features/User/UserGetter': (this.UserGetter = {}), '../../../../app/src/models/User': { User: this.User }, '../../../../app/src/Features/Authentication/AuthenticationController': (this.AuthenticationController = {}), + '../../../../app/src/Features/Authentication/SessionManager': (this.SessionManager = {}), }, }) @@ -74,9 +75,7 @@ describe('LaunchpadController', function () { describe('when the user is not logged in', function () { beforeEach(function () { - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(null) + this.SessionManager.getSessionUser = sinon.stub().returns(null) return (this.res.render = sinon.stub()) }) @@ -134,9 +133,7 @@ describe('LaunchpadController', function () { _id: 'abcd', email: 'abcd@example.com', } - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.user) + this.SessionManager.getSessionUser = sinon.stub().returns(this.user) this._atLeastOneAdminExists.callsArgWith(0, null, true) this.res.render = sinon.stub() return (this.res.redirect = sinon.stub()) diff --git a/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js b/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js index cdba614336..c21a4bb469 100644 --- a/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js +++ b/services/web/test/unit/src/Analytics/AnalyticsControllerTests.js @@ -8,7 +8,7 @@ const sinon = require('sinon') describe('AnalyticsController', function () { beforeEach(function () { - this.AuthenticationController = { getLoggedInUserId: sinon.stub() } + this.SessionManager = { getLoggedInUserId: sinon.stub() } this.AnalyticsManager = { updateEditingSession: sinon.stub(), @@ -22,8 +22,7 @@ describe('AnalyticsController', function () { this.controller = SandboxedModule.require(modulePath, { requires: { './AnalyticsManager': this.AnalyticsManager, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../../infrastructure/Features': this.Features, '../../infrastructure/GeoIpLookup': (this.GeoIpLookup = { getDetails: sinon.stub(), @@ -50,7 +49,7 @@ describe('AnalyticsController', function () { }) it('delegates to the AnalyticsManager', function (done) { - this.AuthenticationController.getLoggedInUserId.returns('1234') + this.SessionManager.getLoggedInUserId.returns('1234') this.controller.updateEditingSession(this.req, this.res) this.AnalyticsManager.updateEditingSession @@ -73,7 +72,7 @@ describe('AnalyticsController', function () { }) it('should use the user_id', function (done) { - this.AuthenticationController.getLoggedInUserId.returns('1234') + this.SessionManager.getLoggedInUserId.returns('1234') this.controller.recordEvent(this.req, this.res) this.AnalyticsManager.recordEvent .calledWith('1234', this.req.params.event, this.req.body) diff --git a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js index f4f35098da..834d0ba725 100644 --- a/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js +++ b/services/web/test/unit/src/Authentication/AuthenticationControllerTests.js @@ -15,6 +15,20 @@ describe('AuthenticationController', function () { this.httpAuthUsers = { 'valid-test-user': Math.random().toString(16).slice(2), } + this.user = { + _id: ObjectId(), + email: (this.email = 'USER@example.com'), + first_name: 'bob', + last_name: 'brown', + referal_id: 1234, + isAdmin: false, + } + this.password = 'banana' + this.req = new MockRequest() + this.res = new MockResponse() + this.callback = sinon.stub() + this.next = sinon.stub() + this.AuthenticationController = SandboxedModule.require(modulePath, { requires: { '../User/UserAuditLogHandler': (this.UserAuditLogHandler = { @@ -72,25 +86,16 @@ describe('AuthenticationController', function () { '../Helpers/UrlHelper': (this.UrlHelper = { getSafeRedirectPath: sinon.stub(), }), + './SessionManager': (this.SessionManager = { + isUserLoggedIn: sinon.stub().returns(true), + getSessionUser: sinon.stub().returns(this.user), + }), }, }) this.UrlHelper.getSafeRedirectPath .withArgs('https://evil.com') .returns(undefined) this.UrlHelper.getSafeRedirectPath.returnsArg(0) - this.user = { - _id: ObjectId(), - email: (this.email = 'USER@example.com'), - first_name: 'bob', - last_name: 'brown', - referal_id: 1234, - isAdmin: false, - } - this.password = 'banana' - this.req = new MockRequest() - this.res = new MockResponse() - this.callback = sinon.stub() - this.next = sinon.stub() }) afterEach(function () { @@ -116,119 +121,53 @@ describe('AuthenticationController', function () { it('should skip when adminDomains are not configured', function (done) { this.Settings.adminDomains = [] - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.normalUser) + this.SessionManager.getSessionUser = sinon.stub().returns(this.normalUser) this.AuthenticationController.validateAdmin(this.req, this.res, err => { - this.AuthenticationController.getSessionUser.called.should.equal(false) + this.SessionManager.getSessionUser.called.should.equal(false) expect(err).to.not.exist done() }) }) it('should skip non-admin user', function (done) { - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.normalUser) + this.SessionManager.getSessionUser = sinon.stub().returns(this.normalUser) this.AuthenticationController.validateAdmin(this.req, this.res, err => { - this.AuthenticationController.getSessionUser.called.should.equal(true) + this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.not.exist done() }) }) it('should permit an admin with the right doman', function (done) { - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.goodAdmin) + this.SessionManager.getSessionUser = sinon.stub().returns(this.goodAdmin) this.AuthenticationController.validateAdmin(this.req, this.res, err => { - this.AuthenticationController.getSessionUser.called.should.equal(true) + this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.not.exist done() }) }) it('should block an admin with a missing email', function (done) { - this.AuthenticationController.getSessionUser = sinon + this.SessionManager.getSessionUser = sinon .stub() .returns({ isAdmin: true }) this.AuthenticationController.validateAdmin(this.req, this.res, err => { - this.AuthenticationController.getSessionUser.called.should.equal(true) + this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.exist done() }) }) it('should block an admin with a bad domain', function (done) { - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.badAdmin) + this.SessionManager.getSessionUser = sinon.stub().returns(this.badAdmin) this.AuthenticationController.validateAdmin(this.req, this.res, err => { - this.AuthenticationController.getSessionUser.called.should.equal(true) + this.SessionManager.getSessionUser.called.should.equal(true) expect(err).to.exist done() }) }) }) - describe('isUserLoggedIn', function () { - beforeEach(function () { - this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId') - }) - - afterEach(function () { - this.stub.restore() - }) - - it('should do the right thing in all cases', function () { - this.AuthenticationController.getLoggedInUserId.returns('some_id') - expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal( - true - ) - this.AuthenticationController.getLoggedInUserId.returns(null) - expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal( - false - ) - this.AuthenticationController.getLoggedInUserId.returns(false) - expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal( - false - ) - this.AuthenticationController.getLoggedInUserId.returns(undefined) - expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal( - false - ) - }) - }) - - describe('setInSessionUser', function () { - beforeEach(function () { - this.user = { - _id: 'id', - first_name: 'a', - last_name: 'b', - email: 'c', - } - this.AuthenticationController.getSessionUser = sinon - .stub() - .returns(this.user) - }) - - it('should update the right properties', function () { - this.AuthenticationController.setInSessionUser(this.req, { - first_name: 'new_first_name', - email: 'new_email', - }) - const expectedUser = { - _id: 'id', - first_name: 'new_first_name', - last_name: 'b', - email: 'new_email', - } - expect(this.user).to.deep.equal(expectedUser) - expect(this.user).to.deep.equal(expectedUser) - }) - }) - describe('passportLogin', function () { beforeEach(function () { this.info = null @@ -444,49 +383,6 @@ describe('AuthenticationController', function () { }) }) - describe('getLoggedInUserId', function () { - beforeEach(function () { - this.req = { session: {} } - }) - - it('should return the user id from the session', function () { - this.user_id = '2134' - this.req.session.user = { _id: this.user_id } - const result = this.AuthenticationController.getLoggedInUserId(this.req) - expect(result).to.equal(this.user_id) - }) - - it('should return user for passport session', function () { - this.user_id = '2134' - this.req.session = { - passport: { - user: { - _id: this.user_id, - }, - }, - } - const result = this.AuthenticationController.getLoggedInUserId(this.req) - expect(result).to.equal(this.user_id) - }) - - it('should return null if there is no user on the session', function () { - const result = this.AuthenticationController.getLoggedInUserId(this.req) - expect(result).to.equal(null) - }) - - it('should return null if there is no session', function () { - this.req = {} - const result = this.AuthenticationController.getLoggedInUserId(this.req) - expect(result).to.equal(null) - }) - - it('should return null if there is no req', function () { - this.req = {} - const result = this.AuthenticationController.getLoggedInUserId(this.req) - expect(result).to.equal(null) - }) - }) - describe('requireLogin', function () { beforeEach(function () { this.user = { @@ -517,6 +413,7 @@ describe('AuthenticationController', function () { this.req.session = {} this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() this.req.query = {} + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) @@ -712,6 +609,7 @@ describe('AuthenticationController', function () { describe('with no login credentials', function () { beforeEach(function () { this.req.session = {} + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.AuthenticationController.requireGlobalLogin( this.req, this.res, @@ -815,6 +713,7 @@ describe('AuthenticationController', function () { describe('they have come directly to the url', function () { beforeEach(function () { this.req.query = {} + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) @@ -831,6 +730,7 @@ describe('AuthenticationController', function () { describe('they have come via a templates link', function () { beforeEach(function () { this.req.query.zipUrl = 'something' + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) @@ -847,6 +747,7 @@ describe('AuthenticationController', function () { describe('they have been invited to a project', function () { beforeEach(function () { this.req.query.project_name = 'something' + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) this.middleware(this.req, this.res, this.next) }) diff --git a/services/web/test/unit/src/Authentication/SessionManagerTests.js b/services/web/test/unit/src/Authentication/SessionManagerTests.js new file mode 100644 index 0000000000..44926c59ce --- /dev/null +++ b/services/web/test/unit/src/Authentication/SessionManagerTests.js @@ -0,0 +1,114 @@ +const sinon = require('sinon') +const { expect } = require('chai') +const modulePath = + '../../../../app/src/Features/Authentication/SessionManager.js' +const SandboxedModule = require('sandboxed-module') +const tk = require('timekeeper') +const { ObjectId } = require('mongodb') + +describe('SessionManager', function () { + beforeEach(function () { + this.UserModel = { findOne: sinon.stub() } + this.SessionManager = SandboxedModule.require(modulePath, { + requires: {}, + }) + this.user = { + _id: ObjectId(), + email: (this.email = 'USER@example.com'), + first_name: 'bob', + last_name: 'brown', + referal_id: 1234, + isAdmin: false, + } + this.session = sinon.stub() + }) + + afterEach(function () { + tk.reset() + }) + + describe('isUserLoggedIn', function () { + beforeEach(function () { + this.stub = sinon.stub(this.SessionManager, 'getLoggedInUserId') + }) + + afterEach(function () { + this.stub.restore() + }) + + it('should do the right thing in all cases', function () { + this.SessionManager.getLoggedInUserId.returns('some_id') + expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(true) + this.SessionManager.getLoggedInUserId.returns(null) + expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false) + this.SessionManager.getLoggedInUserId.returns(false) + expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false) + this.SessionManager.getLoggedInUserId.returns(undefined) + expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false) + }) + }) + + describe('setInSessionUser', function () { + beforeEach(function () { + this.user = { + _id: 'id', + first_name: 'a', + last_name: 'b', + email: 'c', + } + this.SessionManager.getSessionUser = sinon.stub().returns(this.user) + }) + + it('should update the right properties', function () { + this.SessionManager.setInSessionUser(this.session, { + first_name: 'new_first_name', + email: 'new_email', + }) + const expectedUser = { + _id: 'id', + first_name: 'new_first_name', + last_name: 'b', + email: 'new_email', + } + expect(this.user).to.deep.equal(expectedUser) + expect(this.user).to.deep.equal(expectedUser) + }) + }) + + describe('getLoggedInUserId', function () { + beforeEach(function () { + this.req = { session: {} } + }) + + it('should return the user id from the session', function () { + this.user_id = '2134' + this.session.user = { _id: this.user_id } + const result = this.SessionManager.getLoggedInUserId(this.session) + expect(result).to.equal(this.user_id) + }) + + it('should return user for passport session', function () { + this.user_id = '2134' + this.session = { + passport: { + user: { + _id: this.user_id, + }, + }, + } + const result = this.SessionManager.getLoggedInUserId(this.session) + expect(result).to.equal(this.user_id) + }) + + it('should return null if there is no user on the session', function () { + this.session = {} + const result = this.SessionManager.getLoggedInUserId(this.session) + expect(result).to.equal(null) + }) + + it('should return null if there is no session', function () { + const result = this.SessionManager.getLoggedInUserId(undefined) + expect(result).to.equal(null) + }) + }) +}) diff --git a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js index 765b8d3344..f0d1b9631c 100644 --- a/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js +++ b/services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js @@ -11,7 +11,8 @@ describe('AuthorizationMiddleware', function () { this.userId = 'user-id-123' this.project_id = 'project-id-123' this.token = 'some-token' - this.AuthenticationController = { + this.AuthenticationController = {} + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.userId), isUserLoggedIn: sinon.stub().returns(true), } @@ -35,6 +36,7 @@ describe('AuthorizationMiddleware', function () { '../Errors/HttpErrorHandler': this.HttpErrorHandler, '../Authentication/AuthenticationController': this .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler, }, }) @@ -49,9 +51,7 @@ describe('AuthorizationMiddleware', function () { }) it('should get the user from session', function (done) { - this.AuthenticationController.getLoggedInUserId = sinon - .stub() - .returns('1234') + this.SessionManager.getLoggedInUserId = sinon.stub().returns('1234') this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => { expect(err).to.not.exist expect(userId).to.equal('1234') @@ -60,9 +60,7 @@ describe('AuthorizationMiddleware', function () { }) it('should get oauth_user from request', function (done) { - this.AuthenticationController.getLoggedInUserId = sinon - .stub() - .returns(null) + this.SessionManager.getLoggedInUserId = sinon.stub().returns(null) this.req.oauth_user = { _id: '5678' } this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => { expect(err).to.not.exist @@ -72,9 +70,7 @@ describe('AuthorizationMiddleware', function () { }) it('should fall back to null', function (done) { - this.AuthenticationController.getLoggedInUserId = sinon - .stub() - .returns(null) + this.SessionManager.getLoggedInUserId = sinon.stub().returns(null) this.req.oauth_user = undefined this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => { expect(err).to.not.exist @@ -117,7 +113,7 @@ describe('AuthorizationMiddleware', function () { describe('with logged in user', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(this.userId) + this.SessionManager.getLoggedInUserId.returns(this.userId) }) describe('when user has permission', function () { @@ -161,7 +157,7 @@ describe('AuthorizationMiddleware', function () { describe('with anonymous user', function () { describe('when user has permission', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager[managerMethod] .withArgs(null, this.project_id, this.token) .yields(null, true) @@ -179,7 +175,7 @@ describe('AuthorizationMiddleware', function () { describe("when user doesn't have permission", function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager[managerMethod] .withArgs(null, this.project_id, this.token) .yields(null, false) @@ -244,7 +240,7 @@ describe('AuthorizationMiddleware', function () { describe('with logged in user', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(this.userId) + this.SessionManager.getLoggedInUserId.returns(this.userId) }) describe('when user has permission', function () { @@ -284,7 +280,7 @@ describe('AuthorizationMiddleware', function () { describe('with anonymous user', function () { describe('when user has permission', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.canUserAdminProject .withArgs(null, this.project_id, this.token) .yields(null, true) @@ -302,7 +298,7 @@ describe('AuthorizationMiddleware', function () { describe("when user doesn't have permission", function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.canUserAdminProject .withArgs(null, this.project_id, this.token) .yields(null, false) @@ -345,7 +341,7 @@ describe('AuthorizationMiddleware', function () { describe('with logged in user', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(this.userId) + this.SessionManager.getLoggedInUserId.returns(this.userId) }) describe('when user has permission', function () { @@ -389,7 +385,7 @@ describe('AuthorizationMiddleware', function () { describe('with anonymous user', function () { describe('when user has permission', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.isUserSiteAdmin .withArgs(null) .yields(null, true) @@ -407,7 +403,7 @@ describe('AuthorizationMiddleware', function () { describe("when user doesn't have permission", function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.isUserSiteAdmin .withArgs(null) .yields(null, false) @@ -486,7 +482,7 @@ describe('AuthorizationMiddleware', function () { describe('with logged in user', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(this.userId) + this.SessionManager.getLoggedInUserId.returns(this.userId) }) describe('when user has permission to access all projects', function () { @@ -537,7 +533,7 @@ describe('AuthorizationMiddleware', function () { describe('when user has permission', function () { describe('when user has permission to access all projects', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.canUserReadProject .withArgs(null, 'project1', this.token) .yields(null, true) @@ -558,7 +554,7 @@ describe('AuthorizationMiddleware', function () { describe("when user doesn't have permission to access one of the projects", function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId.returns(null) + this.SessionManager.getLoggedInUserId.returns(null) this.AuthorizationManager.canUserReadProject .withArgs(null, 'project1', this.token) .yields(null, true) diff --git a/services/web/test/unit/src/Chat/ChatControllerTests.js b/services/web/test/unit/src/Chat/ChatControllerTests.js index e599e7b698..e06f04fc5a 100644 --- a/services/web/test/unit/src/Chat/ChatControllerTests.js +++ b/services/web/test/unit/src/Chat/ChatControllerTests.js @@ -28,7 +28,7 @@ describe('ChatController', function () { this.settings = {} this.ChatApiHandler = {} this.EditorRealTimeController = { emitToRoom: sinon.stub() } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user_id), } this.ChatController = SandboxedModule.require(modulePath, { @@ -36,8 +36,7 @@ describe('ChatController', function () { '@overleaf/settings': this.settings, './ChatApiHandler': this.ChatApiHandler, '../Editor/EditorRealTimeController': this.EditorRealTimeController, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../User/UserInfoManager': (this.UserInfoManager = {}), '../User/UserInfoController': (this.UserInfoController = {}), }, diff --git a/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js b/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js index 2ba1954efc..ad56d6495a 100644 --- a/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js +++ b/services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js @@ -41,7 +41,7 @@ describe('CollaboratorsController', function () { removeProjectFromAllTags: sinon.stub().resolves(), }, } - this.AuthenticationController = { + this.SessionManager = { getSessionUser: sinon.stub().returns(this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), } @@ -60,8 +60,7 @@ describe('CollaboratorsController', function () { '../Editor/EditorRealTimeController': this.EditorRealTimeController, '../../Features/Errors/HttpErrorHandler': this.HttpErrorHandler, '../Tags/TagsHandler': this.TagsHandler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, }, }) }) diff --git a/services/web/test/unit/src/Compile/CompileControllerTests.js b/services/web/test/unit/src/Compile/CompileControllerTests.js index 7cc39a19b4..416bd9d721 100644 --- a/services/web/test/unit/src/Compile/CompileControllerTests.js +++ b/services/web/test/unit/src/Compile/CompileControllerTests.js @@ -51,7 +51,7 @@ describe('CompileController', function () { this.ClsiCookieManager = { getCookieJar: sinon.stub().callsArgWith(1, null, this.jar), } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user), getLoggedInUserId: sinon.stub().returns(this.user_id), getSessionUser: sinon.stub().returns(this.user), @@ -66,8 +66,7 @@ describe('CompileController', function () { './CompileManager': this.CompileManager, '../User/UserGetter': this.UserGetter, './ClsiManager': this.ClsiManager, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../../infrastructure/RateLimiter': this.RateLimiter, './ClsiCookieManager': () => this.ClsiCookieManager, }, @@ -98,8 +97,8 @@ describe('CompileController', function () { }) it('should look up the user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) diff --git a/services/web/test/unit/src/Contact/ContactControllerTests.js b/services/web/test/unit/src/Contact/ContactControllerTests.js index 9ddf5d1d77..2af38b0dd8 100644 --- a/services/web/test/unit/src/Contact/ContactControllerTests.js +++ b/services/web/test/unit/src/Contact/ContactControllerTests.js @@ -18,15 +18,13 @@ const SandboxedModule = require('sandboxed-module') describe('ContactController', function () { beforeEach(function () { - this.AuthenticationController = { getLoggedInUserId: sinon.stub() } + this.SessionManager = { getLoggedInUserId: sinon.stub() } this.ContactController = SandboxedModule.require(modulePath, { requires: { '../User/UserGetter': (this.UserGetter = {}), './ContactManager': (this.ContactManager = {}), - '../Authentication/AuthenticationController': (this.AuthenticationController = {}), + '../Authentication/SessionManager': (this.SessionManager = {}), '../../infrastructure/Modules': (this.Modules = { hooks: {} }), - '../Authentication/AuthenticationController': this - .AuthenticationController, }, }) @@ -65,9 +63,7 @@ describe('ContactController', function () { unsued: 'foo', }, ] - this.AuthenticationController.getLoggedInUserId = sinon - .stub() - .returns(this.user_id) + this.SessionManager.getLoggedInUserId = sinon.stub().returns(this.user_id) this.ContactManager.getContactIds = sinon .stub() .callsArgWith(2, null, this.contact_ids) @@ -80,8 +76,8 @@ describe('ContactController', function () { }) it('should look up the logged in user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) diff --git a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js index 43af5de144..7e3dddc89e 100644 --- a/services/web/test/unit/src/Editor/EditorHttpControllerTests.js +++ b/services/web/test/unit/src/Editor/EditorHttpControllerTests.js @@ -111,7 +111,7 @@ describe('EditorHttpController', function () { getRequestToken: sinon.stub().returns(this.token), protectTokens: sinon.stub(), } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user._id), } this.ProjectEntityUpdateHandler = { @@ -141,8 +141,7 @@ describe('EditorHttpController', function () { '../Collaborators/CollaboratorsInviteHandler': this .CollaboratorsInviteHandler, '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../../infrastructure/FileWriter': this.FileWriter, '../Project/ProjectEntityUpdateHandler': this .ProjectEntityUpdateHandler, diff --git a/services/web/test/unit/src/History/HistoryControllerTests.js b/services/web/test/unit/src/History/HistoryControllerTests.js index 5e0cccff0f..0ffc3f1fb6 100644 --- a/services/web/test/unit/src/History/HistoryControllerTests.js +++ b/services/web/test/unit/src/History/HistoryControllerTests.js @@ -20,15 +20,14 @@ describe('HistoryController', function () { beforeEach(function () { this.callback = sinon.stub() this.user_id = 'user-id-123' - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user_id), } this.HistoryController = SandboxedModule.require(modulePath, { requires: { request: (this.request = sinon.stub()), '@overleaf/settings': (this.settings = {}), - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, './HistoryManager': (this.HistoryManager = {}), '../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = {}), '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}), @@ -117,8 +116,8 @@ describe('HistoryController', function () { }) it('should get the user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) @@ -150,8 +149,8 @@ describe('HistoryController', function () { }) it('should get the user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) @@ -209,8 +208,8 @@ describe('HistoryController', function () { }) it('should get the user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) @@ -249,8 +248,8 @@ describe('HistoryController', function () { }) it('should get the user id', function () { - return this.AuthenticationController.getLoggedInUserId - .calledWith(this.req) + return this.SessionManager.getLoggedInUserId + .calledWith(this.req.session) .should.equal(true) }) diff --git a/services/web/test/unit/src/Project/ProjectControllerTests.js b/services/web/test/unit/src/Project/ProjectControllerTests.js index 55c66d9240..3fec7ffbbb 100644 --- a/services/web/test/unit/src/Project/ProjectControllerTests.js +++ b/services/web/test/unit/src/Project/ProjectControllerTests.js @@ -76,7 +76,7 @@ describe('ProjectController', function () { isArchivedOrTrashed: sinon.stub(), getAllowedImagesForUser: sinon.stub().returns([]), } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.user), @@ -153,8 +153,7 @@ describe('ProjectController', function () { './ProjectUpdateHandler': this.ProjectUpdateHandler, './ProjectGetter': this.ProjectGetter, './ProjectDetailsHandler': this.ProjectDetailsHandler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler, '../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter, './ProjectEntityHandler': this.ProjectEntityHandler, @@ -1220,9 +1219,7 @@ describe('ProjectController', function () { function tagAnonymous() { beforeEach(function () { - this.AuthenticationController.isUserLoggedIn = sinon - .stub() - .returns(false) + this.SessionManager.isUserLoggedIn = sinon.stub().returns(false) }) } @@ -1563,7 +1560,7 @@ describe('ProjectController', function () { .stub() .callsArgWith(2, null, []) this.ProjectController._buildProjectList = sinon.stub().returns(projects) - this.AuthenticationController.getLoggedInUserId = sinon + this.SessionManager.getLoggedInUserId = sinon .stub() .returns(this.user._id) done() @@ -1585,9 +1582,7 @@ describe('ProjectController', function () { describe('projectEntitiesJson', function () { beforeEach(function () { - this.AuthenticationController.getLoggedInUserId = sinon - .stub() - .returns('abc') + this.SessionManager.getLoggedInUserId = sinon.stub().returns('abc') this.req.params = { Project_id: 'abcd' } this.project = { _id: 'abcd' } this.docs = [ diff --git a/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js b/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js index f82d94dd71..7816cbb305 100644 --- a/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js +++ b/services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js @@ -20,7 +20,7 @@ const modulePath = require('path').join( describe('RateLimiterMiddleware', function () { beforeEach(function () { - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: () => { return __guard__( __guard__( @@ -36,8 +36,7 @@ describe('RateLimiterMiddleware', function () { '@overleaf/settings': (this.settings = {}), '../../infrastructure/RateLimiter': (this.RateLimiter = {}), './LoginRateLimiter': {}, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, }, }) this.req = { params: {} } diff --git a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js index bb2c421162..e334841f13 100644 --- a/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js +++ b/services/web/test/unit/src/Subscription/SubscriptionControllerTests.js @@ -47,7 +47,7 @@ describe('SubscriptionController', function () { this.activeRecurlySubscription = mockSubscriptions['subscription-123-active'] - this.AuthenticationController = { + this.SessionManager = { getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.user), @@ -121,8 +121,7 @@ describe('SubscriptionController', function () { } this.SubscriptionController = SandboxedModule.require(modulePath, { requires: { - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, './SubscriptionHandler': this.SubscriptionHandler, './PlansLocator': this.PlansLocator, './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder, diff --git a/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js b/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js index 0abda17323..604090a3b0 100644 --- a/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js +++ b/services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js @@ -46,12 +46,12 @@ describe('SubscriptionGroupController', function () { getSubscription: sinon.stub().callsArgWith(1, null, this.subscription), } - this.AuthenticationController = { - getLoggedInUserId(req) { - return req.session.user._id + this.SessionManager = { + getLoggedInUserId(session) { + return session.user._id }, - getSessionUser(req) { - return req.session.user + getSessionUser(session) { + return session.user }, } @@ -59,8 +59,7 @@ describe('SubscriptionGroupController', function () { requires: { './SubscriptionGroupHandler': this.GroupHandler, './SubscriptionLocator': this.SubscriptionLocator, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, }, })) }) diff --git a/services/web/test/unit/src/Tags/TagsControllerTests.js b/services/web/test/unit/src/Tags/TagsControllerTests.js index 5a7accf292..652f5edb4b 100644 --- a/services/web/test/unit/src/Tags/TagsControllerTests.js +++ b/services/web/test/unit/src/Tags/TagsControllerTests.js @@ -32,16 +32,15 @@ describe('TagsController', function () { renameTag: sinon.stub().callsArg(3), createTag: sinon.stub(), } - this.AuthenticationController = { - getLoggedInUserId: req => { - return req.session.user._id + this.SessionManager = { + getLoggedInUserId: session => { + return session.user._id }, } this.controller = SandboxedModule.require(modulePath, { requires: { './TagsHandler': this.handler, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, }, }) this.req = { diff --git a/services/web/test/unit/src/Templates/TemplatesManagerTests.js b/services/web/test/unit/src/Templates/TemplatesManagerTests.js index 6daa0518e5..b747a21617 100644 --- a/services/web/test/unit/src/Templates/TemplatesManagerTests.js +++ b/services/web/test/unit/src/Templates/TemplatesManagerTests.js @@ -68,7 +68,7 @@ describe('TemplatesManager', function () { '../Project/ProjectOptionsHandler': this.ProjectOptionsHandler, '../Project/ProjectRootDocManager': this.ProjectRootDocManager, '../Project/ProjectDetailsHandler': this.ProjectDetailsHandler, - '../Authentication/AuthenticationController': (this.AuthenticationController = { + '../Authentication/SessionManager': (this.SessionManager = { getLoggedInUserId: sinon.stub(), }), '../../infrastructure/FileWriter': this.FileWriter, diff --git a/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js b/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js index 293300f8a6..4a84c52920 100644 --- a/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js +++ b/services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js @@ -9,7 +9,7 @@ const modulePath = require('path').join( describe('TpdsController', function () { beforeEach(function () { this.TpdsUpdateHandler = {} - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns('user-id'), } this.TpdsQueueManager = { @@ -24,8 +24,7 @@ describe('TpdsController', function () { '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = { tpdsFileLimit: sinon.stub().returns({ create: sinon.stub() }), }), - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, './TpdsQueueManager': this.TpdsQueueManager, '@overleaf/metrics': { inc() {}, @@ -271,8 +270,7 @@ describe('TpdsController', function () { }) it('should use userId from session', function () { - this.AuthenticationController.getLoggedInUserId.should.have.been - .calledOnce + this.SessionManager.getLoggedInUserId.should.have.been.calledOnce this.TpdsQueueManager.promises.getQueues.should.have.been.calledWith( 'user-id' ) diff --git a/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js b/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js index 9b64220590..798f1331e9 100644 --- a/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js +++ b/services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js @@ -37,7 +37,7 @@ describe('ProjectUploadController', function () { return Timer })()), } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user_id), } @@ -48,8 +48,7 @@ describe('ProjectUploadController', function () { './ProjectUploadManager': (this.ProjectUploadManager = {}), './FileSystemImportManager': (this.FileSystemImportManager = {}), '@overleaf/metrics': this.metrics, - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, './ArchiveErrors': ArchiveErrors, fs: (this.fs = {}), }, diff --git a/services/web/test/unit/src/User/UserControllerTests.js b/services/web/test/unit/src/User/UserControllerTests.js index a7ec1d2217..a3f7d6b51c 100644 --- a/services/web/test/unit/src/User/UserControllerTests.js +++ b/services/web/test/unit/src/User/UserControllerTests.js @@ -44,6 +44,8 @@ describe('UserController', function () { this.UserRegistrationHandler = { registerNewUser: sinon.stub() } this.AuthenticationController = { establishUserSession: sinon.stub().callsArg(2), + } + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.req.session.user), setInSessionUser: sinon.stub(), @@ -102,6 +104,7 @@ describe('UserController', function () { './UserRegistrationHandler': this.UserRegistrationHandler, '../Authentication/AuthenticationController': this .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../Authentication/AuthenticationManager': this.AuthenticationManager, '../../infrastructure/Features': (this.Features = { hasFeature: sinon.stub(), @@ -142,7 +145,7 @@ describe('UserController', function () { this.req.body.password = 'wat' this.req.logout = sinon.stub() this.req.session.destroy = sinon.stub().callsArgWith(0, null) - this.AuthenticationController.getLoggedInUserId = sinon + this.SessionManager.getLoggedInUserId = sinon .stub() .returns(this.user._id) this.AuthenticationManager.authenticate = sinon @@ -397,8 +400,8 @@ describe('UserController', function () { } this.res.sendStatus = code => { code.should.equal(200) - this.AuthenticationController.setInSessionUser - .calledWith(this.req, { + this.SessionManager.setInSessionUser + .calledWith(this.req.session, { email: this.newEmail, first_name: undefined, last_name: undefined, diff --git a/services/web/test/unit/src/User/UserEmailsControllerTests.js b/services/web/test/unit/src/User/UserEmailsControllerTests.js index 93cc68d0d8..da948cf004 100644 --- a/services/web/test/unit/src/User/UserEmailsControllerTests.js +++ b/services/web/test/unit/src/User/UserEmailsControllerTests.js @@ -23,7 +23,7 @@ describe('UserEmailsController', function () { getUser: sinon.stub().resolves(this.user), }, } - this.AuthenticationController = { + this.SessionManager = { getSessionUser: sinon.stub().returns(this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), setInSessionUser: sinon.stub(), @@ -51,8 +51,7 @@ describe('UserEmailsController', function () { this.HttpErrorHandler = { conflict: sinon.stub() } this.UserEmailsController = SandboxedModule.require(modulePath, { requires: { - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, '../../infrastructure/Features': this.Features, './UserSessionsManager': this.UserSessionsManager, './UserGetter': this.UserGetter, @@ -274,7 +273,7 @@ describe('UserEmailsController', function () { this.email = 'email_to_set_default@bar.com' this.req.body.email = this.email this.EmailHelper.parseEmail.returns(this.email) - this.AuthenticationController.setInSessionUser.returns(null) + this.SessionManager.setInSessionUser.returns(null) }) it('sets default email', function (done) { @@ -285,9 +284,11 @@ describe('UserEmailsController', function () { code.should.equal(200) assertCalledWith(this.EmailHelper.parseEmail, this.email) assertCalledWith( - this.AuthenticationController.setInSessionUser, - this.req, - { email: this.email } + this.SessionManager.setInSessionUser, + this.req.session, + { + email: this.email, + } ) assertCalledWith( this.UserUpdater.setDefaultEmailAddress, diff --git a/services/web/test/unit/src/User/UserInfoControllerTests.js b/services/web/test/unit/src/User/UserInfoControllerTests.js index 045ed46325..0012d643ba 100644 --- a/services/web/test/unit/src/User/UserInfoControllerTests.js +++ b/services/web/test/unit/src/User/UserInfoControllerTests.js @@ -31,7 +31,7 @@ describe('UserInfoController', function () { './UserGetter': this.UserGetter, './UserUpdater': this.UserUpdater, './UserDeleter': this.UserDeleter, - '../Authentication/AuthenticationController': (this.AuthenticationController = { + '../Authentication/SessionManager': (this.SessionManager = { getLoggedInUserId: sinon.stub(), }), }, @@ -49,7 +49,7 @@ describe('UserInfoController', function () { this.req.session.user = this.user this.UserInfoController.sendFormattedPersonalInfo = sinon.stub() this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, this.user) - this.AuthenticationController.getLoggedInUserId = sinon + this.SessionManager.getLoggedInUserId = sinon .stub() .returns(this.user._id) return this.UserInfoController.getLoggedInUsersPersonalInfo( diff --git a/services/web/test/unit/src/User/UserPagesControllerTests.js b/services/web/test/unit/src/User/UserPagesControllerTests.js index 20f59e0316..cc60bb104e 100644 --- a/services/web/test/unit/src/User/UserPagesControllerTests.js +++ b/services/web/test/unit/src/User/UserPagesControllerTests.js @@ -47,9 +47,11 @@ describe('UserPagesController', function () { this.UserSessionsManager = { getAllUserSessions: sinon.stub() } this.dropboxStatus = {} this.ErrorController = { notFound: sinon.stub() } - this.AuthenticationController = { + this.SessionManager = { getLoggedInUserId: sinon.stub().returns(this.user._id), getSessionUser: sinon.stub().returns(this.user), + } + this.AuthenticationController = { _getRedirectFromSession: sinon.stub(), setRedirectInSession: sinon.stub(), } @@ -61,6 +63,7 @@ describe('UserPagesController', function () { '../Errors/ErrorController': this.ErrorController, '../Authentication/AuthenticationController': this .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, request: (this.request = sinon.stub()), }, }) diff --git a/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js b/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js index 50fdc22a27..7319ee67a9 100644 --- a/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js +++ b/services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js @@ -54,7 +54,7 @@ describe('UserMembershipController', function () { }, ] - this.AuthenticationController = { + this.SessionManager = { getSessionUser: sinon.stub().returns(this.user), getLoggedInUserId: sinon.stub().returns(this.user._id), } @@ -69,8 +69,7 @@ describe('UserMembershipController', function () { modulePath, { requires: { - '../Authentication/AuthenticationController': this - .AuthenticationController, + '../Authentication/SessionManager': this.SessionManager, './UserMembershipHandler': this.UserMembershipHandler, }, }