ProjectController.js 30 KB

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