ProjectController.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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 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('metrics-sharelatex')
  15. const { User } = require('../../models/User')
  16. const TagsHandler = require('../Tags/TagsHandler')
  17. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  18. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  19. const LimitationsManager = require('../Subscription/LimitationsManager')
  20. const Settings = require('settings-sharelatex')
  21. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  22. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  23. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  24. const ProjectGetter = require('./ProjectGetter')
  25. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  26. const AuthenticationController = require('../Authentication/AuthenticationController')
  27. const PackageVersions = require('../../infrastructure/PackageVersions')
  28. const Sources = require('../Authorization/Sources')
  29. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  30. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  31. const ProjectEntityHandler = require('./ProjectEntityHandler')
  32. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  33. const UserGetter = require('../User/UserGetter')
  34. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  35. const { V1ConnectionError } = require('../Errors/Errors')
  36. const Features = require('../../infrastructure/Features')
  37. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  38. const { getUserAffiliations } = require('../Institutions/InstitutionsAPI')
  39. const V1Handler = require('../V1/V1Handler')
  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. if (
  569. (project.overleaf != null ? project.overleaf.id : undefined) ==
  570. null ||
  571. (project.tokens != null
  572. ? project.tokens.readAndWrite
  573. : undefined) == null ||
  574. Settings.projectImportingCheckMaxCreateDelta == null
  575. ) {
  576. return cb(null, project)
  577. }
  578. const createDelta =
  579. (new Date().getTime() -
  580. new Date(project._id.getTimestamp()).getTime()) /
  581. 1000
  582. if (
  583. !(createDelta < Settings.projectImportingCheckMaxCreateDelta)
  584. ) {
  585. return cb(null, project)
  586. }
  587. V1Handler.getDocExported(
  588. project.tokens.readAndWrite,
  589. (err, docExported) => {
  590. if (err != null) {
  591. return next(err)
  592. }
  593. project.exporting = docExported.exporting
  594. cb(null, project)
  595. }
  596. )
  597. }
  598. )
  599. },
  600. user(cb) {
  601. if (userId == null) {
  602. cb(null, defaultSettingsForAnonymousUser(userId))
  603. } else {
  604. User.findById(userId, (err, user) => {
  605. // Handle case of deleted user
  606. if (user == null) {
  607. UserController.logout(req, res, next)
  608. return
  609. }
  610. logger.log({ projectId, userId }, 'got user')
  611. cb(err, user)
  612. })
  613. }
  614. },
  615. subscription(cb) {
  616. if (userId == null) {
  617. return cb()
  618. }
  619. SubscriptionLocator.getUsersSubscription(userId, cb)
  620. },
  621. activate(cb) {
  622. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  623. },
  624. markAsOpened(cb) {
  625. // don't need to wait for this to complete
  626. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  627. cb()
  628. },
  629. isTokenMember(cb) {
  630. if (userId == null) {
  631. return cb()
  632. }
  633. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  634. },
  635. brandVariation: [
  636. 'project',
  637. (cb, results) => {
  638. if (
  639. (results.project != null
  640. ? results.project.brandVariationId
  641. : undefined) == null
  642. ) {
  643. return cb()
  644. }
  645. BrandVariationsHandler.getBrandVariationById(
  646. results.project.brandVariationId,
  647. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  648. )
  649. }
  650. ],
  651. flushToTpds: cb => {
  652. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  653. }
  654. },
  655. (err, results) => {
  656. if (err != null) {
  657. logger.warn({ err }, 'error getting details for project page')
  658. return next(err)
  659. }
  660. const { project } = results
  661. const { user } = results
  662. const { subscription } = results
  663. const { brandVariation } = results
  664. const anonRequestToken = TokenAccessHandler.getRequestToken(
  665. req,
  666. projectId
  667. )
  668. const { isTokenMember } = results
  669. AuthorizationManager.getPrivilegeLevelForProject(
  670. userId,
  671. projectId,
  672. anonRequestToken,
  673. (error, privilegeLevel) => {
  674. let allowedFreeTrial
  675. if (error != null) {
  676. return next(error)
  677. }
  678. if (
  679. privilegeLevel == null ||
  680. privilegeLevel === PrivilegeLevels.NONE
  681. ) {
  682. return res.sendStatus(401)
  683. }
  684. if (project.exporting) {
  685. res.render('project/importing', { bodyClasses: ['editor'] })
  686. return
  687. }
  688. if (
  689. subscription != null &&
  690. subscription.freeTrial != null &&
  691. subscription.freeTrial.expiresAt != null
  692. ) {
  693. allowedFreeTrial = !!subscription.freeTrial.allowed || true
  694. }
  695. let wsUrl = Settings.wsUrl
  696. let metricName = 'load-editor-ws'
  697. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  698. wsUrl = Settings.wsUrlBeta
  699. metricName += '-beta'
  700. }
  701. if (req.query && req.query.ws === 'fallback') {
  702. // `?ws=fallback` will connect to the bare origin, and ignore
  703. // the custom wsUrl. Hence it must load the client side
  704. // javascript from there too.
  705. // Not resetting it here would possibly load a socket.io v2
  706. // client and connect to a v0 endpoint.
  707. wsUrl = undefined
  708. metricName += '-fallback'
  709. }
  710. metrics.inc(metricName)
  711. res.render('project/editor', {
  712. title: project.name,
  713. priority_title: true,
  714. bodyClasses: ['editor'],
  715. project_id: project._id,
  716. user: {
  717. id: userId,
  718. email: user.email,
  719. first_name: user.first_name,
  720. last_name: user.last_name,
  721. referal_id: user.referal_id,
  722. signUpDate: user.signUpDate,
  723. subscription: {
  724. freeTrial: { allowed: allowedFreeTrial }
  725. },
  726. featureSwitches: user.featureSwitches,
  727. features: user.features,
  728. refProviders: user.refProviders,
  729. betaProgram: user.betaProgram,
  730. isAdmin: user.isAdmin
  731. },
  732. userSettings: {
  733. mode: user.ace.mode,
  734. editorTheme: user.ace.theme,
  735. fontSize: user.ace.fontSize,
  736. autoComplete: user.ace.autoComplete,
  737. autoPairDelimiters: user.ace.autoPairDelimiters,
  738. pdfViewer: user.ace.pdfViewer,
  739. syntaxValidation: user.ace.syntaxValidation,
  740. fontFamily: user.ace.fontFamily || 'lucida',
  741. lineHeight: user.ace.lineHeight || 'normal',
  742. overallTheme: user.ace.overallTheme
  743. },
  744. trackChangesState: project.track_changes,
  745. privilegeLevel,
  746. chatUrl: Settings.apis.chat.url,
  747. anonymous,
  748. anonymousAccessToken: anonymous ? anonRequestToken : null,
  749. isTokenMember,
  750. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  751. userId,
  752. privilegeLevel,
  753. isTokenMember
  754. ),
  755. languages: Settings.languages,
  756. editorThemes: THEME_LIST,
  757. maxDocLength: Settings.max_doc_length,
  758. useV2History:
  759. project.overleaf &&
  760. project.overleaf.history &&
  761. Boolean(project.overleaf.history.display),
  762. brandVariation,
  763. allowedImageNames: Settings.allowedImageNames || [],
  764. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  765. wsUrl,
  766. showSupport: Features.hasFeature('support')
  767. })
  768. timer.done()
  769. }
  770. )
  771. }
  772. )
  773. },
  774. _buildProjectList(allProjects, userId) {
  775. let project
  776. const {
  777. owned,
  778. readAndWrite,
  779. readOnly,
  780. tokenReadAndWrite,
  781. tokenReadOnly
  782. } = allProjects
  783. const projects = []
  784. for (project of owned) {
  785. projects.push(
  786. ProjectController._buildProjectViewModel(
  787. project,
  788. 'owner',
  789. Sources.OWNER,
  790. userId
  791. )
  792. )
  793. }
  794. // Invite-access
  795. for (project of readAndWrite) {
  796. projects.push(
  797. ProjectController._buildProjectViewModel(
  798. project,
  799. 'readWrite',
  800. Sources.INVITE,
  801. userId
  802. )
  803. )
  804. }
  805. for (project of readOnly) {
  806. projects.push(
  807. ProjectController._buildProjectViewModel(
  808. project,
  809. 'readOnly',
  810. Sources.INVITE,
  811. userId
  812. )
  813. )
  814. }
  815. // Token-access
  816. // Only add these projects if they're not already present, this gives us cascading access
  817. // from 'owner' => 'token-read-only'
  818. for (project of tokenReadAndWrite) {
  819. if (
  820. projects.filter(p => p.id.toString() === project._id.toString())
  821. .length === 0
  822. ) {
  823. projects.push(
  824. ProjectController._buildProjectViewModel(
  825. project,
  826. 'readAndWrite',
  827. Sources.TOKEN,
  828. userId
  829. )
  830. )
  831. }
  832. }
  833. for (project of tokenReadOnly) {
  834. if (
  835. projects.filter(p => p.id.toString() === project._id.toString())
  836. .length === 0
  837. ) {
  838. projects.push(
  839. ProjectController._buildProjectViewModel(
  840. project,
  841. 'readOnly',
  842. Sources.TOKEN,
  843. userId
  844. )
  845. )
  846. }
  847. }
  848. return projects
  849. },
  850. _buildProjectViewModel(project, accessLevel, source, userId) {
  851. const archived = ProjectHelper.isArchived(project, userId)
  852. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  853. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  854. TokenAccessHandler.protectTokens(project, accessLevel)
  855. const model = {
  856. id: project._id,
  857. name: project.name,
  858. lastUpdated: project.lastUpdated,
  859. lastUpdatedBy: project.lastUpdatedBy,
  860. publicAccessLevel: project.publicAccesLevel,
  861. accessLevel,
  862. source,
  863. archived,
  864. trashed,
  865. owner_ref: project.owner_ref,
  866. isV1Project: false
  867. }
  868. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  869. model.owner_ref = null
  870. model.lastUpdatedBy = null
  871. }
  872. return model
  873. },
  874. _injectProjectUsers(projects, callback) {
  875. const users = {}
  876. for (const project of projects) {
  877. if (project.owner_ref != null) {
  878. users[project.owner_ref.toString()] = true
  879. }
  880. if (project.lastUpdatedBy != null) {
  881. users[project.lastUpdatedBy.toString()] = true
  882. }
  883. }
  884. const userIds = Object.keys(users)
  885. async.eachSeries(
  886. userIds,
  887. (userId, cb) => {
  888. UserGetter.getUser(
  889. userId,
  890. { first_name: 1, last_name: 1, email: 1 },
  891. (error, user) => {
  892. if (error != null) {
  893. return cb(error)
  894. }
  895. users[userId] = user
  896. cb()
  897. }
  898. )
  899. },
  900. error => {
  901. if (error != null) {
  902. return callback(error)
  903. }
  904. for (const project of projects) {
  905. if (project.owner_ref != null) {
  906. project.owner = users[project.owner_ref.toString()]
  907. }
  908. if (project.lastUpdatedBy != null) {
  909. project.lastUpdatedBy =
  910. users[project.lastUpdatedBy.toString()] || null
  911. }
  912. }
  913. callback(null, projects)
  914. }
  915. )
  916. },
  917. _buildWarningsList(noConnection) {
  918. return noConnection
  919. ? [
  920. 'Error accessing Overleaf V1. Some of your projects or features may be missing.'
  921. ]
  922. : []
  923. },
  924. _buildPortalTemplatesList(affiliations) {
  925. if (affiliations == null) {
  926. affiliations = []
  927. }
  928. const portalTemplates = []
  929. for (let aff of affiliations) {
  930. if (
  931. aff.portal &&
  932. aff.portal.slug &&
  933. aff.portal.templates_count &&
  934. aff.portal.templates_count > 0
  935. ) {
  936. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  937. portalTemplates.push({
  938. name: aff.institution.name,
  939. url: Settings.siteUrl + portalPath + aff.portal.slug
  940. })
  941. }
  942. }
  943. return portalTemplates
  944. }
  945. }
  946. var defaultSettingsForAnonymousUser = userId => ({
  947. id: userId,
  948. ace: {
  949. mode: 'none',
  950. theme: 'textmate',
  951. fontSize: '12',
  952. autoComplete: true,
  953. spellCheckLanguage: '',
  954. pdfViewer: '',
  955. syntaxValidation: true
  956. },
  957. subscription: {
  958. freeTrial: {
  959. allowed: true
  960. }
  961. },
  962. featureSwitches: {
  963. github: false
  964. }
  965. })
  966. var THEME_LIST = []
  967. function generateThemeList() {
  968. const files = fs.readdirSync(
  969. Path.join(
  970. __dirname,
  971. '/../../../../frontend/js/vendor/',
  972. PackageVersions.lib('ace')
  973. )
  974. )
  975. const result = []
  976. for (let file of files) {
  977. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  978. const cleanName = file.slice(0, -3).slice(6)
  979. result.push(THEME_LIST.push(cleanName))
  980. } else {
  981. result.push(undefined)
  982. }
  983. }
  984. }
  985. generateThemeList()
  986. module.exports = ProjectController