ProjectController.mjs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. const _ = require('lodash')
  2. const OError = require('@overleaf/o-error')
  3. const crypto = require('crypto')
  4. const { setTimeout } = require('timers/promises')
  5. const pProps = require('p-props')
  6. const logger = require('@overleaf/logger')
  7. const { expressify } = require('@overleaf/promise-utils')
  8. const { ObjectId } = require('mongodb-legacy')
  9. const ProjectDeleter = require('./ProjectDeleter')
  10. const ProjectDuplicator = require('./ProjectDuplicator')
  11. const ProjectCreationHandler = require('./ProjectCreationHandler')
  12. const EditorController = require('../Editor/EditorController')
  13. const ProjectHelper = require('./ProjectHelper')
  14. const metrics = require('@overleaf/metrics')
  15. const { User } = require('../../models/User')
  16. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  17. const { isPaidSubscription } = require('../Subscription/SubscriptionHelper')
  18. const LimitationsManager = require('../Subscription/LimitationsManager')
  19. const Settings = require('@overleaf/settings')
  20. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  21. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  22. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  23. const ProjectGetter = require('./ProjectGetter')
  24. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  25. const SessionManager = require('../Authentication/SessionManager')
  26. const Sources = require('../Authorization/Sources')
  27. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  28. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  29. const ProjectEntityHandler = require('./ProjectEntityHandler')
  30. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  31. const Features = require('../../infrastructure/Features')
  32. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  33. const UserController = require('../User/UserController')
  34. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  35. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  36. const SplitTestSessionHandler = require('../SplitTests/SplitTestSessionHandler')
  37. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  38. const SpellingHandler = require('../Spelling/SpellingHandler')
  39. const { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
  40. const InstitutionsFeatures = require('../Institutions/InstitutionsFeatures')
  41. const InstitutionsGetter = require('../Institutions/InstitutionsGetter')
  42. const ProjectAuditLogHandler = require('./ProjectAuditLogHandler')
  43. const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
  44. const TagsHandler = require('../Tags/TagsHandler')
  45. const TutorialHandler = require('../Tutorial/TutorialHandler')
  46. const UserUpdater = require('../User/UserUpdater')
  47. const Modules = require('../../infrastructure/Modules')
  48. const UserGetter = require('../User/UserGetter')
  49. const { isStandaloneAiAddOnPlanCode } = require('../Subscription/AiHelper')
  50. const SubscriptionController = require('../Subscription/SubscriptionController.js')
  51. const { formatCurrency } = require('../../util/currency')
  52. /**
  53. * @import { GetProjectsRequest, GetProjectsResponse, Project } from "./types"
  54. */
  55. const _ProjectController = {
  56. _isInPercentageRollout(rolloutName, objectId, percentage) {
  57. if (Settings.bypassPercentageRollouts === true) {
  58. return true
  59. }
  60. const data = `${rolloutName}:${objectId.toString()}`
  61. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  62. const counter = parseInt(md5hash.slice(26, 32), 16)
  63. return counter % 100 < percentage
  64. },
  65. async updateProjectSettings(req, res) {
  66. const projectId = req.params.Project_id
  67. if (req.body.compiler != null) {
  68. await EditorController.promises.setCompiler(projectId, req.body.compiler)
  69. }
  70. if (req.body.imageName != null) {
  71. await EditorController.promises.setImageName(
  72. projectId,
  73. req.body.imageName
  74. )
  75. }
  76. if (req.body.name != null) {
  77. await EditorController.promises.renameProject(projectId, req.body.name)
  78. }
  79. if (req.body.spellCheckLanguage != null) {
  80. await EditorController.promises.setSpellCheckLanguage(
  81. projectId,
  82. req.body.spellCheckLanguage
  83. )
  84. }
  85. if (req.body.rootDocId != null) {
  86. await EditorController.promises.setRootDoc(projectId, req.body.rootDocId)
  87. }
  88. if (req.body.mainBibliographyDocId != null) {
  89. await EditorController.promises.setMainBibliographyDoc(
  90. projectId,
  91. req.body.mainBibliographyDocId
  92. )
  93. }
  94. res.sendStatus(204)
  95. },
  96. async updateProjectAdminSettings(req, res) {
  97. const projectId = req.params.Project_id
  98. const user = SessionManager.getSessionUser(req.session)
  99. if (!Features.hasFeature('link-sharing')) {
  100. return res.sendStatus(403) // return Forbidden if link sharing is not enabled
  101. }
  102. const publicAccessLevel = req.body.publicAccessLevel
  103. const publicAccessLevels = [
  104. PublicAccessLevels.READ_ONLY,
  105. PublicAccessLevels.READ_AND_WRITE,
  106. PublicAccessLevels.PRIVATE,
  107. PublicAccessLevels.TOKEN_BASED,
  108. ]
  109. if (
  110. req.body.publicAccessLevel != null &&
  111. publicAccessLevels.includes(publicAccessLevel)
  112. ) {
  113. await EditorController.promises.setPublicAccessLevel(
  114. projectId,
  115. req.body.publicAccessLevel
  116. )
  117. await ProjectAuditLogHandler.promises.addEntry(
  118. projectId,
  119. 'toggle-access-level',
  120. user._id,
  121. req.ip,
  122. { publicAccessLevel: req.body.publicAccessLevel, status: 'OK' }
  123. )
  124. res.sendStatus(204)
  125. } else {
  126. res.sendStatus(500)
  127. }
  128. },
  129. async deleteProject(req, res) {
  130. const projectId = req.params.Project_id
  131. const user = SessionManager.getSessionUser(req.session)
  132. await ProjectDeleter.promises.deleteProject(projectId, {
  133. deleterUser: user,
  134. ipAddress: req.ip,
  135. })
  136. res.sendStatus(200)
  137. },
  138. async archiveProject(req, res) {
  139. const projectId = req.params.Project_id
  140. const userId = SessionManager.getLoggedInUserId(req.session)
  141. await ProjectDeleter.promises.archiveProject(projectId, userId)
  142. res.sendStatus(200)
  143. },
  144. async unarchiveProject(req, res) {
  145. const projectId = req.params.Project_id
  146. const userId = SessionManager.getLoggedInUserId(req.session)
  147. await ProjectDeleter.promises.unarchiveProject(projectId, userId)
  148. res.sendStatus(200)
  149. },
  150. async trashProject(req, res) {
  151. const projectId = req.params.project_id
  152. const userId = SessionManager.getLoggedInUserId(req.session)
  153. await ProjectDeleter.promises.trashProject(projectId, userId)
  154. res.sendStatus(200)
  155. },
  156. async untrashProject(req, res) {
  157. const projectId = req.params.project_id
  158. const userId = SessionManager.getLoggedInUserId(req.session)
  159. await ProjectDeleter.promises.untrashProject(projectId, userId)
  160. res.sendStatus(200)
  161. },
  162. async expireDeletedProjectsAfterDuration(_req, res) {
  163. await ProjectDeleter.promises.expireDeletedProjectsAfterDuration()
  164. res.sendStatus(200)
  165. },
  166. async expireDeletedProject(req, res) {
  167. const { projectId } = req.params
  168. await ProjectDeleter.promises.expireDeletedProject(projectId)
  169. res.sendStatus(200)
  170. },
  171. async restoreProject(req, res) {
  172. const projectId = req.params.Project_id
  173. await ProjectDeleter.promises.restoreProject(projectId)
  174. res.sendStatus(200)
  175. },
  176. async cloneProject(req, res, next) {
  177. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  178. metrics.inc('cloned-project')
  179. const projectId = req.params.Project_id
  180. const { projectName, tags } = req.body
  181. logger.debug({ projectId, projectName }, 'cloning project')
  182. if (!SessionManager.isUserLoggedIn(req.session)) {
  183. return res.json({ redir: '/register' })
  184. }
  185. const currentUser = SessionManager.getSessionUser(req.session)
  186. const { first_name: firstName, last_name: lastName, email } = currentUser
  187. try {
  188. const project = await ProjectDuplicator.promises.duplicate(
  189. currentUser,
  190. projectId,
  191. projectName,
  192. tags
  193. )
  194. res.json({
  195. name: project.name,
  196. lastUpdated: project.lastUpdated,
  197. project_id: project._id,
  198. owner_ref: project.owner_ref,
  199. owner: {
  200. first_name: firstName,
  201. last_name: lastName,
  202. email,
  203. _id: currentUser._id,
  204. },
  205. })
  206. } catch (err) {
  207. OError.tag(err, 'error cloning project', {
  208. projectId,
  209. userId: currentUser._id,
  210. })
  211. return next(err)
  212. }
  213. },
  214. async newProject(req, res) {
  215. const currentUser = SessionManager.getSessionUser(req.session)
  216. const {
  217. first_name: firstName,
  218. last_name: lastName,
  219. email,
  220. _id: userId,
  221. } = currentUser
  222. const projectName =
  223. req.body.projectName != null ? req.body.projectName.trim() : undefined
  224. const { template } = req.body
  225. const project = await (template === 'example'
  226. ? ProjectCreationHandler.promises.createExampleProject(
  227. userId,
  228. projectName
  229. )
  230. : ProjectCreationHandler.promises.createBasicProject(userId, projectName))
  231. res.json({
  232. project_id: project._id,
  233. owner_ref: project.owner_ref,
  234. owner: {
  235. first_name: firstName,
  236. last_name: lastName,
  237. email,
  238. _id: userId,
  239. },
  240. })
  241. },
  242. async renameProject(req, res) {
  243. const projectId = req.params.Project_id
  244. const newName = req.body.newProjectName
  245. await EditorController.promises.renameProject(projectId, newName)
  246. res.sendStatus(200)
  247. },
  248. async userProjectsJson(req, res) {
  249. const userId = SessionManager.getLoggedInUserId(req.session)
  250. let projects = await ProjectGetter.promises.findAllUsersProjects(
  251. userId,
  252. 'name lastUpdated publicAccesLevel archived trashed owner_ref'
  253. )
  254. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  255. projects = ProjectController._buildProjectList(projects, userId)
  256. .filter(p => !(p.archived || p.trashed))
  257. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  258. res.json({ projects })
  259. },
  260. async projectEntitiesJson(req, res) {
  261. const projectId = req.params.Project_id
  262. const project = await ProjectGetter.promises.getProject(projectId)
  263. const { docs, files } =
  264. ProjectEntityHandler.getAllEntitiesFromProject(project)
  265. const entities = docs
  266. .concat(files)
  267. // Sort by path ascending
  268. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  269. .map(e => ({
  270. path: e.path,
  271. type: e.doc != null ? 'doc' : 'file',
  272. }))
  273. res.json({ project_id: projectId, entities })
  274. },
  275. async loadEditor(req, res, next) {
  276. const timer = new metrics.Timer('load-editor')
  277. if (!Settings.editorIsOpen) {
  278. return res.render('general/closed', { title: 'updating_site' })
  279. }
  280. let anonymous, userId, sessionUser
  281. if (SessionManager.isUserLoggedIn(req.session)) {
  282. sessionUser = SessionManager.getSessionUser(req.session)
  283. userId = SessionManager.getLoggedInUserId(req.session)
  284. anonymous = false
  285. } else {
  286. sessionUser = null
  287. anonymous = true
  288. userId = null
  289. }
  290. if (Features.hasFeature('saas') && userId) {
  291. const { variant: domainCaptureRedirect } =
  292. await SplitTestHandler.promises.getAssignment(
  293. req,
  294. res,
  295. 'domain-capture-redirect'
  296. )
  297. if (domainCaptureRedirect === 'enabled') {
  298. const subscription = (
  299. await Modules.promises.hooks.fire(
  300. 'findDomainCaptureGroupUserCouldBePartOf',
  301. userId
  302. )
  303. )?.[0]
  304. if (subscription) {
  305. if (subscription.managedUsersEnabled) {
  306. return res.redirect('/domain-capture')
  307. } else {
  308. // TODO show notification or anything else
  309. }
  310. }
  311. }
  312. }
  313. const projectId = req.params.Project_id
  314. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  315. function shouldDisplayFeature(name, variantFlag) {
  316. if (req.query && req.query[name]) {
  317. return req.query[name] === 'true'
  318. } else {
  319. return variantFlag === true
  320. }
  321. }
  322. const splitTests = [
  323. 'compile-log-events',
  324. 'visual-preview',
  325. 'external-socket-heartbeat',
  326. 'null-test-share-modal',
  327. 'populate-clsi-cache',
  328. 'pdf-caching-cached-url-lookup',
  329. 'pdf-caching-mode',
  330. 'pdf-caching-prefetch-large',
  331. 'pdf-caching-prefetching',
  332. 'revert-file',
  333. 'revert-project',
  334. !anonymous && 'ro-mirror-on-client',
  335. 'track-pdf-download',
  336. !anonymous && 'writefull-oauth-promotion',
  337. 'hotjar',
  338. 'editor-redesign',
  339. 'overleaf-assist-bundle',
  340. 'word-count-client',
  341. 'editor-popup-ux-survey',
  342. 'client-side-references',
  343. 'editor-redesign-new-users',
  344. ].filter(Boolean)
  345. const getUserValues = async userId =>
  346. pProps(
  347. _.mapValues({
  348. user: (async () => {
  349. const user = await User.findById(
  350. userId,
  351. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsExperiments completedTutorials writefull aiErrorAssistant'
  352. ).exec()
  353. // Handle case of deleted user
  354. if (!user) {
  355. UserController.logout(req, res, next)
  356. return
  357. }
  358. logger.debug({ projectId, userId }, 'got user')
  359. return FeaturesUpdater.featuresEpochIsCurrent(user)
  360. ? user
  361. : await ProjectController._refreshFeatures(req, user)
  362. })(),
  363. learnedWords: SpellingHandler.promises.getUserDictionary(userId),
  364. projectTags: TagsHandler.promises.getTagsForProject(
  365. userId,
  366. projectId
  367. ),
  368. userHasInstitutionLicence: InstitutionsFeatures.promises
  369. .hasLicence(userId)
  370. .catch(err => {
  371. logger.error({ err, userId }, 'failed to get institution licence')
  372. return false
  373. }),
  374. affiliations: InstitutionsGetter.promises
  375. .getCurrentAffiliations(userId)
  376. .catch(err => {
  377. logger.error({ err, userId }, 'failed to get institution licence')
  378. return false
  379. }),
  380. subscription:
  381. SubscriptionLocator.promises.getUsersSubscription(userId),
  382. isTokenMember: CollaboratorsGetter.promises.userIsTokenMember(
  383. userId,
  384. projectId
  385. ),
  386. isInvitedMember:
  387. CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  388. userId,
  389. projectId
  390. ),
  391. })
  392. )
  393. const splitTestAssignments = {}
  394. try {
  395. const responses = await pProps({
  396. userValues: userId ? getUserValues(userId) : defaultUserValues(),
  397. splitTestAssignments: Promise.all(
  398. splitTests.map(async splitTest => {
  399. splitTestAssignments[splitTest] =
  400. await SplitTestHandler.promises.getAssignment(req, res, splitTest)
  401. })
  402. ),
  403. project: ProjectGetter.promises.getProject(projectId, {
  404. name: 1,
  405. lastUpdated: 1,
  406. track_changes: 1,
  407. owner_ref: 1,
  408. brandVariationId: 1,
  409. overleaf: 1,
  410. tokens: 1,
  411. tokenAccessReadAndWrite_refs: 1, // used for link sharing analytics
  412. collaberator_refs: 1, // used for link sharing analytics
  413. pendingEditor_refs: 1, // used for link sharing analytics
  414. reviewer_refs: 1,
  415. }),
  416. userIsMemberOfGroupSubscription: sessionUser
  417. ? (async () =>
  418. (
  419. await LimitationsManager.promises.userIsMemberOfGroupSubscription(
  420. sessionUser
  421. )
  422. ).isMember)()
  423. : false,
  424. _flushToTpds:
  425. TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(projectId),
  426. _activate:
  427. InactiveProjectManager.promises.reactivateProjectIfRequired(
  428. projectId
  429. ),
  430. })
  431. const { project, userValues, userIsMemberOfGroupSubscription } = responses
  432. const {
  433. user,
  434. learnedWords,
  435. projectTags,
  436. userHasInstitutionLicence,
  437. subscription,
  438. isTokenMember,
  439. isInvitedMember,
  440. } = userValues
  441. const brandVariation = project?.brandVariationId
  442. ? await BrandVariationsHandler.promises.getBrandVariationById(
  443. project.brandVariationId
  444. )
  445. : undefined
  446. const anonRequestToken = TokenAccessHandler.getRequestToken(
  447. req,
  448. projectId
  449. )
  450. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  451. const privilegeLevel =
  452. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  453. userId,
  454. projectId,
  455. anonRequestToken
  456. )
  457. await Modules.promises.hooks.fire('enforceCollaboratorLimit', projectId)
  458. if (isTokenMember) {
  459. // Check explicitly that the user is in read write token refs, while this could be inferred
  460. // from the privilege level, the privilege level of token members might later be restricted
  461. const isReadWriteTokenMember =
  462. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  463. userId,
  464. projectId
  465. )
  466. if (isReadWriteTokenMember) {
  467. // Check for an edge case where a user is both in read write token access refs but also
  468. // an invited read write member. Ensure they are not redirected to the sharing updates page
  469. // We could also delete the token access ref if the user is already a member of the project
  470. const isInvitedReadWriteMember =
  471. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  472. userId,
  473. projectId
  474. )
  475. if (!isInvitedReadWriteMember) {
  476. return res.redirect(`/project/${projectId}/sharing-updates`)
  477. }
  478. }
  479. }
  480. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  481. return res.sendStatus(401)
  482. }
  483. const allowedFreeTrial =
  484. subscription == null ||
  485. isStandaloneAiAddOnPlanCode(subscription.planCode)
  486. let wsUrl = Settings.wsUrl
  487. let metricName = 'load-editor-ws'
  488. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  489. wsUrl = Settings.wsUrlBeta
  490. metricName += '-beta'
  491. } else if (
  492. Settings.wsUrlV2 &&
  493. Settings.wsUrlV2Percentage > 0 &&
  494. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  495. Settings.wsUrlV2Percentage
  496. ) {
  497. wsUrl = Settings.wsUrlV2
  498. metricName += '-v2'
  499. }
  500. if (req.query && req.query.ws === 'fallback') {
  501. // `?ws=fallback` will connect to the bare origin, and ignore
  502. // the custom wsUrl. Hence it must load the client side
  503. // javascript from there too.
  504. // Not resetting it here would possibly load a socket.io v2
  505. // client and connect to a v0 endpoint.
  506. wsUrl = undefined
  507. metricName += '-fallback'
  508. }
  509. metrics.inc(metricName)
  510. // don't need to wait for these to complete
  511. ProjectUpdateHandler.promises
  512. .markAsOpened(projectId)
  513. .catch(err =>
  514. logger.error({ err, projectId }, 'failed to mark project as opened')
  515. )
  516. SplitTestSessionHandler.promises
  517. .sessionMaintenance(req, userId ? user : null)
  518. .catch(err =>
  519. logger.error({ err }, 'failed to update split test info in session')
  520. )
  521. const ownerFeatures = await UserGetter.promises.getUserFeatures(
  522. project.owner_ref
  523. )
  524. if (userId) {
  525. const planLimit = ownerFeatures?.collaborators || 0
  526. const namedEditors = project.collaberator_refs?.length || 0
  527. const pendingEditors = project.pendingEditor_refs?.length || 0
  528. const exceedAtLimit = planLimit > -1 && namedEditors >= planLimit
  529. let mode = 'edit'
  530. if (privilegeLevel === PrivilegeLevels.READ_ONLY) {
  531. mode = 'view'
  532. } else if (
  533. project.track_changes === true ||
  534. project.track_changes?.[userId] === true
  535. ) {
  536. mode = 'review'
  537. }
  538. const projectOpenedSegmentation = {
  539. role: privilegeLevel,
  540. mode,
  541. ownerId: project.owner_ref,
  542. projectId: project._id,
  543. namedEditors,
  544. pendingEditors,
  545. tokenEditors: project.tokenAccessReadAndWrite_refs?.length || 0,
  546. planLimit,
  547. exceedAtLimit,
  548. }
  549. AnalyticsManager.recordEventForUserInBackground(
  550. userId,
  551. 'project-opened',
  552. projectOpenedSegmentation
  553. )
  554. User.updateOne(
  555. { _id: new ObjectId(userId) },
  556. { $set: { lastActive: new Date() } }
  557. )
  558. .exec()
  559. .catch(err =>
  560. logger.error(
  561. { err, userId },
  562. 'failed to update lastActive for user'
  563. )
  564. )
  565. }
  566. const isAdminOrTemplateOwner =
  567. hasAdminAccess(user) || Settings.templates?.user_id === userId
  568. const showTemplatesServerPro =
  569. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  570. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  571. const detachRole = req.params.detachRole
  572. const showSymbolPalette =
  573. !Features.hasFeature('saas') ||
  574. (user.features && user.features.symbolPalette)
  575. const userInNonIndividualSub =
  576. userIsMemberOfGroupSubscription || userHasInstitutionLicence
  577. const userHasPremiumSub =
  578. subscription && !isStandaloneAiAddOnPlanCode(subscription.planCode)
  579. // Persistent upgrade prompts
  580. // in header & in share project modal
  581. const showUpgradePrompt =
  582. Features.hasFeature('saas') &&
  583. userId &&
  584. !userHasPremiumSub &&
  585. !userInNonIndividualSub
  586. let aiFeaturesAllowed = false
  587. if (userId && Features.hasFeature('saas')) {
  588. try {
  589. // exit early if the user couldnt use ai anyways, since permissions checks are expensive
  590. const canUserWriteOrReviewProjectContent =
  591. privilegeLevel === PrivilegeLevels.READ_AND_WRITE ||
  592. privilegeLevel === PrivilegeLevels.OWNER ||
  593. privilegeLevel === PrivilegeLevels.REVIEW
  594. if (canUserWriteOrReviewProjectContent) {
  595. // check permissions for user and project owner, to see if they allow AI on the project
  596. const permissionsResults = await Modules.promises.hooks.fire(
  597. 'projectAllowsCapability',
  598. project,
  599. userId,
  600. ['use-ai']
  601. )
  602. const aiAllowed = permissionsResults.every(
  603. result => result === true
  604. )
  605. aiFeaturesAllowed = aiAllowed
  606. }
  607. } catch (err) {
  608. // still allow users to access project if we cant get their permissions, but disable AI feature
  609. aiFeaturesAllowed = false
  610. }
  611. }
  612. let featureUsage = {}
  613. if (Features.hasFeature('saas')) {
  614. const usagesLeft = await Modules.promises.hooks.fire(
  615. 'remainingFeatureAllocation',
  616. userId
  617. )
  618. usagesLeft?.forEach(usage => {
  619. featureUsage = { ...featureUsage, ...usage }
  620. })
  621. }
  622. let inEnterpriseCommons = false
  623. const affiliations = userValues.affiliations || []
  624. for (const affiliation of affiliations) {
  625. inEnterpriseCommons =
  626. inEnterpriseCommons || affiliation.institution?.enterpriseCommons
  627. }
  628. // check if a user has never tried writefull before (writefull.enabled will be null)
  629. // if they previously accepted writefull, or are have been already assigned to a trial, user.writefull will be true,
  630. // if they explicitly disabled it, user.writefull will be false
  631. if (
  632. aiFeaturesAllowed &&
  633. user.writefull?.enabled === null &&
  634. !userIsMemberOfGroupSubscription &&
  635. !inEnterpriseCommons
  636. ) {
  637. await UserUpdater.promises.updateUser(userId, {
  638. $set: {
  639. writefull: { enabled: true, autoCreatedAccount: true },
  640. },
  641. })
  642. user.writefull.enabled = true
  643. user.writefull.autoCreatedAccount = true
  644. }
  645. const template =
  646. detachRole === 'detached'
  647. ? 'project/ide-react-detached'
  648. : 'project/ide-react'
  649. const capabilities = [...req.capabilitySet]
  650. // make sure the capability is added to CE/SP when the feature is enabled
  651. if (!Features.hasFeature('saas') && Features.hasFeature('chat')) {
  652. capabilities.push('chat')
  653. }
  654. // Note: this is not part of the default capabilities in the backend.
  655. // See services/web/modules/group-settings/app/src/DefaultGroupPolicy.mjs.
  656. // We are only using it on the frontend at the moment.
  657. // Add !Features.hasFeature('saas') to the conditional, as for chat above
  658. // if you define the capability in the backend.
  659. if (Features.hasFeature('link-sharing')) {
  660. capabilities.push('link-sharing')
  661. }
  662. const isOverleafAssistBundleEnabled =
  663. splitTestAssignments['overleaf-assist-bundle']?.variant === 'enabled'
  664. let fullFeatureSet = user?.features
  665. if (!anonymous) {
  666. fullFeatureSet = await UserGetter.promises.getUserFeatures(userId)
  667. }
  668. const hasPaidSubscription = isPaidSubscription(subscription)
  669. const hasManuallyCollectedSubscription =
  670. subscription?.collectionMethod === 'manual'
  671. const assistantDisabled = user.aiErrorAssistant?.enabled === false // the assistant has been manually disabled by the user
  672. const canUseErrorAssistant =
  673. (!hasManuallyCollectedSubscription ||
  674. fullFeatureSet?.aiErrorAssistant) &&
  675. !assistantDisabled
  676. const customerIoEnabled =
  677. await SplitTestHandler.promises.hasUserBeenAssignedToVariant(
  678. req,
  679. userId,
  680. 'customer-io-trial-conversion',
  681. 'enabled',
  682. true
  683. )
  684. const addonPrices =
  685. isOverleafAssistBundleEnabled &&
  686. (await ProjectController._getAddonPrices(req, res))
  687. const reducedTimeout =
  688. await SplitTestHandler.promises.getAssignmentForUser(
  689. project.owner_ref,
  690. '10s-timeout-enforcement'
  691. )
  692. let compileTimeout = ownerFeatures?.compileTimeout
  693. if (compileTimeout === 20 && reducedTimeout.variant === 'enabled') {
  694. compileTimeout = 10
  695. }
  696. let planCode = subscription?.planCode
  697. if (!planCode && !userInNonIndividualSub) {
  698. planCode = 'personal'
  699. }
  700. const planDetails = Settings.plans.find(p => p.planCode === planCode)
  701. res.render(template, {
  702. title: project.name,
  703. priority_title: true,
  704. bodyClasses: ['editor'],
  705. project_id: project._id,
  706. projectName: project.name,
  707. projectOwnerHasPremiumOnPageLoad:
  708. ownerFeatures?.compileGroup === 'priority',
  709. user: {
  710. id: userId,
  711. email: user.email,
  712. first_name: user.first_name,
  713. last_name: user.last_name,
  714. referal_id: user.referal_id,
  715. signUpDate: user.signUpDate,
  716. allowedFreeTrial,
  717. hasPaidSubscription,
  718. featureSwitches: user.featureSwitches,
  719. features: fullFeatureSet,
  720. featureUsage,
  721. refProviders: _.mapValues(user.refProviders, Boolean),
  722. writefull: {
  723. enabled: Boolean(user.writefull?.enabled && aiFeaturesAllowed),
  724. autoCreatedAccount: Boolean(user.writefull?.autoCreatedAccount),
  725. firstAutoLoad: Boolean(user.writefull?.firstAutoLoad),
  726. },
  727. alphaProgram: user.alphaProgram,
  728. betaProgram: user.betaProgram,
  729. labsProgram: user.labsProgram,
  730. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  731. isAdmin: hasAdminAccess(user),
  732. planCode,
  733. planName: planDetails?.name,
  734. isAnnualPlan: planCode && planDetails?.annual,
  735. isMemberOfGroupSubscription: userIsMemberOfGroupSubscription,
  736. hasInstitutionLicence: userHasInstitutionLicence,
  737. },
  738. userSettings: {
  739. mode: user.ace.mode,
  740. editorTheme: user.ace.theme,
  741. fontSize: user.ace.fontSize,
  742. autoComplete: user.ace.autoComplete,
  743. autoPairDelimiters: user.ace.autoPairDelimiters,
  744. pdfViewer: user.ace.pdfViewer,
  745. syntaxValidation: user.ace.syntaxValidation,
  746. fontFamily: user.ace.fontFamily || 'lucida',
  747. lineHeight: user.ace.lineHeight || 'normal',
  748. overallTheme: user.ace.overallTheme,
  749. mathPreview: user.ace.mathPreview,
  750. breadcrumbs: user.ace.breadcrumbs,
  751. referencesSearchMode: user.ace.referencesSearchMode,
  752. enableNewEditor: user.ace.enableNewEditor ?? true,
  753. },
  754. labsExperiments: user.labsExperiments ?? [],
  755. privilegeLevel,
  756. anonymous,
  757. isTokenMember,
  758. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  759. userId,
  760. privilegeLevel,
  761. isTokenMember,
  762. isInvitedMember
  763. ),
  764. capabilities,
  765. roMirrorOnClientNoLocalStorage:
  766. Settings.adminOnlyLogin || project.name.startsWith('Debug: '),
  767. languages: Settings.languages,
  768. learnedWords,
  769. editorThemes: THEME_LIST,
  770. legacyEditorThemes: LEGACY_THEME_LIST,
  771. maxDocLength: Settings.max_doc_length,
  772. maxReconnectGracefullyIntervalMs:
  773. Settings.maxReconnectGracefullyIntervalMs,
  774. brandVariation,
  775. allowedImageNames,
  776. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  777. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  778. wsUrl,
  779. showSupport: Features.hasFeature('support'),
  780. showTemplatesServerPro,
  781. debugPdfDetach,
  782. showSymbolPalette,
  783. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  784. userRestrictions: Array.from(req.userRestrictions || []),
  785. showAiErrorAssistant: aiFeaturesAllowed && canUseErrorAssistant,
  786. detachRole,
  787. metadata: { viewport: false },
  788. showUpgradePrompt,
  789. fixedSizeDocument: true,
  790. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  791. otMigrationStage: project.overleaf?.history?.otMigrationStage ?? 0,
  792. projectTags,
  793. isSaas: Features.hasFeature('saas'),
  794. shouldLoadHotjar: splitTestAssignments.hotjar?.variant === 'enabled',
  795. isOverleafAssistBundleEnabled,
  796. customerIoEnabled,
  797. addonPrices,
  798. compileSettings: {
  799. compileTimeout,
  800. },
  801. })
  802. timer.done()
  803. } catch (err) {
  804. OError.tag(err, 'error getting details for project page')
  805. return next(err)
  806. }
  807. },
  808. async _getPaywallPlansPrices(
  809. req,
  810. res,
  811. paywallPlans = ['collaborator', 'student']
  812. ) {
  813. const plansData = {}
  814. const locale = req.i18n.language
  815. const { currency } = await SubscriptionController.getRecommendedCurrency(
  816. req,
  817. res
  818. )
  819. paywallPlans.forEach(plan => {
  820. const planPrice = Settings.localizedPlanPricing[currency][plan].monthly
  821. const formattedPlanPrice = formatCurrency(
  822. planPrice,
  823. currency,
  824. locale,
  825. true
  826. )
  827. plansData[plan] = formattedPlanPrice
  828. })
  829. return plansData
  830. },
  831. async _getAddonPrices(req, res, addonPlans = ['assistant']) {
  832. const plansData = {}
  833. const locale = req.i18n.language
  834. const { currency } = await SubscriptionController.getRecommendedCurrency(
  835. req,
  836. res
  837. )
  838. addonPlans.forEach(plan => {
  839. const annualPrice = Settings.localizedAddOnsPricing[currency][plan].annual
  840. const monthlyPrice =
  841. Settings.localizedAddOnsPricing[currency][plan].monthly
  842. const annualDividedByTwelve =
  843. Settings.localizedAddOnsPricing[currency][plan].annualDividedByTwelve
  844. plansData[plan] = {
  845. annual: formatCurrency(annualPrice, currency, locale, true),
  846. annualDividedByTwelve: formatCurrency(
  847. annualDividedByTwelve,
  848. currency,
  849. locale,
  850. true
  851. ),
  852. monthly: formatCurrency(monthlyPrice, currency, locale, true),
  853. }
  854. })
  855. return plansData
  856. },
  857. async _refreshFeatures(req, user) {
  858. // If the feature refresh has failed in this session, don't retry
  859. // it - require the user to log in again.
  860. if (req.session.feature_refresh_failed) {
  861. metrics.inc('features-refresh', 1, {
  862. path: 'load-editor',
  863. status: 'skipped',
  864. })
  865. return user
  866. }
  867. // If the refresh takes too long then return the current
  868. // features. Note that the user.features property may still be
  869. // updated in the background after the promise is resolved.
  870. const abortController = new AbortController()
  871. const refreshTimeoutHandler = async () => {
  872. await setTimeout(5000, { signal: abortController.signal })
  873. req.session.feature_refresh_failed = {
  874. reason: 'timeout',
  875. at: new Date(),
  876. }
  877. metrics.inc('features-refresh', 1, {
  878. path: 'load-editor',
  879. status: 'timeout',
  880. })
  881. return user
  882. }
  883. // try to refresh user features now
  884. const timer = new metrics.Timer('features-refresh-on-load-editor')
  885. return Promise.race([
  886. refreshTimeoutHandler(),
  887. (async () => {
  888. try {
  889. user.features = await FeaturesUpdater.promises.refreshFeatures(
  890. user._id,
  891. 'load-editor'
  892. )
  893. metrics.inc('features-refresh', 1, {
  894. path: 'load-editor',
  895. status: 'success',
  896. })
  897. } catch (err) {
  898. // keep a record to prevent unneceary retries and leave
  899. // the original features unmodified if the refresh failed
  900. req.session.feature_refresh_failed = {
  901. reason: 'error',
  902. at: new Date(),
  903. }
  904. metrics.inc('features-refresh', 1, {
  905. path: 'load-editor',
  906. status: 'error',
  907. })
  908. }
  909. abortController.abort()
  910. timer.done()
  911. return user
  912. })(),
  913. ])
  914. },
  915. _buildProjectList(allProjects, userId) {
  916. let project
  917. const {
  918. owned,
  919. review,
  920. readAndWrite,
  921. readOnly,
  922. tokenReadAndWrite,
  923. tokenReadOnly,
  924. } = allProjects
  925. const projects = []
  926. for (project of owned) {
  927. projects.push(
  928. ProjectController._buildProjectViewModel(
  929. project,
  930. 'owner',
  931. Sources.OWNER,
  932. userId
  933. )
  934. )
  935. }
  936. // Invite-access
  937. for (project of readAndWrite) {
  938. projects.push(
  939. ProjectController._buildProjectViewModel(
  940. project,
  941. 'readWrite',
  942. Sources.INVITE,
  943. userId
  944. )
  945. )
  946. }
  947. for (project of review) {
  948. projects.push(
  949. ProjectController._buildProjectViewModel(
  950. project,
  951. 'review',
  952. Sources.INVITE,
  953. userId
  954. )
  955. )
  956. }
  957. for (project of readOnly) {
  958. projects.push(
  959. ProjectController._buildProjectViewModel(
  960. project,
  961. 'readOnly',
  962. Sources.INVITE,
  963. userId
  964. )
  965. )
  966. }
  967. // Token-access
  968. // Only add these projects if they're not already present, this gives us cascading access
  969. // from 'owner' => 'token-read-only'
  970. for (project of tokenReadAndWrite) {
  971. if (
  972. projects.filter(p => p.id.toString() === project._id.toString())
  973. .length === 0
  974. ) {
  975. projects.push(
  976. ProjectController._buildProjectViewModel(
  977. project,
  978. 'readAndWrite',
  979. Sources.TOKEN,
  980. userId
  981. )
  982. )
  983. }
  984. }
  985. for (project of tokenReadOnly) {
  986. if (
  987. projects.filter(p => p.id.toString() === project._id.toString())
  988. .length === 0
  989. ) {
  990. projects.push(
  991. ProjectController._buildProjectViewModel(
  992. project,
  993. 'readOnly',
  994. Sources.TOKEN,
  995. userId
  996. )
  997. )
  998. }
  999. }
  1000. return projects
  1001. },
  1002. _buildProjectViewModel(project, accessLevel, source, userId) {
  1003. const archived = ProjectHelper.isArchived(project, userId)
  1004. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1005. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1006. const model = {
  1007. id: project._id,
  1008. name: project.name,
  1009. lastUpdated: project.lastUpdated,
  1010. lastUpdatedBy: project.lastUpdatedBy,
  1011. publicAccessLevel: project.publicAccesLevel,
  1012. accessLevel,
  1013. source,
  1014. archived,
  1015. trashed,
  1016. owner_ref: project.owner_ref,
  1017. isV1Project: false,
  1018. }
  1019. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1020. model.owner_ref = null
  1021. model.lastUpdatedBy = null
  1022. }
  1023. return model
  1024. },
  1025. _buildPortalTemplatesList(affiliations) {
  1026. if (affiliations == null) {
  1027. affiliations = []
  1028. }
  1029. const portalTemplates = []
  1030. for (const aff of affiliations) {
  1031. if (
  1032. aff.portal &&
  1033. aff.portal.slug &&
  1034. aff.portal.templates_count &&
  1035. aff.portal.templates_count > 0
  1036. ) {
  1037. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1038. portalTemplates.push({
  1039. name: aff.institution.name,
  1040. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1041. })
  1042. }
  1043. }
  1044. return portalTemplates
  1045. },
  1046. }
  1047. const defaultSettingsForAnonymousUser = userId => ({
  1048. id: userId,
  1049. ace: {
  1050. mode: 'none',
  1051. theme: 'textmate',
  1052. fontSize: '12',
  1053. autoComplete: true,
  1054. spellCheckLanguage: '',
  1055. pdfViewer: '',
  1056. syntaxValidation: true,
  1057. },
  1058. subscription: {
  1059. freeTrial: {
  1060. allowed: true,
  1061. },
  1062. },
  1063. featureSwitches: {
  1064. github: false,
  1065. },
  1066. alphaProgram: false,
  1067. betaProgram: false,
  1068. writefull: {
  1069. enabled: false,
  1070. },
  1071. })
  1072. const defaultUserValues = () => ({
  1073. user: defaultSettingsForAnonymousUser(null),
  1074. learnedWords: [],
  1075. projectTags: [],
  1076. userHasInstitutionLicence: false,
  1077. subscription: undefined,
  1078. isTokenMember: false,
  1079. isInvitedMember: false,
  1080. })
  1081. const THEME_LIST = [
  1082. 'cobalt',
  1083. 'dracula',
  1084. 'eclipse',
  1085. 'monokai',
  1086. 'overleaf',
  1087. 'overleaf_dark',
  1088. 'textmate',
  1089. ]
  1090. const LEGACY_THEME_LIST = [
  1091. 'ambiance',
  1092. 'chaos',
  1093. 'chrome',
  1094. 'clouds',
  1095. 'clouds_midnight',
  1096. 'crimson_editor',
  1097. 'dawn',
  1098. 'dreamweaver',
  1099. 'github',
  1100. 'gob',
  1101. 'gruvbox',
  1102. 'idle_fingers',
  1103. 'iplastic',
  1104. 'katzenmilch',
  1105. 'kr_theme',
  1106. 'kuroir',
  1107. 'merbivore',
  1108. 'merbivore_soft',
  1109. 'mono_industrial',
  1110. 'nord_dark',
  1111. 'pastel_on_dark',
  1112. 'solarized_dark',
  1113. 'solarized_light',
  1114. 'sqlserver',
  1115. 'terminal',
  1116. 'tomorrow',
  1117. 'tomorrow_night',
  1118. 'tomorrow_night_blue',
  1119. 'tomorrow_night_bright',
  1120. 'tomorrow_night_eighties',
  1121. 'twilight',
  1122. 'vibrant_ink',
  1123. 'xcode',
  1124. ]
  1125. const ProjectController = {
  1126. archiveProject: expressify(_ProjectController.archiveProject),
  1127. cloneProject: expressify(_ProjectController.cloneProject),
  1128. deleteProject: expressify(_ProjectController.deleteProject),
  1129. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  1130. expireDeletedProjectsAfterDuration: expressify(
  1131. _ProjectController.expireDeletedProjectsAfterDuration
  1132. ),
  1133. loadEditor: expressify(_ProjectController.loadEditor),
  1134. newProject: expressify(_ProjectController.newProject),
  1135. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  1136. renameProject: expressify(_ProjectController.renameProject),
  1137. restoreProject: expressify(_ProjectController.restoreProject),
  1138. trashProject: expressify(_ProjectController.trashProject),
  1139. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  1140. untrashProject: expressify(_ProjectController.untrashProject),
  1141. updateProjectAdminSettings: expressify(
  1142. _ProjectController.updateProjectAdminSettings
  1143. ),
  1144. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  1145. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  1146. _buildProjectList: _ProjectController._buildProjectList,
  1147. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  1148. _injectProjectUsers: _ProjectController._injectProjectUsers,
  1149. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  1150. _refreshFeatures: _ProjectController._refreshFeatures,
  1151. _getPaywallPlansPrices: _ProjectController._getPaywallPlansPrices,
  1152. _getAddonPrices: _ProjectController._getAddonPrices,
  1153. }
  1154. module.exports = ProjectController