ProjectController.js 34 KB

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