ProjectController.js 38 KB

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