Procházet zdrojové kódy

Merge pull request #4338 from overleaf/ab-session-manager

Extract functions from AuthenticationController to SessionManager

GitOrigin-RevId: 86870ce03a762e1a837dcf493759e8851e759883
Alexandre Bourdin před 5 roky
rodič
revize
9468e5cb4f
66 změnil soubory, kde provedl 460 přidání a 458 odebrání
  1. 3 3
      services/web/app/src/Features/Analytics/AnalyticsController.js
  2. 2 2
      services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js
  3. 5 46
      services/web/app/src/Features/Authentication/AuthenticationController.js
  4. 46 0
      services/web/app/src/Features/Authentication/SessionManager.js
  5. 3 2
      services/web/app/src/Features/Authorization/AuthorizationMiddleware.js
  6. 4 4
      services/web/app/src/Features/BetaProgram/BetaProgramController.js
  7. 2 3
      services/web/app/src/Features/Chat/ChatController.js
  8. 3 3
      services/web/app/src/Features/Collaborators/CollaboratorsController.js
  9. 5 5
      services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js
  10. 5 6
      services/web/app/src/Features/Compile/CompileController.js
  11. 2 2
      services/web/app/src/Features/Contacts/ContactController.js
  12. 2 1
      services/web/app/src/Features/Contacts/ContactRouter.js
  13. 6 6
      services/web/app/src/Features/Editor/EditorHttpController.js
  14. 2 2
      services/web/app/src/Features/Errors/ErrorController.js
  15. 3 3
      services/web/app/src/Features/Exports/ExportsController.js
  16. 7 7
      services/web/app/src/Features/History/HistoryController.js
  17. 3 3
      services/web/app/src/Features/LinkedFiles/LinkedFilesController.js
  18. 3 3
      services/web/app/src/Features/Notifications/NotificationsController.js
  19. 2 1
      services/web/app/src/Features/PasswordReset/PasswordResetController.js
  20. 15 15
      services/web/app/src/Features/Project/ProjectController.js
  21. 2 2
      services/web/app/src/Features/Referal/ReferalController.js
  22. 2 2
      services/web/app/src/Features/Security/RateLimiterMiddleware.js
  23. 2 2
      services/web/app/src/Features/Spelling/SpellingController.js
  24. 2 2
      services/web/app/src/Features/StaticPages/HomeController.js
  25. 14 14
      services/web/app/src/Features/Subscription/SubscriptionController.js
  26. 2 2
      services/web/app/src/Features/Subscription/SubscriptionGroupController.js
  27. 5 5
      services/web/app/src/Features/Subscription/TeamInvitesController.js
  28. 2 2
      services/web/app/src/Features/SystemMessages/SystemMessageController.js
  29. 7 7
      services/web/app/src/Features/Tags/TagsController.js
  30. 2 2
      services/web/app/src/Features/Templates/TemplatesController.js
  31. 2 2
      services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js
  32. 3 2
      services/web/app/src/Features/TokenAccess/TokenAccessController.js
  33. 3 3
      services/web/app/src/Features/Uploads/ProjectUploadController.js
  34. 10 10
      services/web/app/src/Features/User/UserController.js
  35. 10 10
      services/web/app/src/Features/User/UserEmailsController.js
  36. 2 2
      services/web/app/src/Features/User/UserInfoController.js
  37. 3 2
      services/web/app/src/Features/User/UserPagesController.js
  38. 2 2
      services/web/app/src/Features/UserMembership/UserMembershipController.js
  39. 8 9
      services/web/app/src/infrastructure/ExpressLocals.js
  40. 6 5
      services/web/app/src/infrastructure/Server.js
  41. 2 1
      services/web/app/src/router.js
  42. 2 1
      services/web/modules/launchpad/app/src/LaunchpadController.js
  43. 3 6
      services/web/modules/launchpad/test/unit/src/LaunchpadControllerTests.js
  44. 4 5
      services/web/test/unit/src/Analytics/AnalyticsControllerTests.js
  45. 33 132
      services/web/test/unit/src/Authentication/AuthenticationControllerTests.js
  46. 114 0
      services/web/test/unit/src/Authentication/SessionManagerTests.js
  47. 18 22
      services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js
  48. 2 3
      services/web/test/unit/src/Chat/ChatControllerTests.js
  49. 2 3
      services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js
  50. 4 5
      services/web/test/unit/src/Compile/CompileControllerTests.js
  51. 5 9
      services/web/test/unit/src/Contact/ContactControllerTests.js
  52. 2 3
      services/web/test/unit/src/Editor/EditorHttpControllerTests.js
  53. 10 11
      services/web/test/unit/src/History/HistoryControllerTests.js
  54. 5 10
      services/web/test/unit/src/Project/ProjectControllerTests.js
  55. 2 3
      services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js
  56. 2 3
      services/web/test/unit/src/Subscription/SubscriptionControllerTests.js
  57. 6 7
      services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js
  58. 4 5
      services/web/test/unit/src/Tags/TagsControllerTests.js
  59. 1 1
      services/web/test/unit/src/Templates/TemplatesManagerTests.js
  60. 3 5
      services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js
  61. 2 3
      services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js
  62. 6 3
      services/web/test/unit/src/User/UserControllerTests.js
  63. 8 7
      services/web/test/unit/src/User/UserEmailsControllerTests.js
  64. 2 2
      services/web/test/unit/src/User/UserInfoControllerTests.js
  65. 4 1
      services/web/test/unit/src/User/UserPagesControllerTests.js
  66. 2 3
      services/web/test/unit/src/UserMembership/UserMembershipControllerTests.js

+ 3 - 3
services/web/app/src/Features/Analytics/AnalyticsController.js

@@ -1,6 +1,6 @@
 const metrics = require('@overleaf/metrics')
 const metrics = require('@overleaf/metrics')
 const AnalyticsManager = require('./AnalyticsManager')
 const AnalyticsManager = require('./AnalyticsManager')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const GeoIpLookup = require('../../infrastructure/GeoIpLookup')
 const GeoIpLookup = require('../../infrastructure/GeoIpLookup')
 const Features = require('../../infrastructure/Features')
 const Features = require('../../infrastructure/Features')
 
 
@@ -9,7 +9,7 @@ module.exports = {
     if (!Features.hasFeature('analytics')) {
     if (!Features.hasFeature('analytics')) {
       return res.sendStatus(202)
       return res.sendStatus(202)
     }
     }
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { projectId } = req.params
     const { projectId } = req.params
     let countryCode = null
     let countryCode = null
 
 
@@ -31,7 +31,7 @@ module.exports = {
       return res.sendStatus(202)
       return res.sendStatus(202)
     }
     }
     const userId =
     const userId =
-      AuthenticationController.getLoggedInUserId(req) || req.sessionID
+      SessionManager.getLoggedInUserId(req.session) || req.sessionID
     AnalyticsManager.recordEvent(userId, req.params.event, req.body)
     AnalyticsManager.recordEvent(userId, req.params.event, req.body)
     res.sendStatus(202)
     res.sendStatus(202)
   },
   },

+ 2 - 2
services/web/app/src/Features/Analytics/AnalyticsRegistrationSourceMiddleware.js

@@ -1,7 +1,7 @@
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const OError = require('@overleaf/o-error')
 const OError = require('@overleaf/o-error')
 const AnalyticsRegistrationSourceHelper = require('./AnalyticsRegistrationSourceHelper')
 const AnalyticsRegistrationSourceHelper = require('./AnalyticsRegistrationSourceHelper')
