ProjectController.js 34 KB

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