ProjectController.js 32 KB

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