ProjectController.js 37 KB

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