ProjectController.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. /* eslint-disable
  2. camelcase
  3. */
  4. const Path = require('path')
  5. const fs = require('fs')
  6. const crypto = require('crypto')
  7. const async = require('async')
  8. const logger = require('logger-sharelatex')
  9. const { ObjectId } = require('../../infrastructure/mongojs')
  10. const ProjectDeleter = require('./ProjectDeleter')
  11. const ProjectDuplicator = require('./ProjectDuplicator')
  12. const ProjectCreationHandler = require('./ProjectCreationHandler')
  13. const EditorController = require('../Editor/EditorController')
  14. const ProjectHelper = require('./ProjectHelper')
  15. const metrics = require('metrics-sharelatex')
  16. const { User } = require('../../models/User')
  17. const TagsHandler = require('../Tags/TagsHandler')
  18. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  19. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  20. const LimitationsManager = require('../Subscription/LimitationsManager')
  21. const Settings = require('settings-sharelatex')
  22. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  23. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  24. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  25. const ProjectGetter = require('./ProjectGetter')
  26. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  27. const AuthenticationController = require('../Authentication/AuthenticationController')
  28. const PackageVersions = require('../../infrastructure/PackageVersions')
  29. const Sources = require('../Authorization/Sources')
  30. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  31. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  32. const ProjectEntityHandler = require('./ProjectEntityHandler')
  33. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  34. const UserGetter = require('../User/UserGetter')
  35. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  36. const { V1ConnectionError } = require('../Errors/Errors')
  37. const Features = require('../../infrastructure/Features')
  38. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  39. const { getUserAffiliations } = require('../Institutions/InstitutionsAPI')
  40. const UserController = require('../User/UserController')
  41. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  42. if (!affiliation.institution) return false
  43. // institution.confirmed is for the domain being confirmed, not the email
  44. // Do not show SSO UI for unconfirmed domains
  45. if (!affiliation.institution.confirmed) return false
  46. // Could have multiple emails at the same institution, and if any are
  47. // linked to the institution then do not show notification for others
  48. if (
  49. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  50. ) {
  51. if (affiliation.institution.ssoEnabled) return true
  52. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  53. return false
  54. }
  55. return false
  56. }
  57. const ProjectController = {
  58. _isInPercentageRollout(rolloutName, objectId, percentage) {
  59. if (Settings.bypassPercentageRollouts === true) {
  60. return true
  61. }
  62. const data = `${rolloutName}:${objectId.toString()}`
  63. const md5hash = crypto
  64. .createHash('md5')
  65. .update(data)
  66. .digest('hex')
  67. const counter = parseInt(md5hash.slice(26, 32), 16)
  68. return counter % 100 < percentage
  69. },
  70. updateProjectSettings(req, res, next) {
  71. const projectId = req.params.Project_id
  72. const jobs = []
  73. if (req.body.compiler != null) {
  74. jobs.push(callback =>
  75. EditorController.setCompiler(projectId, req.body.compiler, callback)
  76. )
  77. }
  78. if (req.body.imageName != null) {
  79. jobs.push(callback =>
  80. EditorController.setImageName(projectId, req.body.imageName, callback)
  81. )
  82. }
  83. if (req.body.name != null) {
  84. jobs.push(callback =>
  85. EditorController.renameProject(projectId, req.body.name, callback)
  86. )
  87. }
  88. if (req.body.spellCheckLanguage != null) {
  89. jobs.push(callback =>
  90. EditorController.setSpellCheckLanguage(
  91. projectId,
  92. req.body.spellCheckLanguage,
  93. callback
  94. )
  95. )
  96. }
  97. if (req.body.rootDocId != null) {
  98. jobs.push(callback =>
  99. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  100. )
  101. }
  102. async.series(jobs, error => {
  103. if (error != null) {
  104. return next(error)
  105. }
  106. res.sendStatus(204)
  107. })
  108. },
  109. updateProjectAdminSettings(req, res, next) {
  110. const projectId = req.params.Project_id
  111. const jobs = []
  112. if (req.body.publicAccessLevel != null) {
  113. jobs.push(callback =>
  114. EditorController.setPublicAccessLevel(
  115. projectId,
  116. req.body.publicAccessLevel,
  117. callback
  118. )
  119. )
  120. }
  121. async.series(jobs, error => {
  122. if (error != null) {
  123. return next(error)
  124. }
  125. res.sendStatus(204)
  126. })
  127. },
  128. deleteProject(req, res) {
  129. const projectId = req.params.Project_id
  130. const user = AuthenticationController.getSessionUser(req)
  131. const cb = err => {
  132. if (err != null) {
  133. res.sendStatus(500)
  134. } else {
  135. res.sendStatus(200)
  136. }
  137. }
  138. ProjectDeleter.deleteProject(
  139. projectId,
  140. { deleterUser: user, ipAddress: req.ip },
  141. cb
  142. )
  143. },
  144. archiveProject(req, res, next) {
  145. const projectId = req.params.Project_id
  146. const userId = AuthenticationController.getLoggedInUserId(req)
  147. ProjectDeleter.archiveProject(projectId, userId, function(err) {
  148. if (err != null) {
  149. return next(err)
  150. } else {
  151. return res.sendStatus(200)
  152. }
  153. })
  154. },
  155. unarchiveProject(req, res, next) {
  156. const projectId = req.params.Project_id
  157. const userId = AuthenticationController.getLoggedInUserId(req)
  158. ProjectDeleter.unarchiveProject(projectId, userId, function(err) {
  159. if (err != null) {
  160. return next(err)
  161. } else {
  162. return res.sendStatus(200)
  163. }
  164. })
  165. },
  166. trashProject(req, res, next) {
  167. const projectId = req.params.project_id
  168. const userId = AuthenticationController.getLoggedInUserId(req)
  169. ProjectDeleter.trashProject(projectId, userId, function(err) {
  170. if (err != null) {
  171. return next(err)
  172. } else {
  173. return res.sendStatus(200)
  174. }
  175. })
  176. },
  177. untrashProject(req, res, next) {
  178. const projectId = req.params.project_id
  179. const userId = AuthenticationController.getLoggedInUserId(req)
  180. ProjectDeleter.untrashProject(projectId, userId, function(err) {
  181. if (err != null) {
  182. return next(err)
  183. } else {
  184. return res.sendStatus(200)
  185. }
  186. })
  187. },
  188. expireDeletedProjectsAfterDuration(req, res) {
  189. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  190. if (err != null) {
  191. res.sendStatus(500)
  192. } else {
  193. res.sendStatus(200)
  194. }
  195. })
  196. },
  197. expireDeletedProject(req, res, next) {
  198. const { projectId } = req.params
  199. ProjectDeleter.expireDeletedProject(projectId, err => {
  200. if (err != null) {
  201. next(err)
  202. } else {
  203. res.sendStatus(200)
  204. }
  205. })
  206. },
  207. restoreProject(req, res) {
  208. const projectId = req.params.Project_id
  209. ProjectDeleter.restoreProject(projectId, err => {
  210. if (err != null) {
  211. res.sendStatus(500)
  212. } else {
  213. res.sendStatus(200)
  214. }
  215. })
  216. },
  217. cloneProject(req, res, next) {
  218. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  219. metrics.inc('cloned-project')
  220. const projectId = req.params.Project_id
  221. const { projectName } = req.body
  222. logger.log({ projectId, projectName }, 'cloning project')
  223. if (!AuthenticationController.isUserLoggedIn(req)) {
  224. return res.send({ redir: '/register' })
  225. }
  226. const currentUser = AuthenticationController.getSessionUser(req)
  227. const { first_name, last_name, email } = currentUser
  228. ProjectDuplicator.duplicate(
  229. currentUser,
  230. projectId,
  231. projectName,
  232. (err, project) => {
  233. if (err != null) {
  234. logger.warn(
  235. { err, projectId, userId: currentUser._id },
  236. 'error cloning project'
  237. )
  238. return next(err)
  239. }
  240. res.send({
  241. name: project.name,
  242. project_id: project._id,
  243. owner_ref: project.owner_ref,
  244. owner: { first_name, last_name, email, _id: currentUser._id }
  245. })
  246. }
  247. )
  248. },
  249. newProject(req, res, next) {
  250. const userId = AuthenticationController.getLoggedInUserId(req)
  251. const projectName =
  252. req.body.projectName != null ? req.body.projectName.trim() : undefined
  253. const { template } = req.body
  254. async.waterfall(
  255. [
  256. cb => {
  257. if (template === 'example') {
  258. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  259. } else {
  260. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  261. }
  262. }
  263. ],
  264. (err, project) => {
  265. if (err != null) {
  266. return next(err)
  267. }
  268. res.send({ project_id: project._id })
  269. }
  270. )
  271. },
  272. renameProject(req, res, next) {
  273. const projectId = req.params.Project_id
  274. const newName = req.body.newProjectName
  275. EditorController.renameProject(projectId, newName, err => {
  276. if (err != null) {
  277. return next(err)
  278. }
  279. res.sendStatus(200)
  280. })
  281. },
  282. userProjectsJson(req, res, next) {
  283. const userId = AuthenticationController.getLoggedInUserId(req)
  284. ProjectGetter.findAllUsersProjects(
  285. userId,
  286. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  287. (err, projects) => {
  288. if (err != null) {
  289. return next(err)
  290. }
  291. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  292. projects = ProjectController._buildProjectList(projects, userId)
  293. .filter(p => !(p.archived || p.trashed))
  294. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  295. res.json({ projects })
  296. }
  297. )
  298. },
  299. projectEntitiesJson(req, res, next) {
  300. const projectId = req.params.Project_id
  301. ProjectGetter.getProject(projectId, (err, project) => {
  302. if (err != null) {
  303. return next(err)
  304. }
  305. ProjectEntityHandler.getAllEntitiesFromProject(
  306. project,
  307. (err, docs, files) => {
  308. if (err != null) {
  309. return next(err)
  310. }
  311. const entities = docs
  312. .concat(files)
  313. .sort((a, b) => a.path > b.path) // Sort by path ascending
  314. .map(e => ({
  315. path: e.path,
  316. type: e.doc != null ? 'doc' : 'file'
  317. }))
  318. res.json({ project_id: projectId, entities })
  319. }
  320. )
  321. })
  322. },
  323. projectListPage(req, res, next) {
  324. const timer = new metrics.Timer('project-list')
  325. const userId = AuthenticationController.getLoggedInUserId(req)
  326. const currentUser = AuthenticationController.getSessionUser(req)
  327. let noV1Connection = false
  328. let institutionLinkingError
  329. async.parallel(
  330. {
  331. tags(cb) {
  332. TagsHandler.getAllTags(userId, cb)
  333. },
  334. notifications(cb) {
  335. NotificationsHandler.getUserNotifications(userId, cb)
  336. },
  337. projects(cb) {
  338. ProjectGetter.findAllUsersProjects(
  339. userId,
  340. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  341. cb
  342. )
  343. },
  344. hasSubscription(cb) {
  345. LimitationsManager.hasPaidSubscription(
  346. currentUser,
  347. (error, hasPaidSubscription) => {
  348. if (error != null && error instanceof V1ConnectionError) {
  349. noV1Connection = true
  350. return cb(null, true)
  351. }
  352. cb(error, hasPaidSubscription)
  353. }
  354. )
  355. },
  356. user(cb) {
  357. User.findById(
  358. userId,
  359. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  360. cb
  361. )
  362. },
  363. userAffiliations(cb) {
  364. if (!Features.hasFeature('affiliations')) {
  365. return cb(null, [])
  366. }
  367. getUserAffiliations(userId, (error, affiliations) => {
  368. if (error && error instanceof V1ConnectionError) {
  369. noV1Connection = true
  370. return cb(null, [])
  371. }
  372. cb(error, affiliations)
  373. })
  374. }
  375. },
  376. (err, results) => {
  377. if (err != null) {
  378. logger.warn({ err }, 'error getting data for project list page')
  379. return next(err)
  380. }
  381. const { notifications, user, userAffiliations } = results
  382. // Handle case of deleted user
  383. if (user == null) {
  384. UserController.logout(req, res, next)
  385. return
  386. }
  387. const tags = results.tags
  388. const notificationsInstitution = []
  389. for (const notification of notifications) {
  390. notification.html = req.i18n.translate(
  391. notification.templateKey,
  392. notification.messageOpts
  393. )
  394. }
  395. // Institution SSO Notifications
  396. if (Features.hasFeature('saml')) {
  397. const samlSession = req.session.saml
  398. // Notification: SSO Available
  399. const linkedInstitutionIds = []
  400. user.emails.forEach(email => {
  401. if (email.samlProviderId) {
  402. linkedInstitutionIds.push(email.samlProviderId)
  403. }
  404. })
  405. if (Array.isArray(userAffiliations)) {
  406. userAffiliations.forEach(affiliation => {
  407. if (
  408. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  409. ) {
  410. notificationsInstitution.push({
  411. email: affiliation.email,
  412. institutionId: affiliation.institution.id,
  413. institutionName: affiliation.institution.name,
  414. templateKey: 'notification_institution_sso_available'
  415. })
  416. }
  417. })
  418. }
  419. if (samlSession) {
  420. // Notification: After SSO Linked
  421. if (samlSession.linked) {
  422. notificationsInstitution.push({
  423. email: samlSession.institutionEmail,
  424. institutionName: samlSession.linked.universityName,
  425. templateKey: 'notification_institution_sso_linked'
  426. })
  427. }
  428. // Notification: After SSO Linked or Logging in
  429. // The requested email does not match primary email returned from
  430. // the institution
  431. if (
  432. samlSession.requestedEmail &&
  433. samlSession.emailNonCanonical &&
  434. !samlSession.linkedToAnother
  435. ) {
  436. notificationsInstitution.push({
  437. institutionEmail: samlSession.emailNonCanonical,
  438. requestedEmail: samlSession.requestedEmail,
  439. templateKey: 'notification_institution_sso_non_canonical'
  440. })
  441. }
  442. // Notification: Tried to register, but account already existed
  443. // registerIntercept is set before the institution callback.
  444. // institutionEmail is set after institution callback.
  445. // Check for both in case SSO flow was abandoned
  446. if (
  447. samlSession.registerIntercept &&
  448. samlSession.institutionEmail &&
  449. !samlSession.linkedToAnother
  450. ) {
  451. notificationsInstitution.push({
  452. email: samlSession.institutionEmail,
  453. templateKey: 'notification_institution_sso_already_registered'
  454. })
  455. }
  456. // Notification: Already linked to another account
  457. if (samlSession.linkedToAnother) {
  458. notificationsInstitution.push({
  459. templateKey: 'notification_institution_sso_linked_by_another'
  460. })
  461. }
  462. // Notification: When there is a session error
  463. if (samlSession.error) {
  464. institutionLinkingError = samlSession.error
  465. notificationsInstitution.push({
  466. message: samlSession.error.message,
  467. templateKey: 'notification_institution_sso_error',
  468. tryAgain: samlSession.error.tryAgain
  469. })
  470. }
  471. }
  472. delete req.session.saml
  473. }
  474. const portalTemplates = ProjectController._buildPortalTemplatesList(
  475. userAffiliations
  476. )
  477. const projects = ProjectController._buildProjectList(
  478. results.projects,
  479. userId
  480. )
  481. const warnings = ProjectController._buildWarningsList(noV1Connection)
  482. // in v2 add notifications for matching university IPs
  483. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  484. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  485. }
  486. ProjectController._injectProjectUsers(projects, (error, projects) => {
  487. if (error != null) {
  488. return next(error)
  489. }
  490. const viewModel = {
  491. title: 'your_projects',
  492. priority_title: true,
  493. projects,
  494. tags,
  495. notifications: notifications || [],
  496. notificationsInstitution,
  497. portalTemplates,
  498. user,
  499. userAffiliations,
  500. hasSubscription: results.hasSubscription,
  501. institutionLinkingError,
  502. warnings,
  503. zipFileSizeLimit: Settings.maxUploadSize
  504. }
  505. if (
  506. Settings.algolia &&
  507. Settings.algolia.app_id &&
  508. Settings.algolia.read_only_api_key
  509. ) {
  510. viewModel.showUserDetailsArea = true
  511. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  512. viewModel.algolia_app_id = Settings.algolia.app_id
  513. } else {
  514. viewModel.showUserDetailsArea = false
  515. }
  516. const paidUser =
  517. (user.features != null ? user.features.github : undefined) &&
  518. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  519. const freeUserProportion = 0.1
  520. const sampleFreeUser =
  521. parseInt(user._id.toString().slice(-2), 16) <
  522. freeUserProportion * 255
  523. const showFrontWidget = paidUser || sampleFreeUser
  524. if (showFrontWidget) {
  525. viewModel.frontChatWidgetRoomId =
  526. Settings.overleaf != null
  527. ? Settings.overleaf.front_chat_widget_room_id
  528. : undefined
  529. }
  530. res.render('project/list', viewModel)
  531. timer.done()
  532. })
  533. }
  534. )
  535. },
  536. loadEditor(req, res, next) {
  537. let anonymous, userId
  538. const timer = new metrics.Timer('load-editor')
  539. if (!Settings.editorIsOpen) {
  540. return res.render('general/closed', { title: 'updating_site' })
  541. }
  542. if (AuthenticationController.isUserLoggedIn(req)) {
  543. userId = AuthenticationController.getLoggedInUserId(req)
  544. anonymous = false
  545. } else {
  546. anonymous = true
  547. userId = null
  548. }
  549. const projectId = req.params.Project_id
  550. async.auto(
  551. {
  552. project(cb) {
  553. ProjectGetter.getProject(
  554. projectId,
  555. {
  556. name: 1,
  557. lastUpdated: 1,
  558. track_changes: 1,
  559. owner_ref: 1,
  560. brandVariationId: 1,
  561. overleaf: 1,
  562. tokens: 1
  563. },
  564. (err, project) => {
  565. if (err != null) {
  566. return cb(err)
  567. }
  568. cb(null, project)
  569. }
  570. )
  571. },
  572. user(cb) {
  573. if (userId == null) {
  574. cb(null, defaultSettingsForAnonymousUser(userId))
  575. } else {
  576. User.findById(userId, (err, user) => {
  577. // Handle case of deleted user
  578. if (user == null) {
  579. UserController.logout(req, res, next)
  580. return
  581. }
  582. logger.log({ projectId, userId }, 'got user')
  583. cb(err, user)
  584. })
  585. }
  586. },
  587. subscription(cb) {
  588. if (userId == null) {
  589. return cb()
  590. }
  591. SubscriptionLocator.getUsersSubscription(userId, cb)
  592. },
  593. activate(cb) {
  594. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  595. },
  596. markAsOpened(cb) {
  597. // don't need to wait for this to complete
  598. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  599. cb()
  600. },
  601. isTokenMember(cb) {
  602. if (userId == null) {
  603. return cb()
  604. }
  605. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  606. },
  607. brandVariation: [
  608. 'project',
  609. (cb, results) => {
  610. if (
  611. (results.project != null
  612. ? results.project.brandVariationId
  613. : undefined) == null
  614. ) {
  615. return cb()
  616. }
  617. BrandVariationsHandler.getBrandVariationById(
  618. results.project.brandVariationId,
  619. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  620. )
  621. }
  622. ],
  623. flushToTpds: cb => {
  624. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  625. }
  626. },
  627. (err, results) => {
  628. if (err != null) {
  629. logger.warn({ err }, 'error getting details for project page')
  630. return next(err)
  631. }
  632. const { project } = results
  633. const { user } = results
  634. const { subscription } = results
  635. const { brandVariation } = results
  636. const anonRequestToken = TokenAccessHandler.getRequestToken(
  637. req,
  638. projectId
  639. )
  640. const { isTokenMember } = results
  641. AuthorizationManager.getPrivilegeLevelForProject(
  642. userId,
  643. projectId,
  644. anonRequestToken,
  645. (error, privilegeLevel) => {
  646. let allowedFreeTrial
  647. if (error != null) {
  648. return next(error)
  649. }
  650. if (
  651. privilegeLevel == null ||
  652. privilegeLevel === PrivilegeLevels.NONE
  653. ) {
  654. return res.sendStatus(401)
  655. }
  656. if (
  657. subscription != null &&
  658. subscription.freeTrial != null &&
  659. subscription.freeTrial.expiresAt != null
  660. ) {
  661. allowedFreeTrial = !!subscription.freeTrial.allowed || true
  662. }
  663. let wsUrl = Settings.wsUrl
  664. let metricName = 'load-editor-ws'
  665. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  666. wsUrl = Settings.wsUrlBeta
  667. metricName += '-beta'
  668. } else if (
  669. Settings.wsUrlV2 &&
  670. Settings.wsUrlV2Percentage > 0 &&
  671. (ObjectId(projectId).getTimestamp() / 1000) %
  672. 100 <
  673. Settings.wsUrlV2Percentage
  674. ) {
  675. wsUrl = Settings.wsUrlV2
  676. metricName += '-v2'
  677. }
  678. if (req.query && req.query.ws === 'fallback') {
  679. // `?ws=fallback` will connect to the bare origin, and ignore
  680. // the custom wsUrl. Hence it must load the client side
  681. // javascript from there too.
  682. // Not resetting it here would possibly load a socket.io v2
  683. // client and connect to a v0 endpoint.
  684. wsUrl = undefined
  685. metricName += '-fallback'
  686. }
  687. metrics.inc(metricName)
  688. res.render('project/editor', {
  689. title: project.name,
  690. priority_title: true,
  691. bodyClasses: ['editor'],
  692. project_id: project._id,
  693. user: {
  694. id: userId,
  695. email: user.email,
  696. first_name: user.first_name,
  697. last_name: user.last_name,
  698. referal_id: user.referal_id,
  699. signUpDate: user.signUpDate,
  700. subscription: {
  701. freeTrial: { allowed: allowedFreeTrial }
  702. },
  703. featureSwitches: user.featureSwitches,
  704. features: user.features,
  705. refProviders: user.refProviders,
  706. betaProgram: user.betaProgram,
  707. isAdmin: user.isAdmin
  708. },
  709. userSettings: {
  710. mode: user.ace.mode,
  711. editorTheme: user.ace.theme,
  712. fontSize: user.ace.fontSize,
  713. autoComplete: user.ace.autoComplete,
  714. autoPairDelimiters: user.ace.autoPairDelimiters,
  715. pdfViewer: user.ace.pdfViewer,
  716. syntaxValidation: user.ace.syntaxValidation,
  717. fontFamily: user.ace.fontFamily || 'lucida',
  718. lineHeight: user.ace.lineHeight || 'normal',
  719. overallTheme: user.ace.overallTheme
  720. },
  721. trackChangesState: project.track_changes,
  722. privilegeLevel,
  723. chatUrl: Settings.apis.chat.url,
  724. anonymous,
  725. anonymousAccessToken: anonymous ? anonRequestToken : null,
  726. isTokenMember,
  727. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  728. userId,
  729. privilegeLevel,
  730. isTokenMember
  731. ),
  732. languages: Settings.languages,
  733. editorThemes: THEME_LIST,
  734. maxDocLength: Settings.max_doc_length,
  735. useV2History:
  736. project.overleaf &&
  737. project.overleaf.history &&
  738. Boolean(project.overleaf.history.display),
  739. brandVariation,
  740. allowedImageNames: Settings.allowedImageNames || [],
  741. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  742. wsUrl,
  743. showSupport: Features.hasFeature('support')
  744. })
  745. timer.done()
  746. }
  747. )
  748. }
  749. )
  750. },
  751. _buildProjectList(allProjects, userId) {
  752. let project
  753. const {
  754. owned,
  755. readAndWrite,
  756. readOnly,
  757. tokenReadAndWrite,
  758. tokenReadOnly
  759. } = allProjects
  760. const projects = []
  761. for (project of owned) {
  762. projects.push(
  763. ProjectController._buildProjectViewModel(
  764. project,
  765. 'owner',
  766. Sources.OWNER,
  767. userId
  768. )
  769. )
  770. }
  771. // Invite-access
  772. for (project of readAndWrite) {
  773. projects.push(
  774. ProjectController._buildProjectViewModel(
  775. project,
  776. 'readWrite',
  777. Sources.INVITE,
  778. userId
  779. )
  780. )
  781. }
  782. for (project of readOnly) {
  783. projects.push(
  784. ProjectController._buildProjectViewModel(
  785. project,
  786. 'readOnly',
  787. Sources.INVITE,
  788. userId
  789. )
  790. )
  791. }
  792. // Token-access
  793. // Only add these projects if they're not already present, this gives us cascading access
  794. // from 'owner' => 'token-read-only'
  795. for (project of tokenReadAndWrite) {
  796. if (
  797. projects.filter(p => p.id.toString() === project._id.toString())
  798. .length === 0
  799. ) {
  800. projects.push(
  801. ProjectController._buildProjectViewModel(
  802. project,
  803. 'readAndWrite',
  804. Sources.TOKEN,
  805. userId
  806. )
  807. )
  808. }
  809. }
  810. for (project of tokenReadOnly) {
  811. if (
  812. projects.filter(p => p.id.toString() === project._id.toString())
  813. .length === 0
  814. ) {
  815. projects.push(
  816. ProjectController._buildProjectViewModel(
  817. project,
  818. 'readOnly',
  819. Sources.TOKEN,
  820. userId
  821. )
  822. )
  823. }
  824. }
  825. return projects
  826. },
  827. _buildProjectViewModel(project, accessLevel, source, userId) {
  828. const archived = ProjectHelper.isArchived(project, userId)
  829. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  830. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  831. TokenAccessHandler.protectTokens(project, accessLevel)
  832. const model = {
  833. id: project._id,
  834. name: project.name,
  835. lastUpdated: project.lastUpdated,
  836. lastUpdatedBy: project.lastUpdatedBy,
  837. publicAccessLevel: project.publicAccesLevel,
  838. accessLevel,
  839. source,
  840. archived,
  841. trashed,
  842. owner_ref: project.owner_ref,
  843. isV1Project: false
  844. }
  845. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  846. model.owner_ref = null
  847. model.lastUpdatedBy = null
  848. }
  849. return model
  850. },
  851. _injectProjectUsers(projects, callback) {
  852. const users = {}
  853. for (const project of projects) {
  854. if (project.owner_ref != null) {
  855. users[project.owner_ref.toString()] = true
  856. }
  857. if (project.lastUpdatedBy != null) {
  858. users[project.lastUpdatedBy.toString()] = true
  859. }
  860. }
  861. const userIds = Object.keys(users)
  862. async.eachSeries(
  863. userIds,
  864. (userId, cb) => {
  865. UserGetter.getUser(
  866. userId,
  867. { first_name: 1, last_name: 1, email: 1 },
  868. (error, user) => {
  869. if (error != null) {
  870. return cb(error)
  871. }
  872. users[userId] = user
  873. cb()
  874. }
  875. )
  876. },
  877. error => {
  878. if (error != null) {
  879. return callback(error)
  880. }
  881. for (const project of projects) {
  882. if (project.owner_ref != null) {
  883. project.owner = users[project.owner_ref.toString()]
  884. }
  885. if (project.lastUpdatedBy != null) {
  886. project.lastUpdatedBy =
  887. users[project.lastUpdatedBy.toString()] || null
  888. }
  889. }
  890. callback(null, projects)
  891. }
  892. )
  893. },
  894. _buildWarningsList(noConnection) {
  895. return noConnection
  896. ? [
  897. 'Error accessing Overleaf V1. Some of your projects or features may be missing.'
  898. ]
  899. : []
  900. },
  901. _buildPortalTemplatesList(affiliations) {
  902. if (affiliations == null) {
  903. affiliations = []
  904. }
  905. const portalTemplates = []
  906. for (let aff of affiliations) {
  907. if (
  908. aff.portal &&
  909. aff.portal.slug &&
  910. aff.portal.templates_count &&
  911. aff.portal.templates_count > 0
  912. ) {
  913. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  914. portalTemplates.push({
  915. name: aff.institution.name,
  916. url: Settings.siteUrl + portalPath + aff.portal.slug
  917. })
  918. }
  919. }
  920. return portalTemplates
  921. }
  922. }
  923. var defaultSettingsForAnonymousUser = userId => ({
  924. id: userId,
  925. ace: {
  926. mode: 'none',
  927. theme: 'textmate',
  928. fontSize: '12',
  929. autoComplete: true,
  930. spellCheckLanguage: '',
  931. pdfViewer: '',
  932. syntaxValidation: true
  933. },
  934. subscription: {
  935. freeTrial: {
  936. allowed: true
  937. }
  938. },
  939. featureSwitches: {
  940. github: false
  941. }
  942. })
  943. var THEME_LIST = []
  944. function generateThemeList() {
  945. const files = fs.readdirSync(
  946. Path.join(
  947. __dirname,
  948. '/../../../../frontend/js/vendor/',
  949. PackageVersions.lib('ace')
  950. )
  951. )
  952. const result = []
  953. for (let file of files) {
  954. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  955. const cleanName = file.slice(0, -3).slice(6)
  956. result.push(THEME_LIST.push(cleanName))
  957. } else {
  958. result.push(undefined)
  959. }
  960. }
  961. }
  962. generateThemeList()
  963. module.exports = ProjectController