-const AuthenticationController = require('../../Features/Authentication/AuthenticationController')
+const SessionManager = require('../../Features/Authentication/SessionManager')
 
 
 function setSource(source) {
 function setSource(source) {
   return function (req, res, next) {
   return function (req, res, next) {
@@ -25,7 +25,7 @@ function setInbound() {
       return next() // don't overwrite referrer
       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
       return next() // don't store referrer if user is alread logged in
     }
     }
 
 

+ 5 - 46
services/web/app/src/Features/Authentication/AuthenticationController.js

@@ -1,4 +1,5 @@
 const AuthenticationManager = require('./AuthenticationManager')
 const AuthenticationManager = require('./AuthenticationManager')
+const SessionManager = require('./SessionManager')
 const OError = require('@overleaf/o-error')
 const OError = require('@overleaf/o-error')
 const LoginRateLimiter = require('../Security/LoginRateLimiter')
 const LoginRateLimiter = require('../Security/LoginRateLimiter')
 const UserUpdater = require('../User/UserUpdater')
 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() {
   requireLogin() {
     const doRequest = function (req, res, next) {
     const doRequest = function (req, res, next) {
       if (next == null) {
       if (next == null) {
         next = function () {}
         next = function () {}
       }
       }
-      if (!AuthenticationController.isUserLoggedIn(req)) {
+      if (!SessionManager.isUserLoggedIn(req.session)) {
         if (acceptsJson(req)) return send401WithChallenge(res)
         if (acceptsJson(req)) return send401WithChallenge(res)
         return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
         return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
       } else {
       } else {
-        req.user = AuthenticationController.getSessionUser(req)
+        req.user = SessionManager.getSessionUser(req.session)
         return next()
         return next()
       }
       }
     }
     }
@@ -320,7 +279,7 @@ const AuthenticationController = {
 
 
     if (req.headers.authorization != null) {
     if (req.headers.authorization != null) {
       AuthenticationController.requirePrivateApiAuth()(req, res, next)
       AuthenticationController.requirePrivateApiAuth()(req, res, next)
-    } else if (AuthenticationController.isUserLoggedIn(req)) {
+    } else if (SessionManager.isUserLoggedIn(req.session)) {
       next()
       next()
     } else {
     } else {
       logger.log(
       logger.log(
@@ -341,7 +300,7 @@ const AuthenticationController = {
     ) {
     ) {
       return next()
       return next()
     }
     }
-    const user = AuthenticationController.getSessionUser(req)
+    const user = SessionManager.getSessionUser(req.session)
     if (!(user && user.isAdmin)) {
     if (!(user && user.isAdmin)) {
       return next()
       return next()
     }
     }

+ 46 - 0
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

+ 3 - 2
services/web/app/src/Features/Authorization/AuthorizationMiddleware.js

@@ -6,6 +6,7 @@ const { ObjectId } = require('mongodb')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 const HttpErrorHandler = require('../Errors/HttpErrorHandler')
 const HttpErrorHandler = require('../Errors/HttpErrorHandler')
 const AuthenticationController = require('../Authentication/AuthenticationController')
 const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
 
 
 module.exports = AuthorizationMiddleware = {
 module.exports = AuthorizationMiddleware = {
@@ -244,7 +245,7 @@ module.exports = AuthorizationMiddleware = {
 
 
   _getUserId(req, callback) {
   _getUserId(req, callback) {
     const userId =
     const userId =
-      AuthenticationController.getLoggedInUserId(req) ||
+      SessionManager.getLoggedInUserId(req.session) ||
       (req.oauth_user && req.oauth_user._id) ||
       (req.oauth_user && req.oauth_user._id) ||
       null
       null
     callback(null, userId)
     callback(null, userId)
@@ -258,7 +259,7 @@ module.exports = AuthorizationMiddleware = {
   },
   },
 
 
   restricted(req, res, next) {
   restricted(req, res, next) {
-    if (AuthenticationController.isUserLoggedIn(req)) {
+    if (SessionManager.isUserLoggedIn(req.session)) {
       return res.render('user/restricted', { title: 'restricted' })
       return res.render('user/restricted', { title: 'restricted' })
     }
     }
     const { from } = req.query
     const { from } = req.query

+ 4 - 4
services/web/app/src/Features/BetaProgram/BetaProgramController.js

@@ -3,11 +3,11 @@ const OError = require('@overleaf/o-error')
 const UserGetter = require('../User/UserGetter')
 const UserGetter = require('../User/UserGetter')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 
 
 const BetaProgramController = {
 const BetaProgramController = {
   optIn(req, res, next) {
   optIn(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     logger.log({ userId }, 'user opting in to beta program')
     logger.log({ userId }, 'user opting in to beta program')
     if (userId == null) {
     if (userId == null) {
       return next(new Error('no user id in session'))
       return next(new Error('no user id in session'))
@@ -21,7 +21,7 @@ const BetaProgramController = {
   },
   },
 
 
   optOut(req, res, next) {
   optOut(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     logger.log({ userId }, 'user opting out of beta program')
     logger.log({ userId }, 'user opting out of beta program')
     if (userId == null) {
     if (userId == null) {
       return next(new Error('no user id in session'))
       return next(new Error('no user id in session'))
@@ -35,7 +35,7 @@ const BetaProgramController = {
   },
   },
 
 
   optInPage(req, res, next) {
   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')
     logger.log({ user_id: userId }, 'showing beta participation page for user')
     UserGetter.getUser(userId, function (err, user) {
     UserGetter.getUser(userId, function (err, user) {
       if (err) {
       if (err) {

+ 2 - 3
services/web/app/src/Features/Chat/ChatController.js

@@ -16,8 +16,7 @@
 let ChatController
 let ChatController
 const ChatApiHandler = require('./ChatApiHandler')
 const ChatApiHandler = require('./ChatApiHandler')
 const EditorRealTimeController = require('../Editor/EditorRealTimeController')
 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 UserInfoManager = require('../User/UserInfoManager')
 const UserInfoController = require('../User/UserInfoController')
 const UserInfoController = require('../User/UserInfoController')
 const async = require('async')
 const async = require('async')
@@ -26,7 +25,7 @@ module.exports = ChatController = {
   sendMessage(req, res, next) {
   sendMessage(req, res, next) {
     const { project_id } = req.params
     const { project_id } = req.params
     const { content } = req.body
     const { content } = req.body
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
     if (user_id == null) {
     if (user_id == null) {
       const err = new Error('no logged-in user')
       const err = new Error('no logged-in user')
       return next(err)
       return next(err)

+ 3 - 3
services/web/app/src/Features/Collaborators/CollaboratorsController.js

@@ -4,7 +4,7 @@ const { ObjectId } = require('mongodb')
 const CollaboratorsHandler = require('./CollaboratorsHandler')
 const CollaboratorsHandler = require('./CollaboratorsHandler')
 const CollaboratorsGetter = require('./CollaboratorsGetter')
 const CollaboratorsGetter = require('./CollaboratorsGetter')
 const OwnershipTransferHandler = require('./OwnershipTransferHandler')
 const OwnershipTransferHandler = require('./OwnershipTransferHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const EditorRealTimeController = require('../Editor/EditorRealTimeController')
 const EditorRealTimeController = require('../Editor/EditorRealTimeController')
 const TagsHandler = require('../Tags/TagsHandler')
 const TagsHandler = require('../Tags/TagsHandler')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
@@ -31,7 +31,7 @@ async function removeUserFromProject(req, res, next) {
 
 
 async function removeSelfFromProject(req, res, next) {
 async function removeSelfFromProject(req, res, next) {
   const projectId = req.params.Project_id
   const projectId = req.params.Project_id
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   await _removeUserIdFromProject(projectId, userId)
   await _removeUserIdFromProject(projectId, userId)
   res.sendStatus(204)
   res.sendStatus(204)
 }
 }
@@ -74,7 +74,7 @@ async function setCollaboratorInfo(req, res, next) {
 }
 }
 
 
 async function transferOwnership(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 projectId = req.params.Project_id
   const toUserId = req.body.user_id
   const toUserId = req.body.user_id
   try {
   try {

+ 5 - 5
services/web/app/src/Features/Collaborators/CollaboratorsInviteController.js

@@ -24,7 +24,7 @@ const Settings = require('@overleaf/settings')
 const EmailHelper = require('../Helpers/EmailHelper')
 const EmailHelper = require('../Helpers/EmailHelper')
 const EditorRealTimeController = require('../Editor/EditorRealTimeController')
 const EditorRealTimeController = require('../Editor/EditorRealTimeController')
 const AnalyticsManager = require('../Analytics/AnalyticsManager')
 const AnalyticsManager = require('../Analytics/AnalyticsManager')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const rateLimiter = require('../../infrastructure/RateLimiter')
 const rateLimiter = require('../../infrastructure/RateLimiter')
 
 
 module.exports = CollaboratorsInviteController = {
 module.exports = CollaboratorsInviteController = {
@@ -99,7 +99,7 @@ module.exports = CollaboratorsInviteController = {
   inviteToProject(req, res, next) {
   inviteToProject(req, res, next) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
     let { email } = req.body
     let { email } = req.body
-    const sendingUser = AuthenticationController.getSessionUser(req)
+    const sendingUser = SessionManager.getSessionUser(req.session)
     const sendingUserId = sendingUser._id
     const sendingUserId = sendingUser._id
     if (email === sendingUser.email) {
     if (email === sendingUser.email) {
       logger.log(
       logger.log(
@@ -230,7 +230,7 @@ module.exports = CollaboratorsInviteController = {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
     const inviteId = req.params.invite_id
     const inviteId = req.params.invite_id
     logger.log({ projectId, inviteId }, 'resending invite')
     logger.log({ projectId, inviteId }, 'resending invite')
-    const sendingUser = AuthenticationController.getSessionUser(req)
+    const sendingUser = SessionManager.getSessionUser(req.session)
     return CollaboratorsInviteController._checkRateLimit(
     return CollaboratorsInviteController._checkRateLimit(
       sendingUser._id,
       sendingUser._id,
       function (error, underRateLimit) {
       function (error, underRateLimit) {
@@ -270,7 +270,7 @@ module.exports = CollaboratorsInviteController = {
       return res.render('project/invite/not-valid', { title: 'Invalid Invite' })
       return res.render('project/invite/not-valid', { title: 'Invalid Invite' })
     }
     }
     // check if the user is already a member of the project
     // 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(
     return CollaboratorsGetter.isUserInvitedMemberOfProject(
       currentUser._id,
       currentUser._id,
       projectId,
       projectId,
@@ -355,7 +355,7 @@ module.exports = CollaboratorsInviteController = {
   acceptInvite(req, res, next) {
   acceptInvite(req, res, next) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
     const { token } = req.params
     const { token } = req.params
-    const currentUser = AuthenticationController.getSessionUser(req)
+    const currentUser = SessionManager.getSessionUser(req.session)
     logger.log(
     logger.log(
       { projectId, userId: currentUser._id, token },
       { projectId, userId: currentUser._id, token },
       'got request to accept invite'
       'got request to accept invite'

+ 5 - 6
services/web/app/src/Features/Compile/CompileController.js

@@ -21,8 +21,7 @@ const ClsiManager = require('./ClsiManager')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const request = require('request')
 const request = require('request')
 const Settings = require('@overleaf/settings')
 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 RateLimiter = require('../../infrastructure/RateLimiter')
 const ClsiCookieManager = require('./ClsiCookieManager')(
 const ClsiCookieManager = require('./ClsiCookieManager')(
   Settings.apis.clsi != null ? Settings.apis.clsi.backendGroupName : undefined
   Settings.apis.clsi != null ? Settings.apis.clsi.backendGroupName : undefined
@@ -45,7 +44,7 @@ module.exports = CompileController = {
     const project_id = req.params.Project_id
     const project_id = req.params.Project_id
     const isAutoCompile = !!req.query.auto_compile
     const isAutoCompile = !!req.query.auto_compile
     const enablePdfCaching = !!req.query.enable_pdf_caching
     const enablePdfCaching = !!req.query.enable_pdf_caching
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
     const options = {
     const options = {
       isAutoCompile,
       isAutoCompile,
       enablePdfCaching,
       enablePdfCaching,
@@ -111,7 +110,7 @@ module.exports = CompileController = {
       next = function (error) {}
       next = function (error) {}
     }
     }
     const project_id = req.params.Project_id
     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) {
     return CompileManager.stopCompile(project_id, user_id, function (error) {
       if (error != null) {
       if (error != null) {
         return next(error)
         return next(error)
@@ -174,7 +173,7 @@ module.exports = CompileController = {
   _compileAsUser(req, callback) {
   _compileAsUser(req, callback) {
     // callback with user_id if per-user, undefined otherwise
     // callback with user_id if per-user, undefined otherwise
     if (!Settings.disablePerUserCompiles) {
     if (!Settings.disablePerUserCompiles) {
-      const user_id = AuthenticationController.getLoggedInUserId(req)
+      const user_id = SessionManager.getLoggedInUserId(req.session)
       return callback(null, user_id)
       return callback(null, user_id)
     } else {
     } else {
       return callback()
       return callback()
@@ -184,7 +183,7 @@ module.exports = CompileController = {
   _downloadAsUser(req, callback) {
   _downloadAsUser(req, callback) {
     // callback with user_id if per-user, undefined otherwise
     // callback with user_id if per-user, undefined otherwise
     if (!Settings.disablePerUserCompiles) {
     if (!Settings.disablePerUserCompiles) {
-      const user_id = AuthenticationController.getLoggedInUserId(req)
+      const user_id = SessionManager.getLoggedInUserId(req.session)
       return callback(null, user_id)
       return callback(null, user_id)
     } else {
     } else {
       return callback()
       return callback()

+ 2 - 2
services/web/app/src/Features/Contacts/ContactController.js

@@ -13,7 +13,7 @@
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  */
  */
 let ContactsController
 let ContactsController
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const ContactManager = require('./ContactManager')
 const ContactManager = require('./ContactManager')
 const UserGetter = require('../User/UserGetter')
 const UserGetter = require('../User/UserGetter')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
@@ -21,7 +21,7 @@ const Modules = require('../../infrastructure/Modules')
 
 
 module.exports = ContactsController = {
 module.exports = ContactsController = {
   getContacts(req, res, next) {
   getContacts(req, res, next) {
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
     return ContactManager.getContactIds(
     return ContactManager.getContactIds(
       user_id,
       user_id,
       { limit: 50 },
       { limit: 50 },

+ 2 - 1
services/web/app/src/Features/Contacts/ContactRouter.js

@@ -1,4 +1,5 @@
 const AuthenticationController = require('../Authentication/AuthenticationController')
 const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const ContactController = require('./ContactController')
 const ContactController = require('./ContactController')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
 
 
@@ -7,7 +8,7 @@ function contactsAuthenticationMiddleware() {
     return AuthenticationController.requireLogin()
     return AuthenticationController.requireLogin()
   } else {
   } else {
     return (req, res, next) => {
     return (req, res, next) => {
-      if (AuthenticationController.isUserLoggedIn(req)) {
+      if (SessionManager.isUserLoggedIn(req.session)) {
         next()
         next()
       } else {
       } else {
         res.send({ contacts: [] })
         res.send({ contacts: [] })

+ 6 - 6
services/web/app/src/Features/Editor/EditorHttpController.js

@@ -9,7 +9,7 @@ const CollaboratorsInviteHandler = require('../Collaborators/CollaboratorsInvite
 const CollaboratorsHandler = require('../Collaborators/CollaboratorsHandler')
 const CollaboratorsHandler = require('../Collaborators/CollaboratorsHandler')
 const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
 const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 const HttpErrorHandler = require('../Errors/HttpErrorHandler')
 const HttpErrorHandler = require('../Errors/HttpErrorHandler')
 const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler')
 const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler')
@@ -160,7 +160,7 @@ async function addDoc(req, res, next) {
   const projectId = req.params.Project_id
   const projectId = req.params.Project_id
   const { name } = req.body
   const { name } = req.body
   const parentFolderId = req.body.parent_folder_id
   const parentFolderId = req.body.parent_folder_id
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
 
 
   if (!_nameIsAcceptableLength(name)) {
   if (!_nameIsAcceptableLength(name)) {
     return res.sendStatus(400)
     return res.sendStatus(400)
@@ -188,7 +188,7 @@ async function addFolder(req, res, next) {
   const projectId = req.params.Project_id
   const projectId = req.params.Project_id
   const { name } = req.body
   const { name } = req.body
   const parentFolderId = req.body.parent_folder_id
   const parentFolderId = req.body.parent_folder_id
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   if (!_nameIsAcceptableLength(name)) {
   if (!_nameIsAcceptableLength(name)) {
     return res.sendStatus(400)
     return res.sendStatus(400)
   }
   }
@@ -220,7 +220,7 @@ async function renameEntity(req, res, next) {
   if (!_nameIsAcceptableLength(name)) {
   if (!_nameIsAcceptableLength(name)) {
     return res.sendStatus(400)
     return res.sendStatus(400)
   }
   }
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   await EditorController.promises.renameEntity(
   await EditorController.promises.renameEntity(
     projectId,
     projectId,
     entityId,
     entityId,
@@ -236,7 +236,7 @@ async function moveEntity(req, res, next) {
   const entityId = req.params.entity_id
   const entityId = req.params.entity_id
   const entityType = req.params.entity_type
   const entityType = req.params.entity_type
   const folderId = req.body.folder_id
   const folderId = req.body.folder_id
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   await EditorController.promises.moveEntity(
   await EditorController.promises.moveEntity(
     projectId,
     projectId,
     entityId,
     entityId,
@@ -266,7 +266,7 @@ async function deleteEntity(req, res, next) {
   const projectId = req.params.Project_id
   const projectId = req.params.Project_id
   const entityId = req.params.entity_id
   const entityId = req.params.entity_id
   const entityType = req.params.entity_type
   const entityType = req.params.entity_type
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   await EditorController.promises.deleteEntity(
   await EditorController.promises.deleteEntity(
     projectId,
     projectId,
     entityId,
     entityId,

+ 2 - 2
services/web/app/src/Features/Errors/ErrorController.js

@@ -1,7 +1,7 @@
 let ErrorController
 let ErrorController
 const Errors = require('./Errors')
 const Errors = require('./Errors')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const SamlLogHandler = require('../SamlLog/SamlLogHandler')
 const SamlLogHandler = require('../SamlLog/SamlLogHandler')
 const HttpErrorHandler = require('./HttpErrorHandler')
 const HttpErrorHandler = require('./HttpErrorHandler')
 
 
@@ -22,7 +22,7 @@ module.exports = ErrorController = {
   },
   },
 
 
   handleError(error, req, res, next) {
   handleError(error, req, res, next) {
-    const user = AuthenticationController.getSessionUser(req)
+    const user = SessionManager.getSessionUser(req.session)
     // log errors related to SAML flow
     // log errors related to SAML flow
     if (req.session && req.session.saml) {
     if (req.session && req.session.saml) {
       SamlLogHandler.log(req.session.saml.universityId, req.sessionID, {
       SamlLogHandler.log(req.session.saml.universityId, req.sessionID, {

+ 3 - 3
services/web/app/src/Features/Exports/ExportsController.js

@@ -11,13 +11,13 @@
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  */
  */
 const ExportsHandler = require('./ExportsHandler')
 const ExportsHandler = require('./ExportsHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 
 
 module.exports = {
 module.exports = {
   exportProject(req, res, next) {
   exportProject(req, res, next) {
     const { project_id, brand_variation_id } = req.params
     const { project_id, brand_variation_id } = req.params
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
     const export_params = {
     const export_params = {
       project_id,
       project_id,
       brand_variation_id,
       brand_variation_id,
@@ -111,7 +111,7 @@ module.exports = {
   exportDownload(req, res, next) {
   exportDownload(req, res, next) {
     const { type, export_id } = req.params
     const { type, export_id } = req.params
 
 
-    AuthenticationController.getLoggedInUserId(req)
+    SessionManager.getLoggedInUserId(req.session)
     return ExportsHandler.fetchDownload(
     return ExportsHandler.fetchDownload(
       export_id,
       export_id,
       type,
       type,

+ 7 - 7
services/web/app/src/Features/History/HistoryController.js

@@ -4,7 +4,7 @@ const async = require('async')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const request = require('request')
 const request = require('request')
 const settings = require('@overleaf/settings')
 const settings = require('@overleaf/settings')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const UserGetter = require('../User/UserGetter')
 const UserGetter = require('../User/UserGetter')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 const HistoryManager = require('./HistoryManager')
 const HistoryManager = require('./HistoryManager')
@@ -40,7 +40,7 @@ module.exports = HistoryController = {
   },
   },
 
 
   proxyToHistoryApi(req, res, next) {
   proxyToHistoryApi(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const url =
     const url =
       HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
       HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
 
 
@@ -59,7 +59,7 @@ module.exports = HistoryController = {
   },
   },
 
 
   proxyToHistoryApiAndInjectUserDetails(req, res, next) {
   proxyToHistoryApiAndInjectUserDetails(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const url =
     const url =
       HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
       HistoryController.buildHistoryServiceUrl(req.useProjectHistory) + req.url
     HistoryController._makeRequest(
     HistoryController._makeRequest(
@@ -111,7 +111,7 @@ module.exports = HistoryController = {
   restoreFileFromV2(req, res, next) {
   restoreFileFromV2(req, res, next) {
     const { project_id: projectId } = req.params
     const { project_id: projectId } = req.params
     const { version, pathname } = req.body
     const { version, pathname } = req.body
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     RestoreManager.restoreFileFromV2(
     RestoreManager.restoreFileFromV2(
       userId,
       userId,
       projectId,
       projectId,
@@ -132,7 +132,7 @@ module.exports = HistoryController = {
   restoreDocFromDeletedDoc(req, res, next) {
   restoreDocFromDeletedDoc(req, res, next) {
     const { project_id: projectId, doc_id: docId } = req.params
     const { project_id: projectId, doc_id: docId } = req.params
     const { name } = req.body
     const { name } = req.body
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     if (name == null) {
     if (name == null) {
       return res.sendStatus(400) // Malformed request
       return res.sendStatus(400) // Malformed request
     }
     }
@@ -175,7 +175,7 @@ module.exports = HistoryController = {
   createLabel(req, res, next) {
   createLabel(req, res, next) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
     const { comment, version } = req.body
     const { comment, version } = req.body
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     HistoryController._makeRequest(
     HistoryController._makeRequest(
       {
       {
         method: 'POST',
         method: 'POST',
@@ -268,7 +268,7 @@ module.exports = HistoryController = {
 
 
   deleteLabel(req, res, next) {
   deleteLabel(req, res, next) {
     const { Project_id: projectId, label_id: labelId } = req.params
     const { Project_id: projectId, label_id: labelId } = req.params
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     HistoryController._makeRequest(
     HistoryController._makeRequest(
       {
       {
         method: 'DELETE',
         method: 'DELETE',

+ 3 - 3
services/web/app/src/Features/LinkedFiles/LinkedFilesController.js

@@ -13,7 +13,7 @@
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  */
  */
 let LinkedFilesController
 let LinkedFilesController
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const EditorController = require('../Editor/EditorController')
 const EditorController = require('../Editor/EditorController')
 const ProjectLocator = require('../Project/ProjectLocator')
 const ProjectLocator = require('../Project/ProjectLocator')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
@@ -65,7 +65,7 @@ module.exports = LinkedFilesController = {
   createLinkedFile(req, res, next) {
   createLinkedFile(req, res, next) {
     const { project_id } = req.params
     const { project_id } = req.params
     const { name, provider, data, parent_folder_id } = req.body
     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)
     const Agent = LinkedFilesController._getAgent(provider)
     if (Agent == null) {
     if (Agent == null) {
@@ -91,7 +91,7 @@ module.exports = LinkedFilesController = {
 
 
   refreshLinkedFile(req, res, next) {
   refreshLinkedFile(req, res, next) {
     const { project_id, file_id } = req.params
     const { project_id, file_id } = req.params
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
 
 
     return LinkedFilesHandler.getFileById(
     return LinkedFilesHandler.getFileById(
       project_id,
       project_id,

+ 3 - 3
services/web/app/src/Features/Notifications/NotificationsController.js

@@ -1,10 +1,10 @@
 const NotificationsHandler = require('./NotificationsHandler')
 const NotificationsHandler = require('./NotificationsHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const _ = require('underscore')
 const _ = require('underscore')
 
 
 module.exports = {
 module.exports = {
   getAllUnreadNotifications(req, res) {
   getAllUnreadNotifications(req, res) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     NotificationsHandler.getUserNotifications(
     NotificationsHandler.getUserNotifications(
       userId,
       userId,
       function (err, unreadNotifications) {
       function (err, unreadNotifications) {
@@ -24,7 +24,7 @@ module.exports = {
   },
   },
 
 
   markNotificationAsRead(req, res) {
   markNotificationAsRead(req, res) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { notificationId } = req.params
     const { notificationId } = req.params
     NotificationsHandler.markAsRead(userId, notificationId, () =>
     NotificationsHandler.markAsRead(userId, notificationId, () =>
       res.sendStatus(200)
       res.sendStatus(200)

+ 2 - 1
services/web/app/src/Features/PasswordReset/PasswordResetController.js

@@ -1,5 +1,6 @@
 const PasswordResetHandler = require('./PasswordResetHandler')
 const PasswordResetHandler = require('./PasswordResetHandler')
 const AuthenticationController = require('../Authentication/AuthenticationController')
 const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const UserGetter = require('../User/UserGetter')
 const UserGetter = require('../User/UserGetter')
 const UserUpdater = require('../User/UserUpdater')
 const UserUpdater = require('../User/UserUpdater')
 const UserSessionsManager = require('../User/UserSessionsManager')
 const UserSessionsManager = require('../User/UserSessionsManager')
@@ -16,7 +17,7 @@ async function setNewUserPassword(req, res, next) {
   passwordResetToken = passwordResetToken.trim()
   passwordResetToken = passwordResetToken.trim()
   delete req.session.resetToken
   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
   // password reset via tokens can be done while logged in, or not
   const auditLog = {
   const auditLog = {
     initiatorId,
     initiatorId,

+ 15 - 15
services/web/app/src/Features/Project/ProjectController.js

@@ -23,7 +23,7 @@ const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
 const ProjectUpdateHandler = require('./ProjectUpdateHandler')
 const ProjectUpdateHandler = require('./ProjectUpdateHandler')
 const ProjectGetter = require('./ProjectGetter')
 const ProjectGetter = require('./ProjectGetter')
 const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
 const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const Sources = require('../Authorization/Sources')
 const Sources = require('../Authorization/Sources')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
 const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
 const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
 const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
@@ -141,7 +141,7 @@ const ProjectController = {
 
 
   deleteProject(req, res) {
   deleteProject(req, res) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
-    const user = AuthenticationController.getSessionUser(req)
+    const user = SessionManager.getSessionUser(req.session)
     const cb = err => {
     const cb = err => {
       if (err != null) {
       if (err != null) {
         res.sendStatus(500)
         res.sendStatus(500)
@@ -158,7 +158,7 @@ const ProjectController = {
 
 
   archiveProject(req, res, next) {
   archiveProject(req, res, next) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     ProjectDeleter.archiveProject(projectId, userId, function (err) {
     ProjectDeleter.archiveProject(projectId, userId, function (err) {
       if (err != null) {
       if (err != null) {
@@ -171,7 +171,7 @@ const ProjectController = {
 
 
   unarchiveProject(req, res, next) {
   unarchiveProject(req, res, next) {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
     ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
       if (err != null) {
       if (err != null) {
@@ -184,7 +184,7 @@ const ProjectController = {
 
 
   trashProject(req, res, next) {
   trashProject(req, res, next) {
     const projectId = req.params.project_id
     const projectId = req.params.project_id
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     ProjectDeleter.trashProject(projectId, userId, function (err) {
     ProjectDeleter.trashProject(projectId, userId, function (err) {
       if (err != null) {
       if (err != null) {
@@ -197,7 +197,7 @@ const ProjectController = {
 
 
   untrashProject(req, res, next) {
   untrashProject(req, res, next) {
     const projectId = req.params.project_id
     const projectId = req.params.project_id
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     ProjectDeleter.untrashProject(projectId, userId, function (err) {
     ProjectDeleter.untrashProject(projectId, userId, function (err) {
       if (err != null) {
       if (err != null) {
@@ -246,10 +246,10 @@ const ProjectController = {
     const projectId = req.params.Project_id
     const projectId = req.params.Project_id
     const { projectName } = req.body
     const { projectName } = req.body
     logger.log({ projectId, projectName }, 'cloning project')
     logger.log({ projectId, projectName }, 'cloning project')
-    if (!AuthenticationController.isUserLoggedIn(req)) {
+    if (!SessionManager.isUserLoggedIn(req.session)) {
       return res.send({ redir: '/register' })
       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
     const { first_name: firstName, last_name: lastName, email } = currentUser
     ProjectDuplicator.duplicate(
     ProjectDuplicator.duplicate(
       currentUser,
       currentUser,
@@ -279,7 +279,7 @@ const ProjectController = {
   },
   },
 
 
   newProject(req, res, next) {
   newProject(req, res, next) {
-    const currentUser = AuthenticationController.getSessionUser(req)
+    const currentUser = SessionManager.getSessionUser(req.session)
     const {
     const {
       first_name: firstName,
       first_name: firstName,
       last_name: lastName,
       last_name: lastName,
@@ -330,7 +330,7 @@ const ProjectController = {
   },
   },
 
 
   userProjectsJson(req, res, next) {
   userProjectsJson(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     ProjectGetter.findAllUsersProjects(
     ProjectGetter.findAllUsersProjects(
       userId,
       userId,
       'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
       'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
@@ -377,8 +377,8 @@ const ProjectController = {
 
 
   projectListPage(req, res, next) {
   projectListPage(req, res, next) {
     const timer = new metrics.Timer('project-list')
     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(
     async.parallel(
       {
       {
         tags(cb) {
         tags(cb) {
@@ -617,9 +617,9 @@ const ProjectController = {
     }
     }
 
 
     let anonymous, userId, sessionUser
     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
       anonymous = false
     } else {
     } else {
       sessionUser = null
       sessionUser = null

+ 2 - 2
services/web/app/src/Features/Referal/ReferalController.js

@@ -1,9 +1,9 @@
 const ReferalHandler = require('./ReferalHandler')
 const ReferalHandler = require('./ReferalHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 
 
 module.exports = {
 module.exports = {
   bonus(req, res, next) {
   bonus(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     ReferalHandler.getReferedUsers(
     ReferalHandler.getReferedUsers(
       userId,
       userId,
       (err, referedUsers, referedUserCount) => {
       (err, referedUsers, referedUserCount) => {

+ 2 - 2
services/web/app/src/Features/Security/RateLimiterMiddleware.js

@@ -1,6 +1,6 @@
 const RateLimiter = require('../../infrastructure/RateLimiter')
 const RateLimiter = require('../../infrastructure/RateLimiter')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const LoginRateLimiter = require('./LoginRateLimiter')
 const LoginRateLimiter = require('./LoginRateLimiter')
 const settings = require('@overleaf/settings')
 const settings = require('@overleaf/settings')
 
 
@@ -17,7 +17,7 @@ const settings = require('@overleaf/settings')
 */
 */
 function rateLimit(opts) {
 function rateLimit(opts) {
   return function (req, res, next) {
   return function (req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req) || req.ip
+    const userId = SessionManager.getLoggedInUserId(req.session) || req.ip
     if (
     if (
       settings.smokeTest &&
       settings.smokeTest &&
       settings.smokeTest.userId &&
       settings.smokeTest.userId &&

+ 2 - 2
services/web/app/src/Features/Spelling/SpellingController.js

@@ -1,7 +1,7 @@
 const request = require('request')
 const request = require('request')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 
 
 const TEN_SECONDS = 1000 * 10
 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}`
     url = `/user/${userId}${url}`
     req.headers.Host = Settings.apis.spelling.host
     req.headers.Host = Settings.apis.spelling.host
     return request({
     return request({

+ 2 - 2
services/web/app/src/Features/StaticPages/HomeController.js

@@ -20,7 +20,7 @@ const Path = require('path')
 const fs = require('fs')
 const fs = require('fs')
 
 
 const ErrorController = require('../Errors/ErrorController')
 const ErrorController = require('../Errors/ErrorController')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 
 
 const homepageExists = fs.existsSync(
 const homepageExists = fs.existsSync(
   Path.resolve(__dirname + '/../../../views/external/home/v2.pug')
   Path.resolve(__dirname + '/../../../views/external/home/v2.pug')
@@ -28,7 +28,7 @@ const homepageExists = fs.existsSync(
 
 
 module.exports = HomeController = {
 module.exports = HomeController = {
   index(req, res) {
   index(req, res) {
-    if (AuthenticationController.isUserLoggedIn(req)) {
+    if (SessionManager.isUserLoggedIn(req.session)) {
       if (req.query.scribtex_path != null) {
       if (req.query.scribtex_path != null) {
         return res.redirect(`/project?scribtex_path=${req.query.scribtex_path}`)
         return res.redirect(`/project?scribtex_path=${req.query.scribtex_path}`)
       } else {
       } else {

+ 14 - 14
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 SubscriptionHandler = require('./SubscriptionHandler')
 const PlansLocator = require('./PlansLocator')
 const PlansLocator = require('./PlansLocator')
 const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder')
 const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder')
@@ -45,7 +45,7 @@ async function plansPage(req, res) {
 
 
 // get to show the recurly.js page
 // get to show the recurly.js page
 async function paymentPage(req, res) {
 async function paymentPage(req, res) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
   const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
   if (!plan) {
   if (!plan) {
     return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
     return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
@@ -95,7 +95,7 @@ async function paymentPage(req, res) {
 }
 }
 
 
 async function userSubscriptionPage(req, res) {
 async function userSubscriptionPage(req, res) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   const results = await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
   const results = await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
     user
     user
   )
   )
@@ -172,7 +172,7 @@ async function userSubscriptionPage(req, res) {
 }
 }
 
 
 function createSubscription(req, res, next) {
 function createSubscription(req, res, next) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   const recurlyTokenIds = {
   const recurlyTokenIds = {
     billing: req.body.recurly_token_id,
     billing: req.body.recurly_token_id,
     threeDSecureActionResult:
     threeDSecureActionResult:
@@ -224,7 +224,7 @@ function createSubscription(req, res, next) {
 }
 }
 
 
 function successfulSubscription(req, res, next) {
 function successfulSubscription(req, res, next) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
   return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
     user,
     user,
     function (error, { personalSubscription }) {
     function (error, { personalSubscription }) {
@@ -244,7 +244,7 @@ function successfulSubscription(req, res, next) {
 }
 }
 
 
 function cancelSubscription(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')
   logger.log({ user_id: user._id }, 'canceling subscription')
   SubscriptionHandler.cancelSubscription(user, function (err) {
   SubscriptionHandler.cancelSubscription(user, function (err) {
     if (err) {
     if (err) {
@@ -266,7 +266,7 @@ function canceledSubscription(req, res, next) {
 }
 }
 
 
 function cancelV1Subscription(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')
   logger.log({ userId }, 'canceling v1 subscription')
   V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
   V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
     if (err) {
     if (err) {
@@ -281,7 +281,7 @@ function cancelV1Subscription(req, res, next) {
 
 
 function updateSubscription(req, res, next) {
 function updateSubscription(req, res, next) {
   const origin = req && req.query ? req.query.origin : null
   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
   const planCode = req.body.plan_code
   if (planCode == null) {
   if (planCode == null) {
     const err = new Error('plan_code is not defined')
     const err = new Error('plan_code is not defined')
@@ -304,7 +304,7 @@ function updateSubscription(req, res, next) {
 }
 }
 
 
 function cancelPendingSubscriptionChange(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')
   logger.log({ user_id: user._id }, 'canceling pending subscription change')
   SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
   SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
     if (err) {
     if (err) {
@@ -322,7 +322,7 @@ function cancelPendingSubscriptionChange(req, res, next) {
 }
 }
 
 
 function updateAccountEmailAddress(req, res, next) {
 function updateAccountEmailAddress(req, res, next) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   RecurlyWrapper.updateAccountEmailAddress(
   RecurlyWrapper.updateAccountEmailAddress(
     user._id,
     user._id,
     user.email,
     user.email,
@@ -336,7 +336,7 @@ function updateAccountEmailAddress(req, res, next) {
 }
 }
 
 
 function reactivateSubscription(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')
   logger.log({ user_id: user._id }, 'reactivating subscription')
   SubscriptionHandler.reactivateSubscription(user, function (err) {
   SubscriptionHandler.reactivateSubscription(user, function (err) {
     if (err) {
     if (err) {
@@ -391,7 +391,7 @@ function recurlyCallback(req, res, next) {
 }
 }
 
 
 function renderUpgradeToAnnualPlanPage(req, res, next) {
 function renderUpgradeToAnnualPlanPage(req, res, next) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   LimitationsManager.userHasV2Subscription(
   LimitationsManager.userHasV2Subscription(
     user,
     user,
     function (err, hasSubscription, subscription) {
     function (err, hasSubscription, subscription) {
@@ -424,7 +424,7 @@ function renderUpgradeToAnnualPlanPage(req, res, next) {
 }
 }
 
 
 function processUpgradeToAnnualPlan(req, res, next) {
 function processUpgradeToAnnualPlan(req, res, next) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   const { planName } = req.body
   const { planName } = req.body
   const couponCode = Settings.coupon_codes.upgradeToAnnualPromo[planName]
   const couponCode = Settings.coupon_codes.upgradeToAnnualPromo[planName]
   const annualPlanName = `${planName}-annual`
   const annualPlanName = `${planName}-annual`
@@ -449,7 +449,7 @@ function processUpgradeToAnnualPlan(req, res, next) {
 }
 }
 
 
 async function extendTrial(req, res) {
 async function extendTrial(req, res) {
-  const user = AuthenticationController.getSessionUser(req)
+  const user = SessionManager.getSessionUser(req.session)
   const {
   const {
     subscription,
     subscription,
   } = await LimitationsManager.promises.userHasV2Subscription(user)
   } = await LimitationsManager.promises.userHasV2Subscription(user)

+ 2 - 2
services/web/app/src/Features/Subscription/SubscriptionGroupController.js

@@ -15,7 +15,7 @@ const SubscriptionGroupHandler = require('./SubscriptionGroupHandler')
 const OError = require('@overleaf/o-error')
 const OError = require('@overleaf/o-error')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const SubscriptionLocator = require('./SubscriptionLocator')
 const SubscriptionLocator = require('./SubscriptionLocator')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const _ = require('underscore')
 const _ = require('underscore')
 const async = require('async')
 const async = require('async')
 
 
@@ -45,7 +45,7 @@ module.exports = {
 
 
   removeSelfFromGroup(req, res, next) {
   removeSelfFromGroup(req, res, next) {
     const subscriptionId = req.query.subscriptionId
     const subscriptionId = req.query.subscriptionId
-    const userToRemove_id = AuthenticationController.getLoggedInUserId(req)
+    const userToRemove_id = SessionManager.getLoggedInUserId(req.session)
     return SubscriptionLocator.getSubscription(
     return SubscriptionLocator.getSubscription(
       subscriptionId,
       subscriptionId,
       function (error, subscription) {
       function (error, subscription) {

+ 5 - 5
services/web/app/src/Features/Subscription/TeamInvitesController.js

@@ -13,14 +13,14 @@
 const settings = require('@overleaf/settings')
 const settings = require('@overleaf/settings')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const TeamInvitesHandler = require('./TeamInvitesHandler')
 const TeamInvitesHandler = require('./TeamInvitesHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const SubscriptionLocator = require('./SubscriptionLocator')
 const SubscriptionLocator = require('./SubscriptionLocator')
 const ErrorController = require('../Errors/ErrorController')
 const ErrorController = require('../Errors/ErrorController')
 const EmailHelper = require('../Helpers/EmailHelper')
 const EmailHelper = require('../Helpers/EmailHelper')
 
 
 module.exports = {
 module.exports = {
   createInvite(req, res, next) {
   createInvite(req, res, next) {
-    const teamManagerId = AuthenticationController.getLoggedInUserId(req)
+    const teamManagerId = SessionManager.getLoggedInUserId(req.session)
     const subscription = req.entity
     const subscription = req.entity
     const email = EmailHelper.parseEmail(req.body.email)
     const email = EmailHelper.parseEmail(req.body.email)
     if (email == null) {
     if (email == null) {
@@ -63,7 +63,7 @@ module.exports = {
 
 
   viewInvite(req, res, next) {
   viewInvite(req, res, next) {
     const { token } = req.params
     const { token } = req.params
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     return TeamInvitesHandler.getInvite(
     return TeamInvitesHandler.getInvite(
       token,
       token,
@@ -105,7 +105,7 @@ module.exports = {
 
 
   acceptInvite(req, res, next) {
   acceptInvite(req, res, next) {
     const { token } = req.params
     const { token } = req.params
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
 
 
     return TeamInvitesHandler.acceptInvite(
     return TeamInvitesHandler.acceptInvite(
       token,
       token,
@@ -122,7 +122,7 @@ module.exports = {
   revokeInvite(req, res, next) {
   revokeInvite(req, res, next) {
     const subscription = req.entity
     const subscription = req.entity
     const email = EmailHelper.parseEmail(req.params.email)
     const email = EmailHelper.parseEmail(req.params.email)
-    const teamManagerId = AuthenticationController.getLoggedInUserId(req)
+    const teamManagerId = SessionManager.getLoggedInUserId(req.session)
     if (email == null) {
     if (email == null) {
       return res.sendStatus(400)
       return res.sendStatus(400)
     }
     }

+ 2 - 2
services/web/app/src/Features/SystemMessages/SystemMessageController.js

@@ -1,10 +1,10 @@
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const SystemMessageManager = require('./SystemMessageManager')
 const SystemMessageManager = require('./SystemMessageManager')
 
 
 const ProjectController = {
 const ProjectController = {
   getMessages(req, res, next) {
   getMessages(req, res, next) {
-    if (!AuthenticationController.isUserLoggedIn(req)) {
+    if (!SessionManager.isUserLoggedIn(req.session)) {
       // gracefully handle requests from anonymous users
       // gracefully handle requests from anonymous users
       return res.json([])
       return res.json([])
     }
     }

+ 7 - 7
services/web/app/src/Features/Tags/TagsController.js

@@ -1,5 +1,5 @@
 const TagsHandler = require('./TagsHandler')
 const TagsHandler = require('./TagsHandler')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 
 
 const TagsController = {
 const TagsController = {
@@ -21,12 +21,12 @@ const TagsController = {
   },
   },
 
 
   getAllTags(req, res, next) {
   getAllTags(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     TagsController._getTags(userId, req, res, next)
     TagsController._getTags(userId, req, res, next)
   },
   },
 
 
   createTag(req, res, next) {
   createTag(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { name } = req.body
     const { name } = req.body
     TagsHandler.createTag(userId, name, function (error, tag) {
     TagsHandler.createTag(userId, name, function (error, tag) {
       if (error != null) {
       if (error != null) {
@@ -37,7 +37,7 @@ const TagsController = {
   },
   },
 
 
   addProjectToTag(req, res, next) {
   addProjectToTag(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { tagId, projectId } = req.params
     const { tagId, projectId } = req.params
     TagsHandler.addProjectToTag(userId, tagId, projectId, function (error) {
     TagsHandler.addProjectToTag(userId, tagId, projectId, function (error) {
       if (error) {
       if (error) {
@@ -48,7 +48,7 @@ const TagsController = {
   },
   },
 
 
   removeProjectFromTag(req, res, next) {
   removeProjectFromTag(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { tagId, projectId } = req.params
     const { tagId, projectId } = req.params
     TagsHandler.removeProjectFromTag(
     TagsHandler.removeProjectFromTag(
       userId,
       userId,
@@ -64,7 +64,7 @@ const TagsController = {
   },
   },
 
 
   deleteTag(req, res, next) {
   deleteTag(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { tagId } = req.params
     const { tagId } = req.params
     TagsHandler.deleteTag(userId, tagId, function (error) {
     TagsHandler.deleteTag(userId, tagId, function (error) {
       if (error) {
       if (error) {
@@ -75,7 +75,7 @@ const TagsController = {
   },
   },
 
 
   renameTag(req, res, next) {
   renameTag(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { tagId } = req.params
     const { tagId } = req.params
     const name = req.body != null ? req.body.name : undefined
     const name = req.body != null ? req.body.name : undefined
     if (!name) {
     if (!name) {

+ 2 - 2
services/web/app/src/Features/Templates/TemplatesController.js

@@ -13,7 +13,7 @@
  */
  */
 let TemplatesController
 let TemplatesController
 const path = require('path')
 const path = require('path')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const TemplatesManager = require('./TemplatesManager')
 const TemplatesManager = require('./TemplatesManager')
 const ProjectHelper = require('../Project/ProjectHelper')
 const ProjectHelper = require('../Project/ProjectHelper')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
@@ -47,7 +47,7 @@ module.exports = TemplatesController = {
   },
   },
 
 
   createProjectFromV1Template(req, res, next) {
   createProjectFromV1Template(req, res, next) {
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
     return TemplatesManager.createProjectFromV1Template(
     return TemplatesManager.createProjectFromV1Template(
       req.body.brandVariationId,
       req.body.brandVariationId,
       req.body.compiler,
       req.body.compiler,

+ 2 - 2
services/web/app/src/Features/ThirdPartyDataStore/TpdsController.js

@@ -7,7 +7,7 @@ const logger = require('logger-sharelatex')
 const Path = require('path')
 const Path = require('path')
 const metrics = require('@overleaf/metrics')
 const metrics = require('@overleaf/metrics')
 const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
 const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const TpdsQueueManager = require('./TpdsQueueManager').promises
 const TpdsQueueManager = require('./TpdsQueueManager').promises
 
 
 module.exports = {
 module.exports = {
@@ -111,7 +111,7 @@ module.exports = {
   },
   },
 
 
   async getQueues(req, res, next) {
   async getQueues(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     try {
     try {
       res.json(await TpdsQueueManager.getQueues(userId))
       res.json(await TpdsQueueManager.getQueues(userId))
     } catch (err) {
     } catch (err) {

+ 3 - 2
services/web/app/src/Features/TokenAccess/TokenAccessController.js

@@ -1,4 +1,5 @@
 const AuthenticationController = require('../Authentication/AuthenticationController')
 const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const TokenAccessHandler = require('./TokenAccessHandler')
 const TokenAccessHandler = require('./TokenAccessHandler')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
@@ -213,7 +214,7 @@ async function checkAndGetProjectOrResponseAction(
 
 
 async function grantTokenAccessReadAndWrite(req, res, next) {
 async function grantTokenAccessReadAndWrite(req, res, next) {
   const { token } = req.params
   const { token } = req.params
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   if (!TokenAccessHandler.isReadAndWriteToken(token)) {
   if (!TokenAccessHandler.isReadAndWriteToken(token)) {
     return res.sendStatus(400)
     return res.sendStatus(400)
   }
   }
@@ -254,7 +255,7 @@ async function grantTokenAccessReadAndWrite(req, res, next) {
 
 
 async function grantTokenAccessReadOnly(req, res, next) {
 async function grantTokenAccessReadOnly(req, res, next) {
   const { token } = req.params
   const { token } = req.params
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   if (!TokenAccessHandler.isReadOnlyToken(token)) {
   if (!TokenAccessHandler.isReadOnlyToken(token)) {
     return res.sendStatus(400)
     return res.sendStatus(400)
   }
   }

+ 3 - 3
services/web/app/src/Features/Uploads/ProjectUploadController.js

@@ -18,7 +18,7 @@ const fs = require('fs')
 const Path = require('path')
 const Path = require('path')
 const FileSystemImportManager = require('./FileSystemImportManager')
 const FileSystemImportManager = require('./FileSystemImportManager')
 const ProjectUploadManager = require('./ProjectUploadManager')
 const ProjectUploadManager = require('./ProjectUploadManager')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
 const { InvalidZipFileError } = require('./ArchiveErrors')
 const { InvalidZipFileError } = require('./ArchiveErrors')
 const multer = require('multer')
 const multer = require('multer')
@@ -33,7 +33,7 @@ const upload = multer({
 module.exports = ProjectUploadController = {
 module.exports = ProjectUploadController = {
   uploadProject(req, res, next) {
   uploadProject(req, res, next) {
     const timer = new metrics.Timer('project-upload')
     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 { originalname, path } = req.file
     const name = Path.basename(originalname, '.zip')
     const name = Path.basename(originalname, '.zip')
     return ProjectUploadManager.createProjectFromZipArchive(
     return ProjectUploadManager.createProjectFromZipArchive(
@@ -82,7 +82,7 @@ module.exports = ProjectUploadController = {
         error: 'invalid_filename',
         error: 'invalid_filename',
       })
       })
     }
     }
-    const user_id = AuthenticationController.getLoggedInUserId(req)
+    const user_id = SessionManager.getLoggedInUserId(req.session)
 
 
     return FileSystemImportManager.addEntity(
     return FileSystemImportManager.addEntity(
       user_id,
       user_id,

+ 10 - 10
services/web/app/src/Features/User/UserController.js

@@ -7,7 +7,7 @@ const UserRegistrationHandler = require('./UserRegistrationHandler')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const metrics = require('@overleaf/metrics')
 const metrics = require('@overleaf/metrics')
 const AuthenticationManager = require('../Authentication/AuthenticationManager')
 const AuthenticationManager = require('../Authentication/AuthenticationManager')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const Features = require('../../infrastructure/Features')
 const Features = require('../../infrastructure/Features')
 const UserAuditLogHandler = require('./UserAuditLogHandler')
 const UserAuditLogHandler = require('./UserAuditLogHandler')
 const UserSessionsManager = require('./UserSessionsManager')
 const UserSessionsManager = require('./UserSessionsManager')
@@ -64,7 +64,7 @@ async function _ensureAffiliation(userId, emailData) {
 
 
 async function changePassword(req, res, next) {
 async function changePassword(req, res, next) {
   metrics.inc('user.password-change')
   metrics.inc('user.password-change')
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
 
 
   const user = await AuthenticationManager.promises.authenticate(
   const user = await AuthenticationManager.promises.authenticate(
     { _id: userId },
     { _id: userId },
@@ -119,7 +119,7 @@ async function changePassword(req, res, next) {
 
 
 async function clearSessions(req, res, next) {
 async function clearSessions(req, res, next) {
   metrics.inc('user.clear-sessions')
   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 user = await UserGetter.promises.getUser(userId, { email: 1 })
   const sessions = await UserSessionsManager.promises.getAllUserSessions(user, [
   const sessions = await UserSessionsManager.promises.getAllUserSessions(user, [
     req.sessionID,
     req.sessionID,
@@ -165,7 +165,7 @@ async function ensureAffiliationMiddleware(req, res, next) {
   if (!Features.hasFeature('affiliations') || !req.query.ensureAffiliation) {
   if (!Features.hasFeature('affiliations') || !req.query.ensureAffiliation) {
     return next()
     return next()
   }
   }
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   try {
   try {
     user = await UserGetter.promises.getUser(userId)
     user = await UserGetter.promises.getUser(userId)
   } catch (error) {
   } catch (error) {
@@ -183,7 +183,7 @@ const UserController = {
   clearSessions: expressify(clearSessions),
   clearSessions: expressify(clearSessions),
 
 
   tryDeleteUser(req, res, next) {
   tryDeleteUser(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const { password } = req.body
     const { password } = req.body
 
 
     if (password == null || password === '') {
     if (password == null || password === '') {
@@ -256,7 +256,7 @@ const UserController = {
   },
   },
 
 
   unsubscribe(req, res, next) {
   unsubscribe(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     UserGetter.getUser(userId, (err, user) => {
     UserGetter.getUser(userId, (err, user) => {
       if (err != null) {
       if (err != null) {
         return next(err)
         return next(err)
@@ -274,7 +274,7 @@ const UserController = {
   },
   },
 
 
   updateUserSettings(req, res, next) {
   updateUserSettings(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     User.findById(userId, (err, user) => {
     User.findById(userId, (err, user) => {
       if (err != null || user == null) {
       if (err != null || user == null) {
         logger.err({ err, userId }, 'problem updaing user settings')
         logger.err({ err, userId }, 'problem updaing user settings')
@@ -341,7 +341,7 @@ const UserController = {
           req.externalAuthenticationSystemUsed()
           req.externalAuthenticationSystemUsed()
         ) {
         ) {
           // end here, don't update email
           // end here, don't update email
-          AuthenticationController.setInSessionUser(req, {
+          SessionManager.setInSessionUser(req.session, {
             first_name: user.first_name,
             first_name: user.first_name,
             last_name: user.last_name,
             last_name: user.last_name,
           })
           })
@@ -382,7 +382,7 @@ const UserController = {
                 )
                 )
                 return res.sendStatus(500)
                 return res.sendStatus(500)
               }
               }
-              AuthenticationController.setInSessionUser(req, {
+              SessionManager.setInSessionUser(req.session, {
                 email: user.email,
                 email: user.email,
                 first_name: user.first_name,
                 first_name: user.first_name,
                 last_name: user.last_name,
                 last_name: user.last_name,
@@ -403,7 +403,7 @@ const UserController = {
 
 
   doLogout(req, cb) {
   doLogout(req, cb) {
     metrics.inc('user.logout')
     metrics.inc('user.logout')
-    const user = AuthenticationController.getSessionUser(req)
+    const user = SessionManager.getSessionUser(req.session)
     logger.log({ user }, 'logging out')
     logger.log({ user }, 'logging out')
     const sessionId = req.sessionID
     const sessionId = req.sessionID
     if (typeof req.logout === 'function') {
     if (typeof req.logout === 'function') {

+ 10 - 10
services/web/app/src/Features/User/UserEmailsController.js

@@ -1,5 +1,5 @@
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const UserGetter = require('./UserGetter')
 const UserGetter = require('./UserGetter')
 const UserUpdater = require('./UserUpdater')
 const UserUpdater = require('./UserUpdater')
 const UserSessionsManager = require('./UserSessionsManager')
 const UserSessionsManager = require('./UserSessionsManager')
@@ -24,7 +24,7 @@ async function _sendSecurityAlertEmail(user, email) {
 }
 }
 
 
 async function add(req, res, next) {
 async function add(req, res, next) {
-  const userId = AuthenticationController.getLoggedInUserId(req)
+  const userId = SessionManager.getLoggedInUserId(req.session)
   const email = EmailHelper.parseEmail(req.body.email)
   const email = EmailHelper.parseEmail(req.body.email)
   if (!email) {
   if (!email) {
     return res.sendStatus(422)
     return res.sendStatus(422)
@@ -62,7 +62,7 @@ async function add(req, res, next) {
 }
 }
 
 
 function resendConfirmation(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)
   const email = EmailHelper.parseEmail(req.body.email)
   if (!email) {
   if (!email) {
     return res.sendStatus(422)
     return res.sendStatus(422)
@@ -88,7 +88,7 @@ function resendConfirmation(req, res, next) {
 }
 }
 
 
 function sendReconfirmation(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)
   const email = EmailHelper.parseEmail(req.body.email)
   if (!email) {
   if (!email) {
     return res.sendStatus(400)
     return res.sendStatus(400)
@@ -115,7 +115,7 @@ function sendReconfirmation(req, res, next) {
 
 
 const UserEmailsController = {
 const UserEmailsController = {
   list(req, res, next) {
   list(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     UserGetter.getUserFullEmails(userId, function (error, fullEmails) {
     UserGetter.getUserFullEmails(userId, function (error, fullEmails) {
       if (error) {
       if (error) {
         return next(error)
         return next(error)
@@ -127,7 +127,7 @@ const UserEmailsController = {
   add: expressify(add),
   add: expressify(add),
 
 
   remove(req, res, next) {
   remove(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const email = EmailHelper.parseEmail(req.body.email)
     const email = EmailHelper.parseEmail(req.body.email)
     if (!email) {
     if (!email) {
       return res.sendStatus(422)
       return res.sendStatus(422)
@@ -142,7 +142,7 @@ const UserEmailsController = {
   },
   },
 
 
   setDefault(req, res, next) {
   setDefault(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const email = EmailHelper.parseEmail(req.body.email)
     const email = EmailHelper.parseEmail(req.body.email)
     if (!email) {
     if (!email) {
       return res.sendStatus(422)
       return res.sendStatus(422)
@@ -161,8 +161,8 @@ const UserEmailsController = {
         if (err) {
         if (err) {
           return UserEmailsController._handleEmailError(err, req, res, next)
           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(
         UserSessionsManager.revokeAllUserSessions(
           user,
           user,
           [req.sessionID],
           [req.sessionID],
@@ -180,7 +180,7 @@ const UserEmailsController = {
   },
   },
 
 
   endorse(req, res, next) {
   endorse(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const email = EmailHelper.parseEmail(req.body.email)
     const email = EmailHelper.parseEmail(req.body.email)
     if (!email) {
     if (!email) {
       return res.sendStatus(422)
       return res.sendStatus(422)

+ 2 - 2
services/web/app/src/Features/User/UserInfoController.js

@@ -1,11 +1,11 @@
 let UserController
 let UserController
 const UserGetter = require('./UserGetter')
 const UserGetter = require('./UserGetter')
-const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const { ObjectId } = require('mongodb')
 const { ObjectId } = require('mongodb')
 
 
 module.exports = UserController = {
 module.exports = UserController = {
   getLoggedInUsersPersonalInfo(req, res, next) {
   getLoggedInUsersPersonalInfo(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     if (!userId) {
     if (!userId) {
       return next(new Error('User is not logged in'))
       return next(new Error('User is not logged in'))
     }
     }

+ 3 - 2
services/web/app/src/Features/User/UserPagesController.js

@@ -4,6 +4,7 @@ const UserSessionsManager = require('./UserSessionsManager')
 const logger = require('logger-sharelatex')
 const logger = require('logger-sharelatex')
 const Settings = require('@overleaf/settings')
 const Settings = require('@overleaf/settings')
 const AuthenticationController = require('../Authentication/AuthenticationController')
 const AuthenticationController = require('../Authentication/AuthenticationController')
+const SessionManager = require('../Authentication/SessionManager')
 const _ = require('lodash')
 const _ = require('lodash')
 
 
 const UserPagesController = {
 const UserPagesController = {
@@ -63,7 +64,7 @@ const UserPagesController = {
   },
   },
 
 
   settingsPage(req, res, next) {
   settingsPage(req, res, next) {
-    const userId = AuthenticationController.getLoggedInUserId(req)
+    const userId = SessionManager.getLoggedInUserId(req.session)
     const reconfirmationRemoveEmail = req.query.remove
     const reconfirmationRemoveEmail = req.query.remove
     // SSO
     // SSO
     const ssoError = req.session.ssoError
     const ssoError = req.session.ssoError
@@ -134,7 +135,7 @@ const UserPagesController = {
   },
   },
 
 
   sessionsPage(req, res, next) {
   sessionsPage(req, res, next) {
-    const user = AuthenticationController.getSessionUser(req)
+    const user = SessionManager.getSessionUser(req.session)
     logger.log({ userId: user._id }, 'loading sessions page')
     logger.log({ userId: user._id }, 'loading sessions page')
     UserSessionsManager.getAllUserSessions(
     UserSessionsManager.getAllUserSessions(
       user,
       user,

+ 2 - 2
services/web/app/src/Features/UserMembership/UserMembershipController.js

@@ -10,7 +10,7 @@
  * DS207: Consider shorter variations of null checks
  * DS207: Consider shorter variations of null checks
  * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  * 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 UserMembershipHandler = require('./UserMembershipHandler')
 const Errors = require('../Errors/Errors')
 const Errors = require('../Errors/Errors')
 const EmailHelper = require('../Helpers/EmailHelper')
 const EmailHelper = require('../Helpers/EmailHelper')
@@ -104,7 +104,7 @@ module.exports = {
       return next(new Errors.NotFoundError('Cannot remove users from entity'))
       return next(new Errors.NotFoundError('Cannot remove users from entity'))
     }
     }
 
 
-    const loggedInUserId = AuthenticationController.getLoggedInUserId(req)
+    const loggedInUserId = SessionManager.getLoggedInUserId(req.session)
     if (loggedInUserId === userId) {
     if (loggedInUserId === userId) {
       return res.status(400).json({
       return res.status(400).json({
         error: {
         error: {

+ 8 - 9
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 IS_DEV_ENV = ['development', 'test'].includes(process.env.NODE_ENV)
 
 
 const Features = require('./Features')
 const Features = require('./Features')
-const AuthenticationController = require('../Features/Authentication/AuthenticationController')
+const SessionManager = require('../Features/Authentication/SessionManager')
 const PackageVersions = require('./PackageVersions')
 const PackageVersions = require('./PackageVersions')
 const Modules = require('./Modules')
 const Modules = require('./Modules')
 const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution')
 const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution')
@@ -62,7 +62,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
     const cdnAvailable =
     const cdnAvailable =
       Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
       Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
     const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked
     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) {
     if (cdnBlocked && req.session.cdnBlocked == null) {
       logger.log(
       logger.log(
         { user_id: userId, ip: req != null ? req.ip : undefined },
         { 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) {
   webRouter.use(function (req, res, next) {
     res.locals.getUserEmail = function () {
     res.locals.getUserEmail = function () {
-      const user = AuthenticationController.getSessionUser(req)
+      const user = SessionManager.getSessionUser(req.session)
       const email = (user != null ? user.email : undefined) || ''
       const email = (user != null ? user.email : undefined) || ''
       return email
       return email
     }
     }
@@ -237,7 +237,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
   webRouter.use(function (req, res, next) {
   webRouter.use(function (req, res, next) {
     res.locals.buildReferalUrl = function (referalMedium) {
     res.locals.buildReferalUrl = function (referalMedium) {
       let url = Settings.siteUrl
       let url = Settings.siteUrl
-      const currentUser = AuthenticationController.getSessionUser(req)
+      const currentUser = SessionManager.getSessionUser(req.session)
       if (
       if (
         currentUser != null &&
         currentUser != null &&
         (currentUser != null ? currentUser.referal_id : undefined) != null
         (currentUser != null ? currentUser.referal_id : undefined) != null
@@ -247,7 +247,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
       return url
       return url
     }
     }
     res.locals.getReferalId = function () {
     res.locals.getReferalId = function () {
-      const currentUser = AuthenticationController.getSessionUser(req)
+      const currentUser = SessionManager.getSessionUser(req.session)
       if (
       if (
         currentUser != null &&
         currentUser != null &&
         (currentUser != null ? currentUser.referal_id : undefined) != null
         (currentUser != null ? currentUser.referal_id : undefined) != null
@@ -277,7 +277,7 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
   })
   })
 
 
   webRouter.use(function (req, res, next) {
   webRouter.use(function (req, res, next) {
-    const currentUser = AuthenticationController.getSessionUser(req)
+    const currentUser = SessionManager.getSessionUser(req.session)
     if (currentUser != null) {
     if (currentUser != null) {
       res.locals.user = {
       res.locals.user = {
         email: currentUser.email,
         email: currentUser.email,
@@ -290,9 +290,8 @@ module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
 
 
   webRouter.use(function (req, res, next) {
   webRouter.use(function (req, res, next) {
     res.locals.getLoggedInUserId = () =>
     res.locals.getLoggedInUserId = () =>
-      AuthenticationController.getLoggedInUserId(req)
-    res.locals.getSessionUser = () =>
-      AuthenticationController.getSessionUser(req)
+      SessionManager.getLoggedInUserId(req.session)
+    res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
     next()
     next()
   })
   })
 
 

+ 6 - 5
services/web/app/src/infrastructure/Server.js

@@ -37,6 +37,7 @@ const ErrorController = require('../Features/Errors/ErrorController')
 const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
 const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
 const UserSessionsManager = require('../Features/User/UserSessionsManager')
 const UserSessionsManager = require('../Features/User/UserSessionsManager')
 const AuthenticationController = require('../Features/Authentication/AuthenticationController')
 const AuthenticationController = require('../Features/Authentication/AuthenticationController')
+const SessionManager = require('../Features/Authentication/SessionManager')
 
 
 const STATIC_CACHE_AGE = Settings.cacheStaticAssets
 const STATIC_CACHE_AGE = Settings.cacheStaticAssets
   ? oneDayInMilliseconds * 365
   ? oneDayInMilliseconds * 365
@@ -164,9 +165,9 @@ webRouter.use(translations.setLangBasedOnDomainMiddleware)
 webRouter.use(function (req, res, next) {
 webRouter.use(function (req, res, next) {
   if (!req.session.noSessionCallback) {
   if (!req.session.noSessionCallback) {
     req.session.touch()
     req.session.touch()
-    if (AuthenticationController.isUserLoggedIn(req)) {
+    if (SessionManager.isUserLoggedIn(req.session)) {
       UserSessionsManager.touch(
       UserSessionsManager.touch(
-        AuthenticationController.getSessionUser(req),
+        SessionManager.getSessionUser(req.session),
         err => {
         err => {
           if (err) {
           if (err) {
             logger.err({ err }, 'error extending user session')
             logger.err({ err }, 'error extending user session')
@@ -187,8 +188,8 @@ webRouter.use(function (req, res, next) {
   if (Settings.siteIsOpen) {
   if (Settings.siteIsOpen) {
     next()
     next()
   } else if (
   } else if (
-    AuthenticationController.getSessionUser(req) &&
-    AuthenticationController.getSessionUser(req).isAdmin
+    SessionManager.getSessionUser(req.session) &&
+    SessionManager.getSessionUser(req.session).isAdmin
   ) {
   ) {
     next()
     next()
   } else {
   } else {
@@ -211,7 +212,7 @@ webRouter.use(AuthenticationController.validateAdmin)
 // add security headers using Helmet
 // add security headers using Helmet
 const noCacheMiddleware = require('nocache')()
 const noCacheMiddleware = require('nocache')()
 webRouter.use(function (req, res, next) {
 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}$')
   const isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$')
   if (isLoggedIn || isProjectPage) {
   if (isLoggedIn || isProjectPage) {
     noCacheMiddleware(req, res, next)
     noCacheMiddleware(req, res, next)

+ 2 - 1
services/web/app/src/router.js

@@ -11,6 +11,7 @@ const UploadsRouter = require('./Features/Uploads/UploadsRouter')
 const metrics = require('@overleaf/metrics')
 const metrics = require('@overleaf/metrics')
 const ReferalController = require('./Features/Referal/ReferalController')
 const ReferalController = require('./Features/Referal/ReferalController')
 const AuthenticationController = require('./Features/Authentication/AuthenticationController')
 const AuthenticationController = require('./Features/Authentication/AuthenticationController')
+const SessionManager = require('./Features/Authentication/SessionManager')
 const TagsController = require('./Features/Tags/TagsController')
 const TagsController = require('./Features/Tags/TagsController')
 const NotificationsController = require('./Features/Notifications/NotificationsController')
 const NotificationsController = require('./Features/Notifications/NotificationsController')
 const CollaboratorsRouter = require('./Features/Collaborators/CollaboratorsRouter')
 const CollaboratorsRouter = require('./Features/Collaborators/CollaboratorsRouter')
@@ -923,7 +924,7 @@ function initialize(webRouter, privateApiRouter, publicApiRouter) {
 
 
   webRouter.get('/chrome', function (req, res, next) {
   webRouter.get('/chrome', function (req, res, next) {
     // Match v1 behaviour - this is used for a Chrome web app
     // Match v1 behaviour - this is used for a Chrome web app
-    if (AuthenticationController.isUserLoggedIn(req)) {
+    if (SessionManager.isUserLoggedIn(req.session)) {
       res.redirect('/project')
       res.redirect('/project')
     } else {
     } else {
       res.redirect('/register')
       res.redirect('/register')

+ 2 - 1
services/web/modules/launchpad/app/src/LaunchpadController.js

@@ -24,6 +24,7 @@ const _ = require('underscore')
 const UserGetter = require('../../../../app/src/Features/User/UserGetter')
 const UserGetter = require('../../../../app/src/Features/User/UserGetter')
 const { User } = require('../../../../app/src/models/User')
 const { User } = require('../../../../app/src/models/User')
 const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController')
 const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController')
+const SessionManager = require('../../../../app/src/Features/Authentication/SessionManager')
 
 
 module.exports = LaunchpadController = {
 module.exports = LaunchpadController = {
   _getAuthMethod() {
   _getAuthMethod() {
@@ -39,7 +40,7 @@ module.exports = LaunchpadController = {
   launchpadPage(req, res, next) {
   launchpadPage(req, res, next) {
     // TODO: check if we're using external auth?
     // TODO: check if we're using external auth?
     //   * how does all this work with ldap and saml?
     //   * how does all this work with ldap and saml?
-    const sessionUser = AuthenticationController.getSessionUser(req)
+    const sessionUser = SessionManager.getSessionUser(req.session)
     const authMethod = LaunchpadController._getAuthMethod()
     const authMethod = LaunchpadController._getAuthMethod()
     return LaunchpadController._atLeastOneAdminExists(function (
     return LaunchpadController._atLeastOneAdminExists(function (
       err,
       err,

+ 3 - 6
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/Features/User/UserGetter': (this.UserGetter = {}),
         '../../../../app/src/models/User': { User: this.User },
         '../../../../app/src/models/User': { User: this.User },
         '../../../../app/src/Features/Authentication/AuthenticationController': (this.AuthenticationController = {}),
         '../../../../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 () {
     describe('when the user is not logged in', function () {
       beforeEach(function () {
       beforeEach(function () {
-        this.AuthenticationController.getSessionUser = sinon
-          .stub()
-          .returns(null)
+        this.SessionManager.getSessionUser = sinon.stub().returns(null)
         return (this.res.render = sinon.stub())
         return (this.res.render = sinon.stub())
       })
       })
 
 
@@ -134,9 +133,7 @@ describe('LaunchpadController', function () {
           _id: 'abcd',
           _id: 'abcd',
           email: 'abcd@example.com',
           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._atLeastOneAdminExists.callsArgWith(0, null, true)
         this.res.render = sinon.stub()
         this.res.render = sinon.stub()
         return (this.res.redirect = sinon.stub())
         return (this.res.redirect = sinon.stub())

+ 4 - 5
services/web/test/unit/src/Analytics/AnalyticsControllerTests.js

@@ -8,7 +8,7 @@ const sinon = require('sinon')
 
 
 describe('AnalyticsController', function () {
 describe('AnalyticsController', function () {
   beforeEach(function () {
   beforeEach(function () {
-    this.AuthenticationController = { getLoggedInUserId: sinon.stub() }
+    this.SessionManager = { getLoggedInUserId: sinon.stub() }
 
 
     this.AnalyticsManager = {
     this.AnalyticsManager = {
       updateEditingSession: sinon.stub(),
       updateEditingSession: sinon.stub(),
@@ -22,8 +22,7 @@ describe('AnalyticsController', function () {
     this.controller = SandboxedModule.require(modulePath, {
     this.controller = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
         './AnalyticsManager': this.AnalyticsManager,
         './AnalyticsManager': this.AnalyticsManager,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../../infrastructure/Features': this.Features,
         '../../infrastructure/Features': this.Features,
         '../../infrastructure/GeoIpLookup': (this.GeoIpLookup = {
         '../../infrastructure/GeoIpLookup': (this.GeoIpLookup = {
           getDetails: sinon.stub(),
           getDetails: sinon.stub(),
@@ -50,7 +49,7 @@ describe('AnalyticsController', function () {
     })
     })
 
 
     it('delegates to the AnalyticsManager', function (done) {
     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.controller.updateEditingSession(this.req, this.res)
 
 
       this.AnalyticsManager.updateEditingSession
       this.AnalyticsManager.updateEditingSession
@@ -73,7 +72,7 @@ describe('AnalyticsController', function () {
     })
     })
 
 
     it('should use the user_id', function (done) {
     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.controller.recordEvent(this.req, this.res)
       this.AnalyticsManager.recordEvent
       this.AnalyticsManager.recordEvent
         .calledWith('1234', this.req.params.event, this.req.body)
         .calledWith('1234', this.req.params.event, this.req.body)

+ 33 - 132
services/web/test/unit/src/Authentication/AuthenticationControllerTests.js

@@ -15,6 +15,20 @@ describe('AuthenticationController', function () {
     this.httpAuthUsers = {
     this.httpAuthUsers = {
       'valid-test-user': Math.random().toString(16).slice(2),
       '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, {
     this.AuthenticationController = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
         '../User/UserAuditLogHandler': (this.UserAuditLogHandler = {
         '../User/UserAuditLogHandler': (this.UserAuditLogHandler = {
@@ -72,25 +86,16 @@ describe('AuthenticationController', function () {
         '../Helpers/UrlHelper': (this.UrlHelper = {
         '../Helpers/UrlHelper': (this.UrlHelper = {
           getSafeRedirectPath: sinon.stub(),
           getSafeRedirectPath: sinon.stub(),
         }),
         }),
+        './SessionManager': (this.SessionManager = {
+          isUserLoggedIn: sinon.stub().returns(true),
+          getSessionUser: sinon.stub().returns(this.user),
+        }),
       },
       },
     })
     })
     this.UrlHelper.getSafeRedirectPath
     this.UrlHelper.getSafeRedirectPath
       .withArgs('https://evil.com')
       .withArgs('https://evil.com')
       .returns(undefined)
       .returns(undefined)
     this.UrlHelper.getSafeRedirectPath.returnsArg(0)
     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 () {
   afterEach(function () {
@@ -116,119 +121,53 @@ describe('AuthenticationController', function () {
 
 
     it('should skip when adminDomains are not configured', function (done) {
     it('should skip when adminDomains are not configured', function (done) {
       this.Settings.adminDomains = []
       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.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
         expect(err).to.not.exist
         done()
         done()
       })
       })
     })
     })
 
 
     it('should skip non-admin user', function (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.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
         expect(err).to.not.exist
         done()
         done()
       })
       })
     })
     })
 
 
     it('should permit an admin with the right doman', function (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.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
         expect(err).to.not.exist
         done()
         done()
       })
       })
     })
     })
 
 
     it('should block an admin with a missing email', function (done) {
     it('should block an admin with a missing email', function (done) {
-      this.AuthenticationController.getSessionUser = sinon
+      this.SessionManager.getSessionUser = sinon
         .stub()
         .stub()
         .returns({ isAdmin: true })
         .returns({ isAdmin: true })
       this.AuthenticationController.validateAdmin(this.req, this.res, err => {
       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
         expect(err).to.exist
         done()
         done()
       })
       })
     })
     })
 
 
     it('should block an admin with a bad domain', function (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.validateAdmin(this.req, this.res, err => {
-        this.AuthenticationController.getSessionUser.called.should.equal(true)
+        this.SessionManager.getSessionUser.called.should.equal(true)
         expect(err).to.exist
         expect(err).to.exist
         done()
         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 () {
   describe('passportLogin', function () {
     beforeEach(function () {
     beforeEach(function () {
       this.info = null
       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 () {
   describe('requireLogin', function () {
     beforeEach(function () {
     beforeEach(function () {
       this.user = {
       this.user = {
@@ -517,6 +413,7 @@ describe('AuthenticationController', function () {
         this.req.session = {}
         this.req.session = {}
         this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
         this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
         this.req.query = {}
         this.req.query = {}
+        this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         this.middleware(this.req, this.res, this.next)
         this.middleware(this.req, this.res, this.next)
       })
       })
 
 
@@ -712,6 +609,7 @@ describe('AuthenticationController', function () {
     describe('with no login credentials', function () {
     describe('with no login credentials', function () {
       beforeEach(function () {
       beforeEach(function () {
         this.req.session = {}
         this.req.session = {}
+        this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         this.AuthenticationController.requireGlobalLogin(
         this.AuthenticationController.requireGlobalLogin(
           this.req,
           this.req,
           this.res,
           this.res,
@@ -815,6 +713,7 @@ describe('AuthenticationController', function () {
     describe('they have come directly to the url', function () {
     describe('they have come directly to the url', function () {
       beforeEach(function () {
       beforeEach(function () {
         this.req.query = {}
         this.req.query = {}
+        this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         this.middleware(this.req, this.res, this.next)
         this.middleware(this.req, this.res, this.next)
       })
       })
 
 
@@ -831,6 +730,7 @@ describe('AuthenticationController', function () {
     describe('they have come via a templates link', function () {
     describe('they have come via a templates link', function () {
       beforeEach(function () {
       beforeEach(function () {
         this.req.query.zipUrl = 'something'
         this.req.query.zipUrl = 'something'
+        this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         this.middleware(this.req, this.res, this.next)
         this.middleware(this.req, this.res, this.next)
       })
       })
 
 
@@ -847,6 +747,7 @@ describe('AuthenticationController', function () {
     describe('they have been invited to a project', function () {
     describe('they have been invited to a project', function () {
       beforeEach(function () {
       beforeEach(function () {
         this.req.query.project_name = 'something'
         this.req.query.project_name = 'something'
+        this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         this.middleware(this.req, this.res, this.next)
         this.middleware(this.req, this.res, this.next)
       })
       })
 
 

+ 114 - 0
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)
+    })
+  })
+})

+ 18 - 22
services/web/test/unit/src/Authorization/AuthorizationMiddlewareTests.js

@@ -11,7 +11,8 @@ describe('AuthorizationMiddleware', function () {
     this.userId = 'user-id-123'
     this.userId = 'user-id-123'
     this.project_id = 'project-id-123'
     this.project_id = 'project-id-123'
     this.token = 'some-token'
     this.token = 'some-token'
-    this.AuthenticationController = {
+    this.AuthenticationController = {}
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.userId),
       getLoggedInUserId: sinon.stub().returns(this.userId),
       isUserLoggedIn: sinon.stub().returns(true),
       isUserLoggedIn: sinon.stub().returns(true),
     }
     }
@@ -35,6 +36,7 @@ describe('AuthorizationMiddleware', function () {
         '../Errors/HttpErrorHandler': this.HttpErrorHandler,
         '../Errors/HttpErrorHandler': this.HttpErrorHandler,
         '../Authentication/AuthenticationController': this
         '../Authentication/AuthenticationController': this
           .AuthenticationController,
           .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
       },
       },
     })
     })
@@ -49,9 +51,7 @@ describe('AuthorizationMiddleware', function () {
     })
     })
 
 
     it('should get the user from session', function (done) {
     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) => {
       this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => {
         expect(err).to.not.exist
         expect(err).to.not.exist
         expect(userId).to.equal('1234')
         expect(userId).to.equal('1234')
@@ -60,9 +60,7 @@ describe('AuthorizationMiddleware', function () {
     })
     })
 
 
     it('should get oauth_user from request', function (done) {
     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.req.oauth_user = { _id: '5678' }
       this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => {
       this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => {
         expect(err).to.not.exist
         expect(err).to.not.exist
@@ -72,9 +70,7 @@ describe('AuthorizationMiddleware', function () {
     })
     })
 
 
     it('should fall back to null', function (done) {
     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.req.oauth_user = undefined
       this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => {
       this.AuthorizationMiddleware._getUserId(this.req, (err, userId) => {
         expect(err).to.not.exist
         expect(err).to.not.exist
@@ -117,7 +113,7 @@ describe('AuthorizationMiddleware', function () {
 
 
         describe('with logged in user', function () {
         describe('with logged in user', function () {
           beforeEach(function () {
           beforeEach(function () {
-            this.AuthenticationController.getLoggedInUserId.returns(this.userId)
+            this.SessionManager.getLoggedInUserId.returns(this.userId)
           })
           })
 
 
           describe('when user has permission', function () {
           describe('when user has permission', function () {
@@ -161,7 +157,7 @@ describe('AuthorizationMiddleware', function () {
         describe('with anonymous user', function () {
         describe('with anonymous user', function () {
           describe('when user has permission', function () {
           describe('when user has permission', function () {
             beforeEach(function () {
             beforeEach(function () {
-              this.AuthenticationController.getLoggedInUserId.returns(null)
+              this.SessionManager.getLoggedInUserId.returns(null)
               this.AuthorizationManager[managerMethod]
               this.AuthorizationManager[managerMethod]
                 .withArgs(null, this.project_id, this.token)
                 .withArgs(null, this.project_id, this.token)
                 .yields(null, true)
                 .yields(null, true)
@@ -179,7 +175,7 @@ describe('AuthorizationMiddleware', function () {
 
 
           describe("when user doesn't have permission", function () {
           describe("when user doesn't have permission", function () {
             beforeEach(function () {
             beforeEach(function () {
-              this.AuthenticationController.getLoggedInUserId.returns(null)
+              this.SessionManager.getLoggedInUserId.returns(null)
               this.AuthorizationManager[managerMethod]
               this.AuthorizationManager[managerMethod]
                 .withArgs(null, this.project_id, this.token)
                 .withArgs(null, this.project_id, this.token)
                 .yields(null, false)
                 .yields(null, false)
@@ -244,7 +240,7 @@ describe('AuthorizationMiddleware', function () {
 
 
     describe('with logged in user', function () {
     describe('with logged in user', function () {
       beforeEach(function () {
       beforeEach(function () {
-        this.AuthenticationController.getLoggedInUserId.returns(this.userId)
+        this.SessionManager.getLoggedInUserId.returns(this.userId)
       })
       })
 
 
       describe('when user has permission', function () {
       describe('when user has permission', function () {
@@ -284,7 +280,7 @@ describe('AuthorizationMiddleware', function () {
     describe('with anonymous user', function () {
     describe('with anonymous user', function () {
       describe('when user has permission', function () {
       describe('when user has permission', function () {
         beforeEach(function () {
         beforeEach(function () {
-          this.AuthenticationController.getLoggedInUserId.returns(null)
+          this.SessionManager.getLoggedInUserId.returns(null)
           this.AuthorizationManager.canUserAdminProject
           this.AuthorizationManager.canUserAdminProject
             .withArgs(null, this.project_id, this.token)
             .withArgs(null, this.project_id, this.token)
             .yields(null, true)
             .yields(null, true)
@@ -302,7 +298,7 @@ describe('AuthorizationMiddleware', function () {
 
 
       describe("when user doesn't have permission", function () {
       describe("when user doesn't have permission", function () {
         beforeEach(function () {
         beforeEach(function () {
-          this.AuthenticationController.getLoggedInUserId.returns(null)
+          this.SessionManager.getLoggedInUserId.returns(null)
           this.AuthorizationManager.canUserAdminProject
           this.AuthorizationManager.canUserAdminProject
             .withArgs(null, this.project_id, this.token)
             .withArgs(null, this.project_id, this.token)
             .yields(null, false)
             .yields(null, false)
@@ -345,7 +341,7 @@ describe('AuthorizationMiddleware', function () {
 
 
     describe('with logged in user', function () {
     describe('with logged in user', function () {
       beforeEach(function () {
       beforeEach(function () {
-        this.AuthenticationController.getLoggedInUserId.returns(this.userId)
+        this.SessionManager.getLoggedInUserId.returns(this.userId)
       })
       })
 
 
       describe('when user has permission', function () {
       describe('when user has permission', function () {
@@ -389,7 +385,7 @@ describe('AuthorizationMiddleware', function () {
     describe('with anonymous user', function () {
     describe('with anonymous user', function () {
       describe('when user has permission', function () {
       describe('when user has permission', function () {
         beforeEach(function () {
         beforeEach(function () {
-          this.AuthenticationController.getLoggedInUserId.returns(null)
+          this.SessionManager.getLoggedInUserId.returns(null)
           this.AuthorizationManager.isUserSiteAdmin
           this.AuthorizationManager.isUserSiteAdmin
             .withArgs(null)
             .withArgs(null)
             .yields(null, true)
             .yields(null, true)
@@ -407,7 +403,7 @@ describe('AuthorizationMiddleware', function () {
 
 
       describe("when user doesn't have permission", function () {
       describe("when user doesn't have permission", function () {
         beforeEach(function () {
         beforeEach(function () {
-          this.AuthenticationController.getLoggedInUserId.returns(null)
+          this.SessionManager.getLoggedInUserId.returns(null)
           this.AuthorizationManager.isUserSiteAdmin
           this.AuthorizationManager.isUserSiteAdmin
             .withArgs(null)
             .withArgs(null)
             .yields(null, false)
             .yields(null, false)
@@ -486,7 +482,7 @@ describe('AuthorizationMiddleware', function () {
 
 
     describe('with logged in user', function () {
     describe('with logged in user', function () {
       beforeEach(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 () {
       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', function () {
         describe('when user has permission to access all projects', function () {
         describe('when user has permission to access all projects', function () {
           beforeEach(function () {
           beforeEach(function () {
-            this.AuthenticationController.getLoggedInUserId.returns(null)
+            this.SessionManager.getLoggedInUserId.returns(null)
             this.AuthorizationManager.canUserReadProject
             this.AuthorizationManager.canUserReadProject
               .withArgs(null, 'project1', this.token)
               .withArgs(null, 'project1', this.token)
               .yields(null, true)
               .yields(null, true)
@@ -558,7 +554,7 @@ describe('AuthorizationMiddleware', function () {
 
 
         describe("when user doesn't have permission to access one of the projects", function () {
         describe("when user doesn't have permission to access one of the projects", function () {
           beforeEach(function () {
           beforeEach(function () {
-            this.AuthenticationController.getLoggedInUserId.returns(null)
+            this.SessionManager.getLoggedInUserId.returns(null)
             this.AuthorizationManager.canUserReadProject
             this.AuthorizationManager.canUserReadProject
               .withArgs(null, 'project1', this.token)
               .withArgs(null, 'project1', this.token)
               .yields(null, true)
               .yields(null, true)

+ 2 - 3
services/web/test/unit/src/Chat/ChatControllerTests.js

@@ -28,7 +28,7 @@ describe('ChatController', function () {
     this.settings = {}
     this.settings = {}
     this.ChatApiHandler = {}
     this.ChatApiHandler = {}
     this.EditorRealTimeController = { emitToRoom: sinon.stub() }
     this.EditorRealTimeController = { emitToRoom: sinon.stub() }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user_id),
       getLoggedInUserId: sinon.stub().returns(this.user_id),
     }
     }
     this.ChatController = SandboxedModule.require(modulePath, {
     this.ChatController = SandboxedModule.require(modulePath, {
@@ -36,8 +36,7 @@ describe('ChatController', function () {
         '@overleaf/settings': this.settings,
         '@overleaf/settings': this.settings,
         './ChatApiHandler': this.ChatApiHandler,
         './ChatApiHandler': this.ChatApiHandler,
         '../Editor/EditorRealTimeController': this.EditorRealTimeController,
         '../Editor/EditorRealTimeController': this.EditorRealTimeController,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../User/UserInfoManager': (this.UserInfoManager = {}),
         '../User/UserInfoManager': (this.UserInfoManager = {}),
         '../User/UserInfoController': (this.UserInfoController = {}),
         '../User/UserInfoController': (this.UserInfoController = {}),
       },
       },

+ 2 - 3
services/web/test/unit/src/Collaborators/CollaboratorsControllerTests.js

@@ -41,7 +41,7 @@ describe('CollaboratorsController', function () {
         removeProjectFromAllTags: sinon.stub().resolves(),
         removeProjectFromAllTags: sinon.stub().resolves(),
       },
       },
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
     }
     }
@@ -60,8 +60,7 @@ describe('CollaboratorsController', function () {
         '../Editor/EditorRealTimeController': this.EditorRealTimeController,
         '../Editor/EditorRealTimeController': this.EditorRealTimeController,
         '../../Features/Errors/HttpErrorHandler': this.HttpErrorHandler,
         '../../Features/Errors/HttpErrorHandler': this.HttpErrorHandler,
         '../Tags/TagsHandler': this.TagsHandler,
         '../Tags/TagsHandler': this.TagsHandler,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
       },
       },
     })
     })
   })
   })

+ 4 - 5
services/web/test/unit/src/Compile/CompileControllerTests.js

@@ -51,7 +51,7 @@ describe('CompileController', function () {
     this.ClsiCookieManager = {
     this.ClsiCookieManager = {
       getCookieJar: sinon.stub().callsArgWith(1, null, this.jar),
       getCookieJar: sinon.stub().callsArgWith(1, null, this.jar),
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUserId: sinon.stub().returns(this.user_id),
       getLoggedInUserId: sinon.stub().returns(this.user_id),
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
@@ -66,8 +66,7 @@ describe('CompileController', function () {
         './CompileManager': this.CompileManager,
         './CompileManager': this.CompileManager,
         '../User/UserGetter': this.UserGetter,
         '../User/UserGetter': this.UserGetter,
         './ClsiManager': this.ClsiManager,
         './ClsiManager': this.ClsiManager,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../../infrastructure/RateLimiter': this.RateLimiter,
         '../../infrastructure/RateLimiter': this.RateLimiter,
         './ClsiCookieManager': () => this.ClsiCookieManager,
         './ClsiCookieManager': () => this.ClsiCookieManager,
       },
       },
@@ -98,8 +97,8 @@ describe('CompileController', function () {
       })
       })
 
 
       it('should look up the user id', 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)
           .should.equal(true)
       })
       })
 
 

+ 5 - 9
services/web/test/unit/src/Contact/ContactControllerTests.js

@@ -18,15 +18,13 @@ const SandboxedModule = require('sandboxed-module')
 
 
 describe('ContactController', function () {
 describe('ContactController', function () {
   beforeEach(function () {
   beforeEach(function () {
-    this.AuthenticationController = { getLoggedInUserId: sinon.stub() }
+    this.SessionManager = { getLoggedInUserId: sinon.stub() }
     this.ContactController = SandboxedModule.require(modulePath, {
     this.ContactController = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
         '../User/UserGetter': (this.UserGetter = {}),
         '../User/UserGetter': (this.UserGetter = {}),
         './ContactManager': (this.ContactManager = {}),
         './ContactManager': (this.ContactManager = {}),
-        '../Authentication/AuthenticationController': (this.AuthenticationController = {}),
+        '../Authentication/SessionManager': (this.SessionManager = {}),
         '../../infrastructure/Modules': (this.Modules = { hooks: {} }),
         '../../infrastructure/Modules': (this.Modules = { hooks: {} }),
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
       },
       },
     })
     })
 
 
@@ -65,9 +63,7 @@ describe('ContactController', function () {
           unsued: 'foo',
           unsued: 'foo',
         },
         },
       ]
       ]
-      this.AuthenticationController.getLoggedInUserId = sinon
-        .stub()
-        .returns(this.user_id)
+      this.SessionManager.getLoggedInUserId = sinon.stub().returns(this.user_id)
       this.ContactManager.getContactIds = sinon
       this.ContactManager.getContactIds = sinon
         .stub()
         .stub()
         .callsArgWith(2, null, this.contact_ids)
         .callsArgWith(2, null, this.contact_ids)
@@ -80,8 +76,8 @@ describe('ContactController', function () {
     })
     })
 
 
     it('should look up the logged in user id', 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)
         .should.equal(true)
     })
     })
 
 

+ 2 - 3
services/web/test/unit/src/Editor/EditorHttpControllerTests.js

@@ -111,7 +111,7 @@ describe('EditorHttpController', function () {
       getRequestToken: sinon.stub().returns(this.token),
       getRequestToken: sinon.stub().returns(this.token),
       protectTokens: sinon.stub(),
       protectTokens: sinon.stub(),
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
     }
     }
     this.ProjectEntityUpdateHandler = {
     this.ProjectEntityUpdateHandler = {
@@ -141,8 +141,7 @@ describe('EditorHttpController', function () {
         '../Collaborators/CollaboratorsInviteHandler': this
         '../Collaborators/CollaboratorsInviteHandler': this
           .CollaboratorsInviteHandler,
           .CollaboratorsInviteHandler,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../../infrastructure/FileWriter': this.FileWriter,
         '../../infrastructure/FileWriter': this.FileWriter,
         '../Project/ProjectEntityUpdateHandler': this
         '../Project/ProjectEntityUpdateHandler': this
           .ProjectEntityUpdateHandler,
           .ProjectEntityUpdateHandler,

+ 10 - 11
services/web/test/unit/src/History/HistoryControllerTests.js

@@ -20,15 +20,14 @@ describe('HistoryController', function () {
   beforeEach(function () {
   beforeEach(function () {
     this.callback = sinon.stub()
     this.callback = sinon.stub()
     this.user_id = 'user-id-123'
     this.user_id = 'user-id-123'
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user_id),
       getLoggedInUserId: sinon.stub().returns(this.user_id),
     }
     }
     this.HistoryController = SandboxedModule.require(modulePath, {
     this.HistoryController = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
         request: (this.request = sinon.stub()),
         request: (this.request = sinon.stub()),
         '@overleaf/settings': (this.settings = {}),
         '@overleaf/settings': (this.settings = {}),
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         './HistoryManager': (this.HistoryManager = {}),
         './HistoryManager': (this.HistoryManager = {}),
         '../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = {}),
         '../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = {}),
         '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}),
         '../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}),
@@ -117,8 +116,8 @@ describe('HistoryController', function () {
       })
       })
 
 
       it('should get the user id', 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)
           .should.equal(true)
       })
       })
 
 
@@ -150,8 +149,8 @@ describe('HistoryController', function () {
       })
       })
 
 
       it('should get the user id', 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)
           .should.equal(true)
       })
       })
 
 
@@ -209,8 +208,8 @@ describe('HistoryController', function () {
       })
       })
 
 
       it('should get the user id', 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)
           .should.equal(true)
       })
       })
 
 
@@ -249,8 +248,8 @@ describe('HistoryController', function () {
       })
       })
 
 
       it('should get the user id', 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)
           .should.equal(true)
       })
       })
 
 

+ 5 - 10
services/web/test/unit/src/Project/ProjectControllerTests.js

@@ -76,7 +76,7 @@ describe('ProjectController', function () {
       isArchivedOrTrashed: sinon.stub(),
       isArchivedOrTrashed: sinon.stub(),
       getAllowedImagesForUser: sinon.stub().returns([]),
       getAllowedImagesForUser: sinon.stub().returns([]),
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
@@ -153,8 +153,7 @@ describe('ProjectController', function () {
         './ProjectUpdateHandler': this.ProjectUpdateHandler,
         './ProjectUpdateHandler': this.ProjectUpdateHandler,
         './ProjectGetter': this.ProjectGetter,
         './ProjectGetter': this.ProjectGetter,
         './ProjectDetailsHandler': this.ProjectDetailsHandler,
         './ProjectDetailsHandler': this.ProjectDetailsHandler,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
         '../TokenAccess/TokenAccessHandler': this.TokenAccessHandler,
         '../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
         '../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
         './ProjectEntityHandler': this.ProjectEntityHandler,
         './ProjectEntityHandler': this.ProjectEntityHandler,
@@ -1220,9 +1219,7 @@ describe('ProjectController', function () {
 
 
       function tagAnonymous() {
       function tagAnonymous() {
         beforeEach(function () {
         beforeEach(function () {
-          this.AuthenticationController.isUserLoggedIn = sinon
-            .stub()
-            .returns(false)
+          this.SessionManager.isUserLoggedIn = sinon.stub().returns(false)
         })
         })
       }
       }
 
 
@@ -1563,7 +1560,7 @@ describe('ProjectController', function () {
         .stub()
         .stub()
         .callsArgWith(2, null, [])
         .callsArgWith(2, null, [])
       this.ProjectController._buildProjectList = sinon.stub().returns(projects)
       this.ProjectController._buildProjectList = sinon.stub().returns(projects)
-      this.AuthenticationController.getLoggedInUserId = sinon
+      this.SessionManager.getLoggedInUserId = sinon
         .stub()
         .stub()
         .returns(this.user._id)
         .returns(this.user._id)
       done()
       done()
@@ -1585,9 +1582,7 @@ describe('ProjectController', function () {
 
 
   describe('projectEntitiesJson', function () {
   describe('projectEntitiesJson', function () {
     beforeEach(function () {
     beforeEach(function () {
-      this.AuthenticationController.getLoggedInUserId = sinon
-        .stub()
-        .returns('abc')
+      this.SessionManager.getLoggedInUserId = sinon.stub().returns('abc')
       this.req.params = { Project_id: 'abcd' }
       this.req.params = { Project_id: 'abcd' }
       this.project = { _id: 'abcd' }
       this.project = { _id: 'abcd' }
       this.docs = [
       this.docs = [

+ 2 - 3
services/web/test/unit/src/Security/RateLimiterMiddlewareTests.js

@@ -20,7 +20,7 @@ const modulePath = require('path').join(
 
 
 describe('RateLimiterMiddleware', function () {
 describe('RateLimiterMiddleware', function () {
   beforeEach(function () {
   beforeEach(function () {
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: () => {
       getLoggedInUserId: () => {
         return __guard__(
         return __guard__(
           __guard__(
           __guard__(
@@ -36,8 +36,7 @@ describe('RateLimiterMiddleware', function () {
         '@overleaf/settings': (this.settings = {}),
         '@overleaf/settings': (this.settings = {}),
         '../../infrastructure/RateLimiter': (this.RateLimiter = {}),
         '../../infrastructure/RateLimiter': (this.RateLimiter = {}),
         './LoginRateLimiter': {},
         './LoginRateLimiter': {},
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
       },
       },
     })
     })
     this.req = { params: {} }
     this.req = { params: {} }

+ 2 - 3
services/web/test/unit/src/Subscription/SubscriptionControllerTests.js

@@ -47,7 +47,7 @@ describe('SubscriptionController', function () {
     this.activeRecurlySubscription =
     this.activeRecurlySubscription =
       mockSubscriptions['subscription-123-active']
       mockSubscriptions['subscription-123-active']
 
 
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
@@ -121,8 +121,7 @@ describe('SubscriptionController', function () {
     }
     }
     this.SubscriptionController = SandboxedModule.require(modulePath, {
     this.SubscriptionController = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         './SubscriptionHandler': this.SubscriptionHandler,
         './SubscriptionHandler': this.SubscriptionHandler,
         './PlansLocator': this.PlansLocator,
         './PlansLocator': this.PlansLocator,
         './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder,
         './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder,

+ 6 - 7
services/web/test/unit/src/Subscription/SubscriptionGroupControllerTests.js

@@ -46,12 +46,12 @@ describe('SubscriptionGroupController', function () {
       getSubscription: sinon.stub().callsArgWith(1, null, this.subscription),
       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: {
       requires: {
         './SubscriptionGroupHandler': this.GroupHandler,
         './SubscriptionGroupHandler': this.GroupHandler,
         './SubscriptionLocator': this.SubscriptionLocator,
         './SubscriptionLocator': this.SubscriptionLocator,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
       },
       },
     }))
     }))
   })
   })

+ 4 - 5
services/web/test/unit/src/Tags/TagsControllerTests.js

@@ -32,16 +32,15 @@ describe('TagsController', function () {
       renameTag: sinon.stub().callsArg(3),
       renameTag: sinon.stub().callsArg(3),
       createTag: sinon.stub(),
       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, {
     this.controller = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
         './TagsHandler': this.handler,
         './TagsHandler': this.handler,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
       },
       },
     })
     })
     this.req = {
     this.req = {

+ 1 - 1
services/web/test/unit/src/Templates/TemplatesManagerTests.js

@@ -68,7 +68,7 @@ describe('TemplatesManager', function () {
         '../Project/ProjectOptionsHandler': this.ProjectOptionsHandler,
         '../Project/ProjectOptionsHandler': this.ProjectOptionsHandler,
         '../Project/ProjectRootDocManager': this.ProjectRootDocManager,
         '../Project/ProjectRootDocManager': this.ProjectRootDocManager,
         '../Project/ProjectDetailsHandler': this.ProjectDetailsHandler,
         '../Project/ProjectDetailsHandler': this.ProjectDetailsHandler,
-        '../Authentication/AuthenticationController': (this.AuthenticationController = {
+        '../Authentication/SessionManager': (this.SessionManager = {
           getLoggedInUserId: sinon.stub(),
           getLoggedInUserId: sinon.stub(),
         }),
         }),
         '../../infrastructure/FileWriter': this.FileWriter,
         '../../infrastructure/FileWriter': this.FileWriter,

+ 3 - 5
services/web/test/unit/src/ThirdPartyDataStore/TpdsControllerTests.js

@@ -9,7 +9,7 @@ const modulePath = require('path').join(
 describe('TpdsController', function () {
 describe('TpdsController', function () {
   beforeEach(function () {
   beforeEach(function () {
     this.TpdsUpdateHandler = {}
     this.TpdsUpdateHandler = {}
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns('user-id'),
       getLoggedInUserId: sinon.stub().returns('user-id'),
     }
     }
     this.TpdsQueueManager = {
     this.TpdsQueueManager = {
@@ -24,8 +24,7 @@ describe('TpdsController', function () {
         '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
         '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
           tpdsFileLimit: sinon.stub().returns({ create: sinon.stub() }),
           tpdsFileLimit: sinon.stub().returns({ create: sinon.stub() }),
         }),
         }),
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         './TpdsQueueManager': this.TpdsQueueManager,
         './TpdsQueueManager': this.TpdsQueueManager,
         '@overleaf/metrics': {
         '@overleaf/metrics': {
           inc() {},
           inc() {},
@@ -271,8 +270,7 @@ describe('TpdsController', function () {
       })
       })
 
 
       it('should use userId from session', 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(
         this.TpdsQueueManager.promises.getQueues.should.have.been.calledWith(
           'user-id'
           'user-id'
         )
         )

+ 2 - 3
services/web/test/unit/src/Uploads/ProjectUploadControllerTests.js

@@ -37,7 +37,7 @@ describe('ProjectUploadController', function () {
         return Timer
         return Timer
       })()),
       })()),
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user_id),
       getLoggedInUserId: sinon.stub().returns(this.user_id),
     }
     }
 
 
@@ -48,8 +48,7 @@ describe('ProjectUploadController', function () {
         './ProjectUploadManager': (this.ProjectUploadManager = {}),
         './ProjectUploadManager': (this.ProjectUploadManager = {}),
         './FileSystemImportManager': (this.FileSystemImportManager = {}),
         './FileSystemImportManager': (this.FileSystemImportManager = {}),
         '@overleaf/metrics': this.metrics,
         '@overleaf/metrics': this.metrics,
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         './ArchiveErrors': ArchiveErrors,
         './ArchiveErrors': ArchiveErrors,
         fs: (this.fs = {}),
         fs: (this.fs = {}),
       },
       },

+ 6 - 3
services/web/test/unit/src/User/UserControllerTests.js

@@ -44,6 +44,8 @@ describe('UserController', function () {
     this.UserRegistrationHandler = { registerNewUser: sinon.stub() }
     this.UserRegistrationHandler = { registerNewUser: sinon.stub() }
     this.AuthenticationController = {
     this.AuthenticationController = {
       establishUserSession: sinon.stub().callsArg(2),
       establishUserSession: sinon.stub().callsArg(2),
+    }
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getSessionUser: sinon.stub().returns(this.req.session.user),
       getSessionUser: sinon.stub().returns(this.req.session.user),
       setInSessionUser: sinon.stub(),
       setInSessionUser: sinon.stub(),
@@ -102,6 +104,7 @@ describe('UserController', function () {
         './UserRegistrationHandler': this.UserRegistrationHandler,
         './UserRegistrationHandler': this.UserRegistrationHandler,
         '../Authentication/AuthenticationController': this
         '../Authentication/AuthenticationController': this
           .AuthenticationController,
           .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../Authentication/AuthenticationManager': this.AuthenticationManager,
         '../Authentication/AuthenticationManager': this.AuthenticationManager,
         '../../infrastructure/Features': (this.Features = {
         '../../infrastructure/Features': (this.Features = {
           hasFeature: sinon.stub(),
           hasFeature: sinon.stub(),
@@ -142,7 +145,7 @@ describe('UserController', function () {
       this.req.body.password = 'wat'
       this.req.body.password = 'wat'
       this.req.logout = sinon.stub()
       this.req.logout = sinon.stub()
       this.req.session.destroy = sinon.stub().callsArgWith(0, null)
       this.req.session.destroy = sinon.stub().callsArgWith(0, null)
-      this.AuthenticationController.getLoggedInUserId = sinon
+      this.SessionManager.getLoggedInUserId = sinon
         .stub()
         .stub()
         .returns(this.user._id)
         .returns(this.user._id)
       this.AuthenticationManager.authenticate = sinon
       this.AuthenticationManager.authenticate = sinon
@@ -397,8 +400,8 @@ describe('UserController', function () {
       }
       }
       this.res.sendStatus = code => {
       this.res.sendStatus = code => {
         code.should.equal(200)
         code.should.equal(200)
-        this.AuthenticationController.setInSessionUser
-          .calledWith(this.req, {
+        this.SessionManager.setInSessionUser
+          .calledWith(this.req.session, {
             email: this.newEmail,
             email: this.newEmail,
             first_name: undefined,
             first_name: undefined,
             last_name: undefined,
             last_name: undefined,

+ 8 - 7
services/web/test/unit/src/User/UserEmailsControllerTests.js

@@ -23,7 +23,7 @@ describe('UserEmailsController', function () {
         getUser: sinon.stub().resolves(this.user),
         getUser: sinon.stub().resolves(this.user),
       },
       },
     }
     }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       setInSessionUser: sinon.stub(),
       setInSessionUser: sinon.stub(),
@@ -51,8 +51,7 @@ describe('UserEmailsController', function () {
     this.HttpErrorHandler = { conflict: sinon.stub() }
     this.HttpErrorHandler = { conflict: sinon.stub() }
     this.UserEmailsController = SandboxedModule.require(modulePath, {
     this.UserEmailsController = SandboxedModule.require(modulePath, {
       requires: {
       requires: {
-        '../Authentication/AuthenticationController': this
-          .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         '../../infrastructure/Features': this.Features,
         '../../infrastructure/Features': this.Features,
         './UserSessionsManager': this.UserSessionsManager,
         './UserSessionsManager': this.UserSessionsManager,
         './UserGetter': this.UserGetter,
         './UserGetter': this.UserGetter,
@@ -274,7 +273,7 @@ describe('UserEmailsController', function () {
       this.email = 'email_to_set_default@bar.com'
       this.email = 'email_to_set_default@bar.com'
       this.req.body.email = this.email
       this.req.body.email = this.email
       this.EmailHelper.parseEmail.returns(this.email)
       this.EmailHelper.parseEmail.returns(this.email)
-      this.AuthenticationController.setInSessionUser.returns(null)
+      this.SessionManager.setInSessionUser.returns(null)
     })
     })
 
 
     it('sets default email', function (done) {
     it('sets default email', function (done) {
@@ -285,9 +284,11 @@ describe('UserEmailsController', function () {
           code.should.equal(200)
           code.should.equal(200)
           assertCalledWith(this.EmailHelper.parseEmail, this.email)
           assertCalledWith(this.EmailHelper.parseEmail, this.email)
           assertCalledWith(
           assertCalledWith(
-            this.AuthenticationController.setInSessionUser,
-            this.req,
-            { email: this.email }
+            this.SessionManager.setInSessionUser,
+            this.req.session,
+            {
+              email: this.email,
+            }
           )
           )
           assertCalledWith(
           assertCalledWith(
             this.UserUpdater.setDefaultEmailAddress,
             this.UserUpdater.setDefaultEmailAddress,

+ 2 - 2
services/web/test/unit/src/User/UserInfoControllerTests.js

@@ -31,7 +31,7 @@ describe('UserInfoController', function () {
         './UserGetter': this.UserGetter,
         './UserGetter': this.UserGetter,
         './UserUpdater': this.UserUpdater,
         './UserUpdater': this.UserUpdater,
         './UserDeleter': this.UserDeleter,
         './UserDeleter': this.UserDeleter,
-        '../Authentication/AuthenticationController': (this.AuthenticationController = {
+        '../Authentication/SessionManager': (this.SessionManager = {
           getLoggedInUserId: sinon.stub(),
           getLoggedInUserId: sinon.stub(),
         }),
         }),
       },
       },
@@ -49,7 +49,7 @@ describe('UserInfoController', function () {
       this.req.session.user = this.user
       this.req.session.user = this.user
       this.UserInfoController.sendFormattedPersonalInfo = sinon.stub()
       this.UserInfoController.sendFormattedPersonalInfo = sinon.stub()
       this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, this.user)
       this.UserGetter.getUser = sinon.stub().callsArgWith(2, null, this.user)
-      this.AuthenticationController.getLoggedInUserId = sinon
+      this.SessionManager.getLoggedInUserId = sinon
         .stub()
         .stub()
         .returns(this.user._id)
         .returns(this.user._id)
       return this.UserInfoController.getLoggedInUsersPersonalInfo(
       return this.UserInfoController.getLoggedInUsersPersonalInfo(

+ 4 - 1
services/web/test/unit/src/User/UserPagesControllerTests.js

@@ -47,9 +47,11 @@ describe('UserPagesController', function () {
     this.UserSessionsManager = { getAllUserSessions: sinon.stub() }
     this.UserSessionsManager = { getAllUserSessions: sinon.stub() }
     this.dropboxStatus = {}
     this.dropboxStatus = {}
     this.ErrorController = { notFound: sinon.stub() }
     this.ErrorController = { notFound: sinon.stub() }
-    this.AuthenticationController = {
+    this.SessionManager = {
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getSessionUser: sinon.stub().returns(this.user),
       getSessionUser: sinon.stub().returns(this.user),
+    }
+    this.AuthenticationController = {
       _getRedirectFromSession: sinon.stub(),
       _getRedirectFromSession: sinon.stub(),
       setRedirectInSession: sinon.stub(),
       setRedirectInSession: sinon.stub(),
     }
     }
@@ -61,6 +63,7 @@ describe('UserPagesController', function () {
         '../Errors/ErrorController': this.ErrorController,
         '../Errors/ErrorController': this.ErrorController,
         '../Authentication/AuthenticationController': this
         '../Authentication/AuthenticationController': this
           .AuthenticationController,
           .AuthenticationController,
+        '../Authentication/SessionManager': this.SessionManager,
         request: (this.request = sinon.stub()),
         request: (this.request = sinon.stub()),
       },
       },
     })
     })

+ 2 - 3
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),
       getSessionUser: sinon.stub().returns(this.user),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
       getLoggedInUserId: sinon.stub().returns(this.user._id),
     }
     }
@@ -69,8 +69,7 @@ describe('UserMembershipController', function () {
       modulePath,
       modulePath,
       {
       {
         requires: {
         requires: {
-          '../Authentication/AuthenticationController': this
-            .AuthenticationController,
+          '../Authentication/SessionManager': this.SessionManager,
           './UserMembershipHandler': this.UserMembershipHandler,
           './UserMembershipHandler': this.UserMembershipHandler,
         },
         },
       }
       }