ProjectController.js 35 KB

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