ProjectController.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. const _ = require('lodash')
  2. const OError = require('@overleaf/o-error')
  3. const crypto = require('crypto')
  4. const async = require('async')
  5. const logger = require('@overleaf/logger')
  6. const { ObjectId } = require('mongodb')
  7. const ProjectDeleter = require('./ProjectDeleter')
  8. const ProjectDuplicator = require('./ProjectDuplicator')
  9. const ProjectCreationHandler = require('./ProjectCreationHandler')
  10. const EditorController = require('../Editor/EditorController')
  11. const ProjectHelper = require('./ProjectHelper')
  12. const metrics = require('@overleaf/metrics')
  13. const { User } = require('../../models/User')
  14. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  15. const LimitationsManager = require('../Subscription/LimitationsManager')
  16. const Settings = require('@overleaf/settings')
  17. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  18. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  19. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  20. const ProjectGetter = require('./ProjectGetter')
  21. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  22. const SessionManager = require('../Authentication/SessionManager')
  23. const Sources = require('../Authorization/Sources')
  24. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  25. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  26. const ProjectEntityHandler = require('./ProjectEntityHandler')
  27. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  28. const UserGetter = require('../User/UserGetter')
  29. const Features = require('../../infrastructure/Features')
  30. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  31. const UserController = require('../User/UserController')
  32. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  33. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  34. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  35. const SpellingHandler = require('../Spelling/SpellingHandler')
  36. const { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
  37. const InstitutionsFeatures = require('../Institutions/InstitutionsFeatures')
  38. const ProjectAuditLogHandler = require('./ProjectAuditLogHandler')
  39. const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
  40. /**
  41. * @typedef {import("./types").GetProjectsRequest} GetProjectsRequest
  42. * @typedef {import("./types").GetProjectsResponse} GetProjectsResponse
  43. * @typedef {import("./types").Project} Project
  44. */
  45. const ProjectController = {
  46. _isInPercentageRollout(rolloutName, objectId, percentage) {
  47. if (Settings.bypassPercentageRollouts === true) {
  48. return true
  49. }
  50. const data = `${rolloutName}:${objectId.toString()}`
  51. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  52. const counter = parseInt(md5hash.slice(26, 32), 16)
  53. return counter % 100 < percentage
  54. },
  55. updateProjectSettings(req, res, next) {
  56. const projectId = req.params.Project_id
  57. const jobs = []
  58. if (req.body.compiler != null) {
  59. jobs.push(callback =>
  60. EditorController.setCompiler(projectId, req.body.compiler, callback)
  61. )
  62. }
  63. if (req.body.imageName != null) {
  64. jobs.push(callback =>
  65. EditorController.setImageName(projectId, req.body.imageName, callback)
  66. )
  67. }
  68. if (req.body.name != null) {
  69. jobs.push(callback =>
  70. EditorController.renameProject(projectId, req.body.name, callback)
  71. )
  72. }
  73. if (req.body.spellCheckLanguage != null) {
  74. jobs.push(callback =>
  75. EditorController.setSpellCheckLanguage(
  76. projectId,
  77. req.body.spellCheckLanguage,
  78. callback
  79. )
  80. )
  81. }
  82. if (req.body.rootDocId != null) {
  83. jobs.push(callback =>
  84. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  85. )
  86. }
  87. async.series(jobs, error => {
  88. if (error != null) {
  89. return next(error)
  90. }
  91. res.sendStatus(204)
  92. })
  93. },
  94. updateProjectAdminSettings(req, res, next) {
  95. const projectId = req.params.Project_id
  96. const user = SessionManager.getSessionUser(req.session)
  97. const publicAccessLevel = req.body.publicAccessLevel
  98. const publicAccessLevels = [
  99. PublicAccessLevels.READ_ONLY,
  100. PublicAccessLevels.READ_AND_WRITE,
  101. PublicAccessLevels.PRIVATE,
  102. PublicAccessLevels.TOKEN_BASED,
  103. ]
  104. if (
  105. req.body.publicAccessLevel != null &&
  106. publicAccessLevels.includes(publicAccessLevel)
  107. ) {
  108. const jobs = []
  109. jobs.push(callback =>
  110. EditorController.setPublicAccessLevel(
  111. projectId,
  112. req.body.publicAccessLevel,
  113. callback
  114. )
  115. )
  116. jobs.push(callback =>
  117. ProjectAuditLogHandler.addEntry(
  118. projectId,
  119. 'toggle-access-level',
  120. user._id,
  121. { publicAccessLevel: req.body.publicAccessLevel, status: 'OK' },
  122. callback
  123. )
  124. )
  125. async.series(jobs, error => {
  126. if (error != null) {
  127. return next(error)
  128. }
  129. res.sendStatus(204)
  130. })
  131. } else {
  132. res.sendStatus(500)
  133. }
  134. },
  135. deleteProject(req, res) {
  136. const projectId = req.params.Project_id
  137. const user = SessionManager.getSessionUser(req.session)
  138. const cb = err => {
  139. if (err != null) {
  140. res.sendStatus(500)
  141. } else {
  142. res.sendStatus(200)
  143. }
  144. }
  145. ProjectDeleter.deleteProject(
  146. projectId,
  147. { deleterUser: user, ipAddress: req.ip },
  148. cb
  149. )
  150. },
  151. archiveProject(req, res, next) {
  152. const projectId = req.params.Project_id
  153. const userId = SessionManager.getLoggedInUserId(req.session)
  154. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  155. if (err != null) {
  156. next(err)
  157. } else {
  158. res.sendStatus(200)
  159. }
  160. })
  161. },
  162. unarchiveProject(req, res, next) {
  163. const projectId = req.params.Project_id
  164. const userId = SessionManager.getLoggedInUserId(req.session)
  165. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  166. if (err != null) {
  167. next(err)
  168. } else {
  169. res.sendStatus(200)
  170. }
  171. })
  172. },
  173. trashProject(req, res, next) {
  174. const projectId = req.params.project_id
  175. const userId = SessionManager.getLoggedInUserId(req.session)
  176. ProjectDeleter.trashProject(projectId, userId, function (err) {
  177. if (err != null) {
  178. next(err)
  179. } else {
  180. res.sendStatus(200)
  181. }
  182. })
  183. },
  184. untrashProject(req, res, next) {
  185. const projectId = req.params.project_id
  186. const userId = SessionManager.getLoggedInUserId(req.session)
  187. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  188. if (err != null) {
  189. next(err)
  190. } else {
  191. res.sendStatus(200)
  192. }
  193. })
  194. },
  195. expireDeletedProjectsAfterDuration(req, res) {
  196. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  197. if (err != null) {
  198. res.sendStatus(500)
  199. } else {
  200. res.sendStatus(200)
  201. }
  202. })
  203. },
  204. expireDeletedProject(req, res, next) {
  205. const { projectId } = req.params
  206. ProjectDeleter.expireDeletedProject(projectId, err => {
  207. if (err != null) {
  208. next(err)
  209. } else {
  210. res.sendStatus(200)
  211. }
  212. })
  213. },
  214. restoreProject(req, res) {
  215. const projectId = req.params.Project_id
  216. ProjectDeleter.restoreProject(projectId, err => {
  217. if (err != null) {
  218. res.sendStatus(500)
  219. } else {
  220. res.sendStatus(200)
  221. }
  222. })
  223. },
  224. cloneProject(req, res, next) {
  225. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  226. metrics.inc('cloned-project')
  227. const projectId = req.params.Project_id
  228. const { projectName } = req.body
  229. logger.debug({ projectId, projectName }, 'cloning project')
  230. if (!SessionManager.isUserLoggedIn(req.session)) {
  231. return res.json({ redir: '/register' })
  232. }
  233. const currentUser = SessionManager.getSessionUser(req.session)
  234. const { first_name: firstName, last_name: lastName, email } = currentUser
  235. ProjectDuplicator.duplicate(
  236. currentUser,
  237. projectId,
  238. projectName,
  239. (err, project) => {
  240. if (err != null) {
  241. OError.tag(err, 'error cloning project', {
  242. projectId,
  243. userId: currentUser._id,
  244. })
  245. return next(err)
  246. }
  247. res.json({
  248. name: project.name,
  249. lastUpdated: project.lastUpdated,
  250. project_id: project._id,
  251. owner_ref: project.owner_ref,
  252. owner: {
  253. first_name: firstName,
  254. last_name: lastName,
  255. email,
  256. _id: currentUser._id,
  257. },
  258. })
  259. }
  260. )
  261. },
  262. newProject(req, res, next) {
  263. const currentUser = SessionManager.getSessionUser(req.session)
  264. const {
  265. first_name: firstName,
  266. last_name: lastName,
  267. email,
  268. _id: userId,
  269. } = currentUser
  270. const projectName =
  271. req.body.projectName != null ? req.body.projectName.trim() : undefined
  272. const { template } = req.body
  273. async.waterfall(
  274. [
  275. cb => {
  276. if (template === 'example') {
  277. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  278. } else {
  279. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  280. }
  281. },
  282. ],
  283. (err, project) => {
  284. if (err != null) {
  285. return next(err)
  286. }
  287. res.json({
  288. project_id: project._id,
  289. owner_ref: project.owner_ref,
  290. owner: {
  291. first_name: firstName,
  292. last_name: lastName,
  293. email,
  294. _id: userId,
  295. },
  296. })
  297. }
  298. )
  299. },
  300. renameProject(req, res, next) {
  301. const projectId = req.params.Project_id
  302. const newName = req.body.newProjectName
  303. EditorController.renameProject(projectId, newName, err => {
  304. if (err != null) {
  305. return next(err)
  306. }
  307. res.sendStatus(200)
  308. })
  309. },
  310. userProjectsJson(req, res, next) {
  311. const userId = SessionManager.getLoggedInUserId(req.session)
  312. ProjectGetter.findAllUsersProjects(
  313. userId,
  314. 'name lastUpdated publicAccesLevel archived trashed owner_ref',
  315. (err, projects) => {
  316. if (err != null) {
  317. return next(err)
  318. }
  319. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  320. projects = ProjectController._buildProjectList(projects, userId)
  321. .filter(p => !(p.archived || p.trashed))
  322. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  323. res.json({ projects })
  324. }
  325. )
  326. },
  327. projectEntitiesJson(req, res, next) {
  328. const projectId = req.params.Project_id
  329. ProjectGetter.getProject(projectId, (err, project) => {
  330. if (err != null) {
  331. return next(err)
  332. }
  333. let docs, files
  334. try {
  335. ;({ docs, files } =
  336. ProjectEntityHandler.getAllEntitiesFromProject(project))
  337. } catch (err) {
  338. return next(err)
  339. }
  340. const entities = docs
  341. .concat(files)
  342. // Sort by path ascending
  343. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  344. .map(e => ({
  345. path: e.path,
  346. type: e.doc != null ? 'doc' : 'file',
  347. }))
  348. res.json({ project_id: projectId, entities })
  349. })
  350. },
  351. loadEditor(req, res, next) {
  352. const timer = new metrics.Timer('load-editor')
  353. if (!Settings.editorIsOpen) {
  354. return res.render('general/closed', { title: 'updating_site' })
  355. }
  356. let anonymous, userId, sessionUser
  357. if (SessionManager.isUserLoggedIn(req.session)) {
  358. sessionUser = SessionManager.getSessionUser(req.session)
  359. userId = SessionManager.getLoggedInUserId(req.session)
  360. anonymous = false
  361. } else {
  362. sessionUser = null
  363. anonymous = true
  364. userId = null
  365. }
  366. const projectId = req.params.Project_id
  367. async.auto(
  368. {
  369. project(cb) {
  370. ProjectGetter.getProject(
  371. projectId,
  372. {
  373. name: 1,
  374. lastUpdated: 1,
  375. track_changes: 1,
  376. owner_ref: 1,
  377. brandVariationId: 1,
  378. overleaf: 1,
  379. tokens: 1,
  380. },
  381. (err, project) => {
  382. if (err != null) {
  383. return cb(err)
  384. }
  385. cb(null, project)
  386. }
  387. )
  388. },
  389. user(cb) {
  390. if (userId == null) {
  391. cb(null, defaultSettingsForAnonymousUser(userId))
  392. } else {
  393. User.updateOne(
  394. { _id: ObjectId(userId) },
  395. { $set: { lastActive: new Date() } },
  396. {},
  397. () => {}
  398. )
  399. User.findById(
  400. userId,
  401. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsProgramGalileo',
  402. (err, user) => {
  403. // Handle case of deleted user
  404. if (user == null) {
  405. UserController.logout(req, res, next)
  406. return
  407. }
  408. if (err) {
  409. return cb(err)
  410. }
  411. logger.debug({ projectId, userId }, 'got user')
  412. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  413. return cb(null, user)
  414. }
  415. ProjectController._refreshFeatures(req, user, cb)
  416. }
  417. )
  418. }
  419. },
  420. userHasInstitutionLicence(cb) {
  421. if (!userId) {
  422. return cb(null, false)
  423. }
  424. InstitutionsFeatures.hasLicence(userId, (error, hasLicence) => {
  425. if (error) {
  426. // Don't fail if we can't get affiliation licences
  427. return cb(null, false)
  428. }
  429. cb(null, hasLicence)
  430. })
  431. },
  432. learnedWords(cb) {
  433. if (!userId) {
  434. return cb(null, [])
  435. }
  436. SpellingHandler.getUserDictionary(userId, cb)
  437. },
  438. subscription(cb) {
  439. if (userId == null) {
  440. return cb()
  441. }
  442. SubscriptionLocator.getUsersSubscription(userId, cb)
  443. },
  444. userIsMemberOfGroupSubscription(cb) {
  445. if (sessionUser == null) {
  446. return cb(null, false)
  447. }
  448. LimitationsManager.userIsMemberOfGroupSubscription(
  449. sessionUser,
  450. (error, isMember) => {
  451. cb(error, isMember)
  452. }
  453. )
  454. },
  455. activate(cb) {
  456. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  457. },
  458. markAsOpened(cb) {
  459. // don't need to wait for this to complete
  460. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  461. cb()
  462. },
  463. isTokenMember(cb) {
  464. if (userId == null) {
  465. return cb()
  466. }
  467. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  468. },
  469. isInvitedMember(cb) {
  470. CollaboratorsGetter.isUserInvitedMemberOfProject(
  471. userId,
  472. projectId,
  473. cb
  474. )
  475. },
  476. brandVariation: [
  477. 'project',
  478. (results, cb) => {
  479. if (
  480. (results.project != null
  481. ? results.project.brandVariationId
  482. : undefined) == null
  483. ) {
  484. return cb()
  485. }
  486. BrandVariationsHandler.getBrandVariationById(
  487. results.project.brandVariationId,
  488. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  489. )
  490. },
  491. ],
  492. flushToTpds: cb => {
  493. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  494. },
  495. sharingModalSplitTest(cb) {
  496. SplitTestHandler.getAssignment(
  497. req,
  498. res,
  499. 'project-share-modal-paywall',
  500. {},
  501. () => {
  502. // do not fail editor load if assignment fails
  503. cb()
  504. }
  505. )
  506. },
  507. sharingModalNullTest(cb) {
  508. // null test targeting logged in users, for front-end side
  509. SplitTestHandler.getAssignment(
  510. req,
  511. res,
  512. 'null-test-share-modal',
  513. {},
  514. () => {
  515. // do not fail editor load if assignment fails
  516. cb()
  517. }
  518. )
  519. },
  520. pdfjsAssignment(cb) {
  521. SplitTestHandler.getAssignment(
  522. req,
  523. res,
  524. 'pdfjs-36',
  525. {},
  526. (error, assignment) => {
  527. // do not fail editor load if assignment fails
  528. if (error) {
  529. cb(null, { variant: 'default' })
  530. } else {
  531. cb(null, assignment)
  532. }
  533. }
  534. )
  535. },
  536. latexLogParserAssignment(cb) {
  537. SplitTestHandler.getAssignment(
  538. req,
  539. res,
  540. 'latex-log-parser',
  541. (error, assignment) => {
  542. // do not fail editor load if assignment fails
  543. if (error) {
  544. cb(null, { variant: 'default' })
  545. } else {
  546. cb(null, assignment)
  547. }
  548. }
  549. )
  550. },
  551. trackPdfDownloadAssignment(cb) {
  552. SplitTestHandler.getAssignment(req, res, 'track-pdf-download', () => {
  553. // We'll pick up the assignment from the res.locals assignment.
  554. cb()
  555. })
  556. },
  557. pdfCachingModeAssignment(cb) {
  558. SplitTestHandler.getAssignment(req, res, 'pdf-caching-mode', () => {
  559. // We'll pick up the assignment from the res.locals assignment.
  560. cb()
  561. })
  562. },
  563. pdfCachingPrefetchingAssignment(cb) {
  564. SplitTestHandler.getAssignment(
  565. req,
  566. res,
  567. 'pdf-caching-prefetching',
  568. () => {
  569. // We'll pick up the assignment from the res.locals assignment.
  570. cb()
  571. }
  572. )
  573. },
  574. pdfCachingPrefetchLargeAssignment(cb) {
  575. SplitTestHandler.getAssignment(
  576. req,
  577. res,
  578. 'pdf-caching-prefetch-large',
  579. () => {
  580. // We'll pick up the assignment from the res.locals assignment.
  581. cb()
  582. }
  583. )
  584. },
  585. pdfCachingCachedUrlLookupAssignment(cb) {
  586. SplitTestHandler.getAssignment(
  587. req,
  588. res,
  589. 'pdf-caching-cached-url-lookup',
  590. () => {
  591. // We'll pick up the assignment from the res.locals assignment.
  592. cb()
  593. }
  594. )
  595. },
  596. editorLeftMenuAssignment(cb) {
  597. SplitTestHandler.getAssignment(
  598. req,
  599. res,
  600. 'editor-left-menu',
  601. (error, assignment) => {
  602. // do not fail editor load if assignment fails
  603. if (error) {
  604. cb(null, { variant: 'default' })
  605. } else {
  606. cb(null, assignment)
  607. }
  608. }
  609. )
  610. },
  611. editorDocumentationButton(cb) {
  612. SplitTestHandler.getAssignment(
  613. req,
  614. res,
  615. 'documentation-on-editor',
  616. (error, assignment) => {
  617. // do not fail editor load if assignment fails
  618. if (error) {
  619. cb(null, { variant: 'default' })
  620. } else {
  621. cb(null, assignment)
  622. }
  623. }
  624. )
  625. },
  626. richTextAssignment(cb) {
  627. SplitTestHandler.getAssignment(
  628. req,
  629. res,
  630. 'rich-text',
  631. (error, assignment) => {
  632. // do not fail editor load if assignment fails
  633. if (error) {
  634. cb(null, { variant: 'default' })
  635. } else {
  636. cb(null, assignment)
  637. }
  638. }
  639. )
  640. },
  641. figureModalAssignment(cb) {
  642. SplitTestHandler.getAssignment(req, res, 'figure-modal', () => {
  643. // We'll pick up the assignment from the res.locals assignment.
  644. cb()
  645. })
  646. },
  647. tableGeneratorAssignment(cb) {
  648. SplitTestHandler.getAssignment(req, res, 'table-generator', () => {
  649. // We'll pick up the assignment from the res.locals assignment.
  650. cb()
  651. })
  652. },
  653. sourceEditorToolbarAssigment(cb) {
  654. SplitTestHandler.getAssignment(
  655. req,
  656. res,
  657. 'source-editor-toolbar',
  658. (error, assignment) => {
  659. // do not fail editor load if assignment fails
  660. if (error) {
  661. cb(null, { variant: 'default' })
  662. } else {
  663. cb(null, assignment)
  664. }
  665. }
  666. )
  667. },
  668. historyViewAssignment(cb) {
  669. SplitTestHandler.getAssignment(
  670. req,
  671. res,
  672. 'history-view',
  673. (error, assignment) => {
  674. // do not fail editor load if assignment fails
  675. if (error) {
  676. cb(null, { variant: 'default' })
  677. } else {
  678. cb(null, assignment)
  679. }
  680. }
  681. )
  682. },
  683. reviewPanelAssignment(cb) {
  684. SplitTestHandler.getAssignment(
  685. req,
  686. res,
  687. 'review-panel',
  688. (error, assignment) => {
  689. // do not fail editor load if assignment fails
  690. if (error) {
  691. cb(null, { variant: 'default' })
  692. } else {
  693. cb(null, assignment)
  694. }
  695. }
  696. )
  697. },
  698. },
  699. (
  700. err,
  701. {
  702. project,
  703. user,
  704. userHasInstitutionLicence,
  705. learnedWords,
  706. subscription,
  707. userIsMemberOfGroupSubscription,
  708. isTokenMember,
  709. isInvitedMember,
  710. brandVariation,
  711. pdfjsAssignment,
  712. editorLeftMenuAssignment,
  713. richTextAssignment,
  714. sourceEditorToolbarAssigment,
  715. historyViewAssignment,
  716. reviewPanelAssignment,
  717. }
  718. ) => {
  719. if (err != null) {
  720. OError.tag(err, 'error getting details for project page')
  721. return next(err)
  722. }
  723. const anonRequestToken = TokenAccessHandler.getRequestToken(
  724. req,
  725. projectId
  726. )
  727. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  728. AuthorizationManager.getPrivilegeLevelForProject(
  729. userId,
  730. projectId,
  731. anonRequestToken,
  732. (error, privilegeLevel) => {
  733. let allowedFreeTrial = true
  734. if (error != null) {
  735. return next(error)
  736. }
  737. if (
  738. privilegeLevel == null ||
  739. privilegeLevel === PrivilegeLevels.NONE
  740. ) {
  741. return res.sendStatus(401)
  742. }
  743. if (subscription != null) {
  744. allowedFreeTrial = false
  745. }
  746. let wsUrl = Settings.wsUrl
  747. let metricName = 'load-editor-ws'
  748. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  749. wsUrl = Settings.wsUrlBeta
  750. metricName += '-beta'
  751. } else if (
  752. Settings.wsUrlV2 &&
  753. Settings.wsUrlV2Percentage > 0 &&
  754. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  755. Settings.wsUrlV2Percentage
  756. ) {
  757. wsUrl = Settings.wsUrlV2
  758. metricName += '-v2'
  759. }
  760. if (req.query && req.query.ws === 'fallback') {
  761. // `?ws=fallback` will connect to the bare origin, and ignore
  762. // the custom wsUrl. Hence it must load the client side
  763. // javascript from there too.
  764. // Not resetting it here would possibly load a socket.io v2
  765. // client and connect to a v0 endpoint.
  766. wsUrl = undefined
  767. metricName += '-fallback'
  768. }
  769. metrics.inc(metricName)
  770. if (userId) {
  771. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  772. projectId: project._id,
  773. })
  774. }
  775. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  776. function shouldDisplayFeature(name, variantFlag) {
  777. if (req.query && req.query[name]) {
  778. return req.query[name] === 'true'
  779. } else {
  780. return variantFlag === true
  781. }
  782. }
  783. const isAdminOrTemplateOwner =
  784. hasAdminAccess(user) || Settings.templates?.user_id === userId
  785. const showTemplatesServerPro =
  786. Features.hasFeature('templates-server-pro') &&
  787. isAdminOrTemplateOwner
  788. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  789. const detachRole = req.params.detachRole
  790. const showLegacySourceEditor =
  791. !Features.hasFeature('saas') ||
  792. // Allow override via legacy_source_editor=true in query string
  793. shouldDisplayFeature('legacy_source_editor')
  794. const editorLeftMenuReact =
  795. editorLeftMenuAssignment?.variant === 'react'
  796. const showSymbolPalette =
  797. !Features.hasFeature('saas') ||
  798. (user.features && user.features.symbolPalette)
  799. // It would be nice if this could go in the Galileo module but
  800. // nothing else does that
  801. const galileoEnabled = req.query?.galileo || ''
  802. const galileoFeatures =
  803. req.query && 'galileoFeatures' in req.query
  804. ? req.query.galileoFeatures.split(',').map(f => f.trim())
  805. : ['all']
  806. const galileoPromptWords = req.query?.galileoPromptWords || ''
  807. // Persistent upgrade prompts
  808. // in header & in share project modal
  809. const showUpgradePrompt =
  810. Features.hasFeature('saas') &&
  811. userId &&
  812. !subscription &&
  813. !userIsMemberOfGroupSubscription &&
  814. !userHasInstitutionLicence
  815. const showPersonalAccessToken =
  816. !Features.hasFeature('saas') ||
  817. req.query?.personal_access_token === 'true'
  818. const template =
  819. detachRole === 'detached'
  820. ? 'project/editor_detached'
  821. : 'project/editor'
  822. let richTextVariant
  823. if (!Features.hasFeature('saas')) {
  824. richTextVariant = 'cm6'
  825. } else {
  826. richTextVariant = richTextAssignment.variant
  827. }
  828. res.render(template, {
  829. title: project.name,
  830. priority_title: true,
  831. bodyClasses: ['editor'],
  832. project_id: project._id,
  833. projectName: project.name,
  834. editorLeftMenuReact,
  835. user: {
  836. id: userId,
  837. email: user.email,
  838. first_name: user.first_name,
  839. last_name: user.last_name,
  840. referal_id: user.referal_id,
  841. signUpDate: user.signUpDate,
  842. allowedFreeTrial,
  843. featureSwitches: user.featureSwitches,
  844. features: user.features,
  845. refProviders: _.mapValues(user.refProviders, Boolean),
  846. alphaProgram: user.alphaProgram,
  847. betaProgram: user.betaProgram,
  848. labsProgram: user.labsProgram,
  849. labsProgramGalileo: user.labsProgramGalileo,
  850. isAdmin: hasAdminAccess(user),
  851. },
  852. userSettings: {
  853. mode: user.ace.mode,
  854. editorTheme: user.ace.theme,
  855. fontSize: user.ace.fontSize,
  856. autoComplete: user.ace.autoComplete,
  857. autoPairDelimiters: user.ace.autoPairDelimiters,
  858. pdfViewer: user.ace.pdfViewer,
  859. syntaxValidation: user.ace.syntaxValidation,
  860. fontFamily: user.ace.fontFamily || 'lucida',
  861. lineHeight: user.ace.lineHeight || 'normal',
  862. overallTheme: user.ace.overallTheme,
  863. },
  864. privilegeLevel,
  865. anonymous,
  866. anonymousAccessToken: anonymous ? anonRequestToken : null,
  867. isTokenMember,
  868. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  869. userId,
  870. privilegeLevel,
  871. isTokenMember,
  872. isInvitedMember
  873. ),
  874. languages: Settings.languages,
  875. learnedWords,
  876. editorThemes: THEME_LIST,
  877. legacyEditorThemes: LEGACY_THEME_LIST,
  878. maxDocLength: Settings.max_doc_length,
  879. brandVariation,
  880. allowedImageNames,
  881. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  882. wsUrl,
  883. showSupport: Features.hasFeature('support'),
  884. showTemplatesServerPro,
  885. pdfjsVariant: pdfjsAssignment.variant,
  886. debugPdfDetach,
  887. showLegacySourceEditor,
  888. showSourceToolbar:
  889. !showLegacySourceEditor &&
  890. sourceEditorToolbarAssigment.variant === 'enabled',
  891. showSymbolPalette,
  892. symbolPaletteAvailable: Features.hasFeature('symbol-palette'),
  893. galileoEnabled,
  894. galileoFeatures,
  895. galileoPromptWords,
  896. detachRole,
  897. metadata: { viewport: false },
  898. showUpgradePrompt,
  899. fixedSizeDocument: true,
  900. useOpenTelemetry: Settings.useOpenTelemetryClient,
  901. showCM6SwitchAwaySurvey: Settings.showCM6SwitchAwaySurvey,
  902. richTextVariant,
  903. historyViewReact: historyViewAssignment.variant === 'react',
  904. isReviewPanelReact: reviewPanelAssignment.variant === 'react',
  905. showPersonalAccessToken,
  906. hasTrackChangesFeature: Features.hasFeature('track-changes'),
  907. })
  908. timer.done()
  909. }
  910. )
  911. }
  912. )
  913. },
  914. _refreshFeatures(req, user, callback) {
  915. // If the feature refresh has failed in this session, don't retry
  916. // it - require the user to log in again.
  917. if (req.session.feature_refresh_failed) {
  918. metrics.inc('features-refresh', 1, {
  919. path: 'load-editor',
  920. status: 'skipped',
  921. })
  922. return callback(null, user)
  923. }
  924. // If the refresh takes too long then return the current
  925. // features. Note that the user.features property may still be
  926. // updated in the background after the callback is called.
  927. callback = _.once(callback)
  928. const refreshTimeoutHandler = setTimeout(() => {
  929. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  930. metrics.inc('features-refresh', 1, {
  931. path: 'load-editor',
  932. status: 'timeout',
  933. })
  934. callback(null, user)
  935. }, 5000)
  936. // try to refresh user features now
  937. const timer = new metrics.Timer('features-refresh-on-load-editor')
  938. FeaturesUpdater.refreshFeatures(
  939. user._id,
  940. 'load-editor',
  941. (err, features) => {
  942. clearTimeout(refreshTimeoutHandler)
  943. timer.done()
  944. if (err) {
  945. // keep a record to prevent unneceary retries and leave
  946. // the original features unmodified if the refresh failed
  947. req.session.feature_refresh_failed = {
  948. reason: 'error',
  949. at: new Date(),
  950. }
  951. metrics.inc('features-refresh', 1, {
  952. path: 'load-editor',
  953. status: 'error',
  954. })
  955. } else {
  956. user.features = features
  957. metrics.inc('features-refresh', 1, {
  958. path: 'load-editor',
  959. status: 'success',
  960. })
  961. }
  962. callback(null, user)
  963. }
  964. )
  965. },
  966. _buildProjectList(allProjects, userId) {
  967. let project
  968. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  969. allProjects
  970. const projects = []
  971. for (project of owned) {
  972. projects.push(
  973. ProjectController._buildProjectViewModel(
  974. project,
  975. 'owner',
  976. Sources.OWNER,
  977. userId
  978. )
  979. )
  980. }
  981. // Invite-access
  982. for (project of readAndWrite) {
  983. projects.push(
  984. ProjectController._buildProjectViewModel(
  985. project,
  986. 'readWrite',
  987. Sources.INVITE,
  988. userId
  989. )
  990. )
  991. }
  992. for (project of readOnly) {
  993. projects.push(
  994. ProjectController._buildProjectViewModel(
  995. project,
  996. 'readOnly',
  997. Sources.INVITE,
  998. userId
  999. )
  1000. )
  1001. }
  1002. // Token-access
  1003. // Only add these projects if they're not already present, this gives us cascading access
  1004. // from 'owner' => 'token-read-only'
  1005. for (project of tokenReadAndWrite) {
  1006. if (
  1007. projects.filter(p => p.id.toString() === project._id.toString())
  1008. .length === 0
  1009. ) {
  1010. projects.push(
  1011. ProjectController._buildProjectViewModel(
  1012. project,
  1013. 'readAndWrite',
  1014. Sources.TOKEN,
  1015. userId
  1016. )
  1017. )
  1018. }
  1019. }
  1020. for (project of tokenReadOnly) {
  1021. if (
  1022. projects.filter(p => p.id.toString() === project._id.toString())
  1023. .length === 0
  1024. ) {
  1025. projects.push(
  1026. ProjectController._buildProjectViewModel(
  1027. project,
  1028. 'readOnly',
  1029. Sources.TOKEN,
  1030. userId
  1031. )
  1032. )
  1033. }
  1034. }
  1035. return projects
  1036. },
  1037. _buildProjectViewModel(project, accessLevel, source, userId) {
  1038. const archived = ProjectHelper.isArchived(project, userId)
  1039. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1040. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1041. const model = {
  1042. id: project._id,
  1043. name: project.name,
  1044. lastUpdated: project.lastUpdated,
  1045. lastUpdatedBy: project.lastUpdatedBy,
  1046. publicAccessLevel: project.publicAccesLevel,
  1047. accessLevel,
  1048. source,
  1049. archived,
  1050. trashed,
  1051. owner_ref: project.owner_ref,
  1052. isV1Project: false,
  1053. }
  1054. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1055. model.owner_ref = null
  1056. model.lastUpdatedBy = null
  1057. }
  1058. return model
  1059. },
  1060. _injectProjectUsers(projects, callback) {
  1061. const users = {}
  1062. for (const project of projects) {
  1063. if (project.owner_ref != null) {
  1064. users[project.owner_ref.toString()] = true
  1065. }
  1066. if (project.lastUpdatedBy != null) {
  1067. users[project.lastUpdatedBy.toString()] = true
  1068. }
  1069. }
  1070. const userIds = Object.keys(users)
  1071. async.eachSeries(
  1072. userIds,
  1073. (userId, cb) => {
  1074. UserGetter.getUser(
  1075. userId,
  1076. { first_name: 1, last_name: 1, email: 1 },
  1077. (error, user) => {
  1078. if (error != null) {
  1079. return cb(error)
  1080. }
  1081. users[userId] = user
  1082. cb()
  1083. }
  1084. )
  1085. },
  1086. error => {
  1087. if (error != null) {
  1088. return callback(error)
  1089. }
  1090. for (const project of projects) {
  1091. if (project.owner_ref != null) {
  1092. project.owner = users[project.owner_ref.toString()]
  1093. }
  1094. if (project.lastUpdatedBy != null) {
  1095. project.lastUpdatedBy =
  1096. users[project.lastUpdatedBy.toString()] || null
  1097. }
  1098. }
  1099. callback(null, projects)
  1100. }
  1101. )
  1102. },
  1103. _buildPortalTemplatesList(affiliations) {
  1104. if (affiliations == null) {
  1105. affiliations = []
  1106. }
  1107. const portalTemplates = []
  1108. for (const aff of affiliations) {
  1109. if (
  1110. aff.portal &&
  1111. aff.portal.slug &&
  1112. aff.portal.templates_count &&
  1113. aff.portal.templates_count > 0
  1114. ) {
  1115. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1116. portalTemplates.push({
  1117. name: aff.institution.name,
  1118. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1119. })
  1120. }
  1121. }
  1122. return portalTemplates
  1123. },
  1124. }
  1125. const defaultSettingsForAnonymousUser = userId => ({
  1126. id: userId,
  1127. ace: {
  1128. mode: 'none',
  1129. theme: 'textmate',
  1130. fontSize: '12',
  1131. autoComplete: true,
  1132. spellCheckLanguage: '',
  1133. pdfViewer: '',
  1134. syntaxValidation: true,
  1135. },
  1136. subscription: {
  1137. freeTrial: {
  1138. allowed: true,
  1139. },
  1140. },
  1141. featureSwitches: {
  1142. github: false,
  1143. },
  1144. alphaProgram: false,
  1145. betaProgram: false,
  1146. })
  1147. const THEME_LIST = [
  1148. 'cobalt',
  1149. 'dracula',
  1150. 'eclipse',
  1151. 'monokai',
  1152. 'overleaf',
  1153. 'textmate',
  1154. ]
  1155. const LEGACY_THEME_LIST = [
  1156. 'ambiance',
  1157. 'chaos',
  1158. 'chrome',
  1159. 'clouds',
  1160. 'clouds_midnight',
  1161. 'crimson_editor',
  1162. 'dawn',
  1163. 'dreamweaver',
  1164. 'github',
  1165. 'gob',
  1166. 'gruvbox',
  1167. 'idle_fingers',
  1168. 'iplastic',
  1169. 'katzenmilch',
  1170. 'kr_theme',
  1171. 'kuroir',
  1172. 'merbivore',
  1173. 'merbivore_soft',
  1174. 'mono_industrial',
  1175. 'nord_dark',
  1176. 'pastel_on_dark',
  1177. 'solarized_dark',
  1178. 'solarized_light',
  1179. 'sqlserver',
  1180. 'terminal',
  1181. 'tomorrow',
  1182. 'tomorrow_night',
  1183. 'tomorrow_night_blue',
  1184. 'tomorrow_night_bright',
  1185. 'tomorrow_night_eighties',
  1186. 'twilight',
  1187. 'vibrant_ink',
  1188. 'xcode',
  1189. ]
  1190. module.exports = ProjectController