ProjectController.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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 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. 'review-panel-redesign',
  303. 'track-pdf-download',
  304. !anonymous && 'writefull-oauth-promotion',
  305. 'ieee-stylesheet',
  306. 'write-and-cite',
  307. ].filter(Boolean)
  308. const getUserValues = async userId =>
  309. pProps(
  310. _.mapValues({
  311. user: (async () => {
  312. const user = await User.findById(
  313. userId,
  314. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram completedTutorials writefull'
  315. ).exec()
  316. // Handle case of deleted user
  317. if (!user) {
  318. UserController.logout(req, res, next)
  319. return
  320. }
  321. logger.debug({ projectId, userId }, 'got user')
  322. return FeaturesUpdater.featuresEpochIsCurrent(user)
  323. ? user
  324. : await ProjectController._refreshFeatures(req, user)
  325. })(),
  326. learnedWords: SpellingHandler.promises.getUserDictionary(userId),
  327. projectTags: TagsHandler.promises.getTagsForProject(
  328. userId,
  329. projectId
  330. ),
  331. userHasInstitutionLicence: InstitutionsFeatures.promises
  332. .hasLicence(userId)
  333. .catch(err => {
  334. logger.error({ err, userId }, 'failed to get institution licence')
  335. return false
  336. }),
  337. subscription:
  338. SubscriptionLocator.promises.getUsersSubscription(userId),
  339. isTokenMember: CollaboratorsGetter.promises.userIsTokenMember(
  340. userId,
  341. projectId
  342. ),
  343. isInvitedMember:
  344. CollaboratorsGetter.promises.isUserInvitedMemberOfProject(
  345. userId,
  346. projectId
  347. ),
  348. usedLatex: OnboardingDataCollectionManager.getOnboardingDataValue(
  349. userId,
  350. 'usedLatex'
  351. ).catch(err => {
  352. logger.error({ err, userId })
  353. return null
  354. }),
  355. })
  356. )
  357. const splitTestAssignments = {}
  358. try {
  359. const responses = await pProps({
  360. userValues: userId ? getUserValues(userId) : defaultUserValues(),
  361. splitTestAssignments: Promise.all(
  362. splitTests.map(async splitTest => {
  363. splitTestAssignments[splitTest] =
  364. await SplitTestHandler.promises.getAssignment(req, res, splitTest)
  365. })
  366. ),
  367. project: ProjectGetter.promises.getProject(projectId, {
  368. name: 1,
  369. lastUpdated: 1,
  370. track_changes: 1,
  371. owner_ref: 1,
  372. brandVariationId: 1,
  373. overleaf: 1,
  374. tokens: 1,
  375. tokenAccessReadAndWrite_refs: 1, // used for link sharing analytics
  376. collaberator_refs: 1, // used for link sharing analytics
  377. }),
  378. userIsMemberOfGroupSubscription: sessionUser
  379. ? LimitationsManager.promises.userIsMemberOfGroupSubscription(
  380. sessionUser
  381. )
  382. : false,
  383. _flushToTpds:
  384. TpdsProjectFlusher.promises.flushProjectToTpdsIfNeeded(projectId),
  385. _activate:
  386. InactiveProjectManager.promises.reactivateProjectIfRequired(
  387. projectId
  388. ),
  389. })
  390. const { project, userValues, userIsMemberOfGroupSubscription } = responses
  391. const {
  392. user,
  393. learnedWords,
  394. projectTags,
  395. userHasInstitutionLicence,
  396. subscription,
  397. isTokenMember,
  398. isInvitedMember,
  399. usedLatex,
  400. } = userValues
  401. // check if a user is not in the writefull-oauth-promotion, in which case they may be part of the auto trial group
  402. if (
  403. !anonymous &&
  404. splitTestAssignments['writefull-oauth-promotion']?.variant === 'default'
  405. ) {
  406. // since we are auto-enrolling users into writefull if they are part of the group, we only want to
  407. // auto enroll (set writefull to true) if its the first time they have entered the test
  408. // this ensures that they can still turn writefull off (otherwise, we would be setting writefull on every time they access their projects)
  409. const { variant, metadata } =
  410. await SplitTestHandler.promises.getAssignment(
  411. req,
  412. res,
  413. 'writefull-auto-load'
  414. )
  415. if (variant === 'enabled' && metadata?.isFirstNonDefaultAssignment) {
  416. await UserUpdater.promises.updateUser(userId, {
  417. $set: {
  418. writefull: { enabled: true },
  419. },
  420. })
  421. user.writefull.enabled = true
  422. }
  423. }
  424. const brandVariation = project?.brandVariationId
  425. ? await BrandVariationsHandler.promises.getBrandVariationById(
  426. project.brandVariationId
  427. )
  428. : undefined
  429. const anonRequestToken = TokenAccessHandler.getRequestToken(
  430. req,
  431. projectId
  432. )
  433. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  434. const privilegeLevel =
  435. await AuthorizationManager.promises.getPrivilegeLevelForProject(
  436. userId,
  437. projectId,
  438. anonRequestToken
  439. )
  440. const linkSharingChanges =
  441. await SplitTestHandler.promises.getAssignmentForUser(
  442. project.owner_ref,
  443. 'link-sharing-warning'
  444. )
  445. if (linkSharingChanges?.variant === 'active') {
  446. if (isTokenMember) {
  447. // Check explicitly that the user is in read write token refs, while this could be inferred
  448. // from the privilege level, the privilege level of token members might later be restricted
  449. const isReadWriteTokenMember =
  450. await CollaboratorsGetter.promises.userIsReadWriteTokenMember(
  451. userId,
  452. projectId
  453. )
  454. if (isReadWriteTokenMember) {
  455. // Check for an edge case where a user is both in read write token access refs but also
  456. // an invited read write member. Ensure they are not redirected to the sharing updates page
  457. // We could also delete the token access ref if the user is already a member of the project
  458. const isInvitedReadWriteMember =
  459. await CollaboratorsGetter.promises.isUserInvitedReadWriteMemberOfProject(
  460. userId,
  461. projectId
  462. )
  463. if (!isInvitedReadWriteMember) {
  464. return res.redirect(`/project/${projectId}/sharing-updates`)
  465. }
  466. }
  467. }
  468. }
  469. let allowedFreeTrial = true
  470. if (privilegeLevel == null || privilegeLevel === PrivilegeLevels.NONE) {
  471. return res.sendStatus(401)
  472. }
  473. if (subscription != null) {
  474. allowedFreeTrial = false
  475. }
  476. let wsUrl = Settings.wsUrl
  477. let metricName = 'load-editor-ws'
  478. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  479. wsUrl = Settings.wsUrlBeta
  480. metricName += '-beta'
  481. } else if (
  482. Settings.wsUrlV2 &&
  483. Settings.wsUrlV2Percentage > 0 &&
  484. (new ObjectId(projectId).getTimestamp() / 1000) % 100 <
  485. Settings.wsUrlV2Percentage
  486. ) {
  487. wsUrl = Settings.wsUrlV2
  488. metricName += '-v2'
  489. }
  490. if (req.query && req.query.ws === 'fallback') {
  491. // `?ws=fallback` will connect to the bare origin, and ignore
  492. // the custom wsUrl. Hence it must load the client side
  493. // javascript from there too.
  494. // Not resetting it here would possibly load a socket.io v2
  495. // client and connect to a v0 endpoint.
  496. wsUrl = undefined
  497. metricName += '-fallback'
  498. }
  499. metrics.inc(metricName)
  500. // don't need to wait for these to complete
  501. ProjectUpdateHandler.promises
  502. .markAsOpened(projectId)
  503. .catch(err =>
  504. logger.error({ err, projectId }, 'failed to mark project as opened')
  505. )
  506. SplitTestSessionHandler.promises
  507. .sessionMaintenance(req, userId ? user : null)
  508. .catch(err =>
  509. logger.error({ err }, 'failed to update split test info in session')
  510. )
  511. if (userId) {
  512. const ownerFeatures = await UserGetter.promises.getUserFeatures(
  513. project.owner_ref
  514. )
  515. const planLimit = ownerFeatures?.collaborators || 0
  516. const namedEditors = project.collaberator_refs?.length || 0
  517. const exceedAtLimit = planLimit > -1 && namedEditors >= planLimit
  518. const projectOpenedSegmentation = {
  519. projectId: project._id,
  520. // temporary link sharing segmentation:
  521. linkSharingWarning: linkSharingChanges?.variant,
  522. namedEditors,
  523. tokenEditors: project.tokenAccessReadAndWrite_refs?.length || 0,
  524. planLimit,
  525. exceedAtLimit,
  526. }
  527. AnalyticsManager.recordEventForUserInBackground(
  528. userId,
  529. 'project-opened',
  530. projectOpenedSegmentation
  531. )
  532. User.updateOne(
  533. { _id: new ObjectId(userId) },
  534. { $set: { lastActive: new Date() } }
  535. )
  536. .exec()
  537. .catch(err =>
  538. logger.error(
  539. { err, userId },
  540. 'failed to update lastActive for user'
  541. )
  542. )
  543. }
  544. const isAdminOrTemplateOwner =
  545. hasAdminAccess(user) || Settings.templates?.user_id === userId
  546. const showTemplatesServerPro =
  547. Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
  548. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  549. const detachRole = req.params.detachRole
  550. const showSymbolPalette =
  551. !Features.hasFeature('saas') ||
  552. (user.features && user.features.symbolPalette)
  553. // Persistent upgrade prompts
  554. // in header & in share project modal
  555. const showUpgradePrompt =
  556. Features.hasFeature('saas') &&
  557. userId &&
  558. !subscription &&
  559. !userIsMemberOfGroupSubscription &&
  560. !userHasInstitutionLicence
  561. const showPersonalAccessToken =
  562. userId &&
  563. (!Features.hasFeature('saas') ||
  564. req.query?.personal_access_token === 'true')
  565. const optionalPersonalAccessToken =
  566. userId &&
  567. !showPersonalAccessToken &&
  568. splitTestAssignments['personal-access-token'].variant === 'enabled' // `?personal-access-token=enabled`
  569. let showAiErrorAssistant = false
  570. if (userId && Features.hasFeature('saas')) {
  571. try {
  572. // exit early if the user couldnt use ai anyways, since permissions checks are expensive
  573. const canUseAiOnProject =
  574. user.features?.aiErrorAssistant &&
  575. (privilegeLevel === PrivilegeLevels.READ_AND_WRITE ||
  576. privilegeLevel === PrivilegeLevels.OWNER)
  577. if (canUseAiOnProject) {
  578. // check permissions for user and project owner, to see if they allow AI on the project
  579. const permissionsResults = await Modules.promises.hooks.fire(
  580. 'projectAllowsCapability',
  581. project,
  582. userId,
  583. ['use-ai']
  584. )
  585. const aiAllowed = permissionsResults.every(
  586. result => result === true
  587. )
  588. showAiErrorAssistant = aiAllowed
  589. }
  590. } catch (err) {
  591. // still allow users to access project if we cant get their permissions, but disable AI feature
  592. showAiErrorAssistant = false
  593. }
  594. }
  595. const template =
  596. detachRole === 'detached'
  597. ? 'project/ide-react-detached'
  598. : 'project/ide-react'
  599. res.render(template, {
  600. title: project.name,
  601. priority_title: true,
  602. bodyClasses: ['editor'],
  603. project_id: project._id,
  604. projectName: project.name,
  605. user: {
  606. id: userId,
  607. email: user.email,
  608. first_name: user.first_name,
  609. last_name: user.last_name,
  610. referal_id: user.referal_id,
  611. signUpDate: user.signUpDate,
  612. allowedFreeTrial,
  613. featureSwitches: user.featureSwitches,
  614. features: user.features,
  615. refProviders: _.mapValues(user.refProviders, Boolean),
  616. writefull: {
  617. enabled: Boolean(user.writefull?.enabled),
  618. },
  619. alphaProgram: user.alphaProgram,
  620. betaProgram: user.betaProgram,
  621. labsProgram: user.labsProgram,
  622. inactiveTutorials: TutorialHandler.getInactiveTutorials(user),
  623. isAdmin: hasAdminAccess(user),
  624. },
  625. userSettings: {
  626. mode: user.ace.mode,
  627. editorTheme: user.ace.theme,
  628. fontSize: user.ace.fontSize,
  629. autoComplete: user.ace.autoComplete,
  630. autoPairDelimiters: user.ace.autoPairDelimiters,
  631. pdfViewer: user.ace.pdfViewer,
  632. syntaxValidation: user.ace.syntaxValidation,
  633. fontFamily: user.ace.fontFamily || 'lucida',
  634. lineHeight: user.ace.lineHeight || 'normal',
  635. overallTheme: user.ace.overallTheme,
  636. mathPreview: user.ace.mathPreview,
  637. },
  638. privilegeLevel,
  639. anonymous,
  640. isTokenMember,
  641. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  642. userId,
  643. privilegeLevel,
  644. isTokenMember,
  645. isInvitedMember
  646. ),
  647. languages: Settings.languages,
  648. learnedWords,
  649. editorThemes: THEME_LIST,
  650. legacyEditorThemes: LEGACY_THEME_LIST,
  651. maxDocLength: Settings.max_doc_length,
  652. brandVariation,
  653. allowedImageNames,
  654. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  655. gitBridgeEnabled: Features.hasFeature('git-bridge'),
  656. wsUrl,
  657. showSupport: Features.hasFeature('support'),
  658. showTemplatesServerPro,
  659. pdfjsVariant: splitTestAssignments['pdfjs-40'].variant,
  660. debugPdfDetach,
  661. showSymbolPalette,
  662. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  663. showAiErrorAssistant,
  664. detachRole,
  665. metadata: { viewport: false },
  666. showUpgradePrompt,
  667. fixedSizeDocument: true,
  668. useOpenTelemetry: Settings.useOpenTelemetryClient,
  669. showPersonalAccessToken,
  670. optionalPersonalAccessToken,
  671. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  672. projectTags,
  673. linkSharingWarning: linkSharingChanges.variant === 'active',
  674. usedLatex,
  675. })
  676. timer.done()
  677. } catch (err) {
  678. OError.tag(err, 'error getting details for project page')
  679. return next(err)
  680. }
  681. },
  682. async _refreshFeatures(req, user) {
  683. // If the feature refresh has failed in this session, don't retry
  684. // it - require the user to log in again.
  685. if (req.session.feature_refresh_failed) {
  686. metrics.inc('features-refresh', 1, {
  687. path: 'load-editor',
  688. status: 'skipped',
  689. })
  690. return user
  691. }
  692. // If the refresh takes too long then return the current
  693. // features. Note that the user.features property may still be
  694. // updated in the background after the promise is resolved.
  695. const abortController = new AbortController()
  696. const refreshTimeoutHandler = async () => {
  697. await setTimeout(5000, { signal: abortController.signal })
  698. req.session.feature_refresh_failed = {
  699. reason: 'timeout',
  700. at: new Date(),
  701. }
  702. metrics.inc('features-refresh', 1, {
  703. path: 'load-editor',
  704. status: 'timeout',
  705. })
  706. return user
  707. }
  708. // try to refresh user features now
  709. const timer = new metrics.Timer('features-refresh-on-load-editor')
  710. return Promise.race([
  711. refreshTimeoutHandler(),
  712. (async () => {
  713. try {
  714. user.features = await FeaturesUpdater.promises.refreshFeatures(
  715. user._id,
  716. 'load-editor'
  717. )
  718. metrics.inc('features-refresh', 1, {
  719. path: 'load-editor',
  720. status: 'success',
  721. })
  722. } catch (err) {
  723. // keep a record to prevent unneceary retries and leave
  724. // the original features unmodified if the refresh failed
  725. req.session.feature_refresh_failed = {
  726. reason: 'error',
  727. at: new Date(),
  728. }
  729. metrics.inc('features-refresh', 1, {
  730. path: 'load-editor',
  731. status: 'error',
  732. })
  733. }
  734. abortController.abort()
  735. timer.done()
  736. return user
  737. })(),
  738. ])
  739. },
  740. _buildProjectList(allProjects, userId) {
  741. let project
  742. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  743. allProjects
  744. const projects = []
  745. for (project of owned) {
  746. projects.push(
  747. ProjectController._buildProjectViewModel(
  748. project,
  749. 'owner',
  750. Sources.OWNER,
  751. userId
  752. )
  753. )
  754. }
  755. // Invite-access
  756. for (project of readAndWrite) {
  757. projects.push(
  758. ProjectController._buildProjectViewModel(
  759. project,
  760. 'readWrite',
  761. Sources.INVITE,
  762. userId
  763. )
  764. )
  765. }
  766. for (project of readOnly) {
  767. projects.push(
  768. ProjectController._buildProjectViewModel(
  769. project,
  770. 'readOnly',
  771. Sources.INVITE,
  772. userId
  773. )
  774. )
  775. }
  776. // Token-access
  777. // Only add these projects if they're not already present, this gives us cascading access
  778. // from 'owner' => 'token-read-only'
  779. for (project of tokenReadAndWrite) {
  780. if (
  781. projects.filter(p => p.id.toString() === project._id.toString())
  782. .length === 0
  783. ) {
  784. projects.push(
  785. ProjectController._buildProjectViewModel(
  786. project,
  787. 'readAndWrite',
  788. Sources.TOKEN,
  789. userId
  790. )
  791. )
  792. }
  793. }
  794. for (project of tokenReadOnly) {
  795. if (
  796. projects.filter(p => p.id.toString() === project._id.toString())
  797. .length === 0
  798. ) {
  799. projects.push(
  800. ProjectController._buildProjectViewModel(
  801. project,
  802. 'readOnly',
  803. Sources.TOKEN,
  804. userId
  805. )
  806. )
  807. }
  808. }
  809. return projects
  810. },
  811. _buildProjectViewModel(project, accessLevel, source, userId) {
  812. const archived = ProjectHelper.isArchived(project, userId)
  813. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  814. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  815. const model = {
  816. id: project._id,
  817. name: project.name,
  818. lastUpdated: project.lastUpdated,
  819. lastUpdatedBy: project.lastUpdatedBy,
  820. publicAccessLevel: project.publicAccesLevel,
  821. accessLevel,
  822. source,
  823. archived,
  824. trashed,
  825. owner_ref: project.owner_ref,
  826. isV1Project: false,
  827. }
  828. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  829. model.owner_ref = null
  830. model.lastUpdatedBy = null
  831. }
  832. return model
  833. },
  834. _buildPortalTemplatesList(affiliations) {
  835. if (affiliations == null) {
  836. affiliations = []
  837. }
  838. const portalTemplates = []
  839. for (const aff of affiliations) {
  840. if (
  841. aff.portal &&
  842. aff.portal.slug &&
  843. aff.portal.templates_count &&
  844. aff.portal.templates_count > 0
  845. ) {
  846. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  847. portalTemplates.push({
  848. name: aff.institution.name,
  849. url: Settings.siteUrl + portalPath + aff.portal.slug,
  850. })
  851. }
  852. }
  853. return portalTemplates
  854. },
  855. }
  856. const defaultSettingsForAnonymousUser = userId => ({
  857. id: userId,
  858. ace: {
  859. mode: 'none',
  860. theme: 'textmate',
  861. fontSize: '12',
  862. autoComplete: true,
  863. spellCheckLanguage: '',
  864. pdfViewer: '',
  865. syntaxValidation: true,
  866. },
  867. subscription: {
  868. freeTrial: {
  869. allowed: true,
  870. },
  871. },
  872. featureSwitches: {
  873. github: false,
  874. },
  875. alphaProgram: false,
  876. betaProgram: false,
  877. writefull: {
  878. enabled: false,
  879. },
  880. })
  881. const defaultUserValues = () => ({
  882. user: defaultSettingsForAnonymousUser(null),
  883. learnedWords: [],
  884. projectTags: [],
  885. userHasInstitutionLicence: false,
  886. subscription: undefined,
  887. isTokenMember: false,
  888. isInvitedMember: false,
  889. })
  890. const THEME_LIST = [
  891. 'cobalt',
  892. 'dracula',
  893. 'eclipse',
  894. 'monokai',
  895. 'overleaf',
  896. 'textmate',
  897. ]
  898. const LEGACY_THEME_LIST = [
  899. 'ambiance',
  900. 'chaos',
  901. 'chrome',
  902. 'clouds',
  903. 'clouds_midnight',
  904. 'crimson_editor',
  905. 'dawn',
  906. 'dreamweaver',
  907. 'github',
  908. 'gob',
  909. 'gruvbox',
  910. 'idle_fingers',
  911. 'iplastic',
  912. 'katzenmilch',
  913. 'kr_theme',
  914. 'kuroir',
  915. 'merbivore',
  916. 'merbivore_soft',
  917. 'mono_industrial',
  918. 'nord_dark',
  919. 'pastel_on_dark',
  920. 'solarized_dark',
  921. 'solarized_light',
  922. 'sqlserver',
  923. 'terminal',
  924. 'tomorrow',
  925. 'tomorrow_night',
  926. 'tomorrow_night_blue',
  927. 'tomorrow_night_bright',
  928. 'tomorrow_night_eighties',
  929. 'twilight',
  930. 'vibrant_ink',
  931. 'xcode',
  932. ]
  933. const ProjectController = {
  934. archiveProject: expressify(_ProjectController.archiveProject),
  935. cloneProject: expressify(_ProjectController.cloneProject),
  936. deleteProject: expressify(_ProjectController.deleteProject),
  937. expireDeletedProject: expressify(_ProjectController.expireDeletedProject),
  938. expireDeletedProjectsAfterDuration: expressify(
  939. _ProjectController.expireDeletedProjectsAfterDuration
  940. ),
  941. loadEditor: expressify(_ProjectController.loadEditor),
  942. newProject: expressify(_ProjectController.newProject),
  943. projectEntitiesJson: expressify(_ProjectController.projectEntitiesJson),
  944. renameProject: expressify(_ProjectController.renameProject),
  945. restoreProject: expressify(_ProjectController.restoreProject),
  946. trashProject: expressify(_ProjectController.trashProject),
  947. unarchiveProject: expressify(_ProjectController.unarchiveProject),
  948. untrashProject: expressify(_ProjectController.untrashProject),
  949. updateProjectAdminSettings: expressify(
  950. _ProjectController.updateProjectAdminSettings
  951. ),
  952. updateProjectSettings: expressify(_ProjectController.updateProjectSettings),
  953. userProjectsJson: expressify(_ProjectController.userProjectsJson),
  954. _buildProjectList: _ProjectController._buildProjectList,
  955. _buildProjectViewModel: _ProjectController._buildProjectViewModel,
  956. _injectProjectUsers: _ProjectController._injectProjectUsers,
  957. _isInPercentageRollout: _ProjectController._isInPercentageRollout,
  958. _refreshFeatures: _ProjectController._refreshFeatures,
  959. }
  960. module.exports = ProjectController