ProjectController.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. const _ = require('lodash')
  2. const Path = require('path')
  3. const OError = require('@overleaf/o-error')
  4. const fs = require('fs')
  5. const crypto = require('crypto')
  6. const async = require('async')
  7. const logger = require('logger-sharelatex')
  8. const { ObjectId } = require('mongodb')
  9. const ProjectDeleter = require('./ProjectDeleter')
  10. const ProjectDuplicator = require('./ProjectDuplicator')
  11. const ProjectCreationHandler = require('./ProjectCreationHandler')
  12. const EditorController = require('../Editor/EditorController')
  13. const ProjectHelper = require('./ProjectHelper')
  14. const metrics = require('@overleaf/metrics')
  15. const { User } = require('../../models/User')
  16. const 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 Sources = require('../Authorization/Sources')
  28. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  29. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  30. const ProjectEntityHandler = require('./ProjectEntityHandler')
  31. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  32. const UserGetter = require('../User/UserGetter')
  33. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  34. const { V1ConnectionError } = require('../Errors/Errors')
  35. const Features = require('../../infrastructure/Features')
  36. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  37. const UserController = require('../User/UserController')
  38. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  39. const Modules = require('../../infrastructure/Modules')
  40. const { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
  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: firstName, last_name: lastName, email } = currentUser
  228. ProjectDuplicator.duplicate(
  229. currentUser,
  230. projectId,
  231. projectName,
  232. (err, project) => {
  233. if (err != null) {
  234. OError.tag(err, 'error cloning project', {
  235. projectId,
  236. userId: currentUser._id
  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: {
  245. first_name: firstName,
  246. last_name: lastName,
  247. email,
  248. _id: currentUser._id
  249. }
  250. })
  251. }
  252. )
  253. },
  254. newProject(req, res, next) {
  255. const currentUser = AuthenticationController.getSessionUser(req)
  256. const {
  257. first_name: firstName,
  258. last_name: lastName,
  259. email,
  260. _id: userId
  261. } = currentUser
  262. const projectName =
  263. req.body.projectName != null ? req.body.projectName.trim() : undefined
  264. const { template } = req.body
  265. async.waterfall(
  266. [
  267. cb => {
  268. if (template === 'example') {
  269. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  270. } else {
  271. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  272. }
  273. }
  274. ],
  275. (err, project) => {
  276. if (err != null) {
  277. return next(err)
  278. }
  279. res.send({
  280. project_id: project._id,
  281. owner_ref: project.owner_ref,
  282. owner: {
  283. first_name: firstName,
  284. last_name: lastName,
  285. email,
  286. _id: userId
  287. }
  288. })
  289. }
  290. )
  291. },
  292. renameProject(req, res, next) {
  293. const projectId = req.params.Project_id
  294. const newName = req.body.newProjectName
  295. EditorController.renameProject(projectId, newName, err => {
  296. if (err != null) {
  297. return next(err)
  298. }
  299. res.sendStatus(200)
  300. })
  301. },
  302. userProjectsJson(req, res, next) {
  303. const userId = AuthenticationController.getLoggedInUserId(req)
  304. ProjectGetter.findAllUsersProjects(
  305. userId,
  306. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  307. (err, projects) => {
  308. if (err != null) {
  309. return next(err)
  310. }
  311. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  312. projects = ProjectController._buildProjectList(projects, userId)
  313. .filter(p => !(p.archived || p.trashed))
  314. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  315. res.json({ projects })
  316. }
  317. )
  318. },
  319. projectEntitiesJson(req, res, next) {
  320. const projectId = req.params.Project_id
  321. ProjectGetter.getProject(projectId, (err, project) => {
  322. if (err != null) {
  323. return next(err)
  324. }
  325. ProjectEntityHandler.getAllEntitiesFromProject(
  326. project,
  327. (err, docs, files) => {
  328. if (err != null) {
  329. return next(err)
  330. }
  331. const entities = docs
  332. .concat(files)
  333. // Sort by path ascending
  334. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  335. .map(e => ({
  336. path: e.path,
  337. type: e.doc != null ? 'doc' : 'file'
  338. }))
  339. res.json({ project_id: projectId, entities })
  340. }
  341. )
  342. })
  343. },
  344. projectListPage(req, res, next) {
  345. const timer = new metrics.Timer('project-list')
  346. const userId = AuthenticationController.getLoggedInUserId(req)
  347. const currentUser = AuthenticationController.getSessionUser(req)
  348. async.parallel(
  349. {
  350. tags(cb) {
  351. TagsHandler.getAllTags(userId, cb)
  352. },
  353. notifications(cb) {
  354. NotificationsHandler.getUserNotifications(userId, cb)
  355. },
  356. projects(cb) {
  357. ProjectGetter.findAllUsersProjects(
  358. userId,
  359. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  360. cb
  361. )
  362. },
  363. hasSubscription(cb) {
  364. LimitationsManager.hasPaidSubscription(
  365. currentUser,
  366. (error, hasPaidSubscription) => {
  367. if (error != null && error instanceof V1ConnectionError) {
  368. return cb(null, true)
  369. }
  370. cb(error, hasPaidSubscription)
  371. }
  372. )
  373. },
  374. user(cb) {
  375. User.findById(
  376. userId,
  377. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  378. cb
  379. )
  380. },
  381. userEmailsData(cb) {
  382. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  383. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  384. if (error && error instanceof V1ConnectionError) {
  385. return cb(null, result)
  386. }
  387. if (!Features.hasFeature('affiliations')) {
  388. result.list = fullEmails
  389. return cb(null, result)
  390. }
  391. Modules.hooks.fire(
  392. 'allInReconfirmNotificationPeriodsForUser',
  393. fullEmails,
  394. (error, results) => {
  395. // Module.hooks.fire accepts multiple methods
  396. // and does async.series
  397. const allInReconfirmNotificationPeriods =
  398. (results && results[0]) || []
  399. return cb(null, {
  400. list: fullEmails,
  401. allInReconfirmNotificationPeriods
  402. })
  403. }
  404. )
  405. })
  406. }
  407. },
  408. (err, results) => {
  409. if (err != null) {
  410. OError.tag(err, 'error getting data for project list page')
  411. return next(err)
  412. }
  413. const { notifications, user, userEmailsData } = results
  414. const userEmails = userEmailsData.list || []
  415. const userAffiliations = userEmails
  416. .filter(emailData => !!emailData.affiliation)
  417. .map(emailData => {
  418. const result = emailData.affiliation
  419. result.email = emailData.email
  420. return result
  421. })
  422. const { allInReconfirmNotificationPeriods } = userEmailsData
  423. // Handle case of deleted user
  424. if (user == null) {
  425. UserController.logout(req, res, next)
  426. return
  427. }
  428. const tags = results.tags
  429. const notificationsInstitution = []
  430. for (const notification of notifications) {
  431. notification.html = req.i18n.translate(
  432. notification.templateKey,
  433. notification.messageOpts
  434. )
  435. }
  436. // Institution SSO Notifications
  437. let reconfirmedViaSAML
  438. if (Features.hasFeature('saml')) {
  439. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  440. const samlSession = req.session.saml
  441. // Notification: SSO Available
  442. const linkedInstitutionIds = []
  443. user.emails.forEach(email => {
  444. if (email.samlProviderId) {
  445. linkedInstitutionIds.push(email.samlProviderId)
  446. }
  447. })
  448. if (Array.isArray(userAffiliations)) {
  449. userAffiliations.forEach(affiliation => {
  450. if (
  451. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  452. ) {
  453. notificationsInstitution.push({
  454. email: affiliation.email,
  455. institutionId: affiliation.institution.id,
  456. institutionName: affiliation.institution.name,
  457. templateKey: 'notification_institution_sso_available'
  458. })
  459. }
  460. })
  461. }
  462. if (samlSession) {
  463. // Notification: After SSO Linked
  464. if (samlSession.linked) {
  465. notificationsInstitution.push({
  466. email: samlSession.institutionEmail,
  467. institutionName: samlSession.linked.universityName,
  468. templateKey: 'notification_institution_sso_linked'
  469. })
  470. }
  471. // Notification: After SSO Linked or Logging in
  472. // The requested email does not match primary email returned from
  473. // the institution
  474. if (
  475. samlSession.requestedEmail &&
  476. samlSession.emailNonCanonical &&
  477. !samlSession.error
  478. ) {
  479. notificationsInstitution.push({
  480. institutionEmail: samlSession.emailNonCanonical,
  481. requestedEmail: samlSession.requestedEmail,
  482. templateKey: 'notification_institution_sso_non_canonical'
  483. })
  484. }
  485. // Notification: Tried to register, but account already existed
  486. // registerIntercept is set before the institution callback.
  487. // institutionEmail is set after institution callback.
  488. // Check for both in case SSO flow was abandoned
  489. if (
  490. samlSession.registerIntercept &&
  491. samlSession.institutionEmail &&
  492. !samlSession.error
  493. ) {
  494. notificationsInstitution.push({
  495. email: samlSession.institutionEmail,
  496. templateKey: 'notification_institution_sso_already_registered'
  497. })
  498. }
  499. // Notification: When there is a session error
  500. if (samlSession.error) {
  501. notificationsInstitution.push({
  502. templateKey: 'notification_institution_sso_error',
  503. error: samlSession.error
  504. })
  505. }
  506. }
  507. delete req.session.saml
  508. }
  509. const portalTemplates = ProjectController._buildPortalTemplatesList(
  510. userAffiliations
  511. )
  512. const projects = ProjectController._buildProjectList(
  513. results.projects,
  514. userId
  515. )
  516. // in v2 add notifications for matching university IPs
  517. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  518. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  519. }
  520. ProjectController._injectProjectUsers(projects, (error, projects) => {
  521. if (error != null) {
  522. return next(error)
  523. }
  524. const viewModel = {
  525. title: 'your_projects',
  526. priority_title: true,
  527. projects,
  528. tags,
  529. notifications: notifications || [],
  530. notificationsInstitution,
  531. allInReconfirmNotificationPeriods,
  532. portalTemplates,
  533. user,
  534. userAffiliations,
  535. userEmails,
  536. hasSubscription: results.hasSubscription,
  537. reconfirmedViaSAML,
  538. zipFileSizeLimit: Settings.maxUploadSize
  539. }
  540. if (
  541. Settings.algolia &&
  542. Settings.algolia.app_id &&
  543. Settings.algolia.read_only_api_key
  544. ) {
  545. viewModel.showUserDetailsArea = true
  546. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  547. viewModel.algolia_app_id = Settings.algolia.app_id
  548. } else {
  549. viewModel.showUserDetailsArea = false
  550. }
  551. const paidUser =
  552. (user.features != null ? user.features.github : undefined) &&
  553. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  554. const freeUserProportion = 0.1
  555. const sampleFreeUser =
  556. parseInt(user._id.toString().slice(-2), 16) <
  557. freeUserProportion * 255
  558. const showFrontWidget = paidUser || sampleFreeUser
  559. if (showFrontWidget) {
  560. viewModel.frontChatWidgetRoomId =
  561. Settings.overleaf != null
  562. ? Settings.overleaf.front_chat_widget_room_id
  563. : undefined
  564. }
  565. res.render('project/list', viewModel)
  566. timer.done()
  567. })
  568. }
  569. )
  570. },
  571. loadEditor(req, res, next) {
  572. const timer = new metrics.Timer('load-editor')
  573. if (!Settings.editorIsOpen) {
  574. return res.render('general/closed', { title: 'updating_site' })
  575. }
  576. let anonymous, userId, sessionUser
  577. if (AuthenticationController.isUserLoggedIn(req)) {
  578. sessionUser = AuthenticationController.getSessionUser(req)
  579. userId = AuthenticationController.getLoggedInUserId(req)
  580. anonymous = false
  581. } else {
  582. sessionUser = null
  583. anonymous = true
  584. userId = null
  585. }
  586. const projectId = req.params.Project_id
  587. async.auto(
  588. {
  589. project(cb) {
  590. ProjectGetter.getProject(
  591. projectId,
  592. {
  593. name: 1,
  594. lastUpdated: 1,
  595. track_changes: 1,
  596. owner_ref: 1,
  597. brandVariationId: 1,
  598. overleaf: 1,
  599. tokens: 1
  600. },
  601. (err, project) => {
  602. if (err != null) {
  603. return cb(err)
  604. }
  605. cb(null, project)
  606. }
  607. )
  608. },
  609. user(cb) {
  610. if (userId == null) {
  611. cb(null, defaultSettingsForAnonymousUser(userId))
  612. } else {
  613. User.findById(
  614. userId,
  615. 'email first_name last_name referal_id signUpDate featureSwitches features refProviders alphaProgram betaProgram isAdmin ace',
  616. (err, user) => {
  617. // Handle case of deleted user
  618. if (user == null) {
  619. UserController.logout(req, res, next)
  620. return
  621. }
  622. logger.log({ projectId, userId }, 'got user')
  623. cb(err, user)
  624. }
  625. )
  626. }
  627. },
  628. subscription(cb) {
  629. if (userId == null) {
  630. return cb()
  631. }
  632. SubscriptionLocator.getUsersSubscription(userId, cb)
  633. },
  634. activate(cb) {
  635. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  636. },
  637. markAsOpened(cb) {
  638. // don't need to wait for this to complete
  639. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  640. cb()
  641. },
  642. isTokenMember(cb) {
  643. if (userId == null) {
  644. return cb()
  645. }
  646. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  647. },
  648. brandVariation: [
  649. 'project',
  650. (cb, results) => {
  651. if (
  652. (results.project != null
  653. ? results.project.brandVariationId
  654. : undefined) == null
  655. ) {
  656. return cb()
  657. }
  658. BrandVariationsHandler.getBrandVariationById(
  659. results.project.brandVariationId,
  660. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  661. )
  662. }
  663. ],
  664. flushToTpds: cb => {
  665. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  666. }
  667. },
  668. (err, results) => {
  669. if (err != null) {
  670. OError.tag(err, 'error getting details for project page')
  671. return next(err)
  672. }
  673. const { project } = results
  674. const { user } = results
  675. const { subscription } = results
  676. const { brandVariation } = results
  677. const anonRequestToken = TokenAccessHandler.getRequestToken(
  678. req,
  679. projectId
  680. )
  681. const { isTokenMember } = results
  682. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  683. sessionUser
  684. )
  685. const wantsOldFileTreeUI =
  686. req.query && req.query.new_file_tree_ui === 'false'
  687. const wantsNewShareModalUI =
  688. req.query && req.query.new_share_modal_ui === 'true'
  689. const wantsNewAddFilesModalUI =
  690. req.query && req.query.new_add_files_modal_ui === 'true'
  691. AuthorizationManager.getPrivilegeLevelForProject(
  692. userId,
  693. projectId,
  694. anonRequestToken,
  695. (error, privilegeLevel) => {
  696. let allowedFreeTrial = true
  697. if (error != null) {
  698. return next(error)
  699. }
  700. if (
  701. privilegeLevel == null ||
  702. privilegeLevel === PrivilegeLevels.NONE
  703. ) {
  704. return res.sendStatus(401)
  705. }
  706. if (subscription != null) {
  707. allowedFreeTrial = false
  708. }
  709. let wsUrl = Settings.wsUrl
  710. let metricName = 'load-editor-ws'
  711. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  712. wsUrl = Settings.wsUrlBeta
  713. metricName += '-beta'
  714. } else if (
  715. Settings.wsUrlV2 &&
  716. Settings.wsUrlV2Percentage > 0 &&
  717. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  718. Settings.wsUrlV2Percentage
  719. ) {
  720. wsUrl = Settings.wsUrlV2
  721. metricName += '-v2'
  722. }
  723. if (req.query && req.query.ws === 'fallback') {
  724. // `?ws=fallback` will connect to the bare origin, and ignore
  725. // the custom wsUrl. Hence it must load the client side
  726. // javascript from there too.
  727. // Not resetting it here would possibly load a socket.io v2
  728. // client and connect to a v0 endpoint.
  729. wsUrl = undefined
  730. metricName += '-fallback'
  731. }
  732. metrics.inc(metricName)
  733. if (userId) {
  734. AnalyticsManager.recordEvent(userId, 'project-opened', {
  735. projectId: project._id
  736. })
  737. }
  738. const logsUIVariant = getNewLogsUIVariantForUser(user)
  739. const userShouldSeeNewLogsUI = logsUIVariant.newLogsUI
  740. const wantsOldLogsUI =
  741. req.query && req.query.new_logs_ui === 'false'
  742. res.render('project/editor', {
  743. title: project.name,
  744. priority_title: true,
  745. bodyClasses: ['editor'],
  746. project_id: project._id,
  747. user: {
  748. id: userId,
  749. email: user.email,
  750. first_name: user.first_name,
  751. last_name: user.last_name,
  752. referal_id: user.referal_id,
  753. signUpDate: user.signUpDate,
  754. allowedFreeTrial: allowedFreeTrial,
  755. featureSwitches: user.featureSwitches,
  756. features: user.features,
  757. refProviders: user.refProviders,
  758. alphaProgram: user.alphaProgram,
  759. betaProgram: user.betaProgram,
  760. isAdmin: user.isAdmin
  761. },
  762. userSettings: {
  763. mode: user.ace.mode,
  764. editorTheme: user.ace.theme,
  765. fontSize: user.ace.fontSize,
  766. autoComplete: user.ace.autoComplete,
  767. autoPairDelimiters: user.ace.autoPairDelimiters,
  768. pdfViewer: user.ace.pdfViewer,
  769. syntaxValidation: user.ace.syntaxValidation,
  770. fontFamily: user.ace.fontFamily || 'lucida',
  771. lineHeight: user.ace.lineHeight || 'normal',
  772. overallTheme: user.ace.overallTheme
  773. },
  774. trackChangesState: project.track_changes,
  775. privilegeLevel,
  776. chatUrl: Settings.apis.chat.url,
  777. anonymous,
  778. anonymousAccessToken: anonymous ? anonRequestToken : null,
  779. isTokenMember,
  780. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  781. userId,
  782. privilegeLevel,
  783. isTokenMember
  784. ),
  785. languages: Settings.languages,
  786. editorThemes: THEME_LIST,
  787. maxDocLength: Settings.max_doc_length,
  788. useV2History:
  789. project.overleaf &&
  790. project.overleaf.history &&
  791. Boolean(project.overleaf.history.display),
  792. brandVariation,
  793. allowedImageNames,
  794. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  795. wsUrl,
  796. showSupport: Features.hasFeature('support'),
  797. showNewLogsUI: userShouldSeeNewLogsUI && !wantsOldLogsUI,
  798. logsUISubvariant: logsUIVariant.subvariant,
  799. showNewNavigationUI:
  800. req.query && req.query.new_navigation_ui === 'true',
  801. showReactFileTree: !wantsOldFileTreeUI,
  802. showReactShareModal: wantsNewShareModalUI,
  803. showReactAddFilesModal: wantsNewAddFilesModalUI
  804. })
  805. timer.done()
  806. }
  807. )
  808. }
  809. )
  810. },
  811. _buildProjectList(allProjects, userId) {
  812. let project
  813. const {
  814. owned,
  815. readAndWrite,
  816. readOnly,
  817. tokenReadAndWrite,
  818. tokenReadOnly
  819. } = allProjects
  820. const projects = []
  821. for (project of owned) {
  822. projects.push(
  823. ProjectController._buildProjectViewModel(
  824. project,
  825. 'owner',
  826. Sources.OWNER,
  827. userId
  828. )
  829. )
  830. }
  831. // Invite-access
  832. for (project of readAndWrite) {
  833. projects.push(
  834. ProjectController._buildProjectViewModel(
  835. project,
  836. 'readWrite',
  837. Sources.INVITE,
  838. userId
  839. )
  840. )
  841. }
  842. for (project of readOnly) {
  843. projects.push(
  844. ProjectController._buildProjectViewModel(
  845. project,
  846. 'readOnly',
  847. Sources.INVITE,
  848. userId
  849. )
  850. )
  851. }
  852. // Token-access
  853. // Only add these projects if they're not already present, this gives us cascading access
  854. // from 'owner' => 'token-read-only'
  855. for (project of tokenReadAndWrite) {
  856. if (
  857. projects.filter(p => p.id.toString() === project._id.toString())
  858. .length === 0
  859. ) {
  860. projects.push(
  861. ProjectController._buildProjectViewModel(
  862. project,
  863. 'readAndWrite',
  864. Sources.TOKEN,
  865. userId
  866. )
  867. )
  868. }
  869. }
  870. for (project of tokenReadOnly) {
  871. if (
  872. projects.filter(p => p.id.toString() === project._id.toString())
  873. .length === 0
  874. ) {
  875. projects.push(
  876. ProjectController._buildProjectViewModel(
  877. project,
  878. 'readOnly',
  879. Sources.TOKEN,
  880. userId
  881. )
  882. )
  883. }
  884. }
  885. return projects
  886. },
  887. _buildProjectViewModel(project, accessLevel, source, userId) {
  888. const archived = ProjectHelper.isArchived(project, userId)
  889. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  890. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  891. TokenAccessHandler.protectTokens(project, accessLevel)
  892. const model = {
  893. id: project._id,
  894. name: project.name,
  895. lastUpdated: project.lastUpdated,
  896. lastUpdatedBy: project.lastUpdatedBy,
  897. publicAccessLevel: project.publicAccesLevel,
  898. accessLevel,
  899. source,
  900. archived,
  901. trashed,
  902. owner_ref: project.owner_ref,
  903. isV1Project: false
  904. }
  905. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  906. model.owner_ref = null
  907. model.lastUpdatedBy = null
  908. }
  909. return model
  910. },
  911. _injectProjectUsers(projects, callback) {
  912. const users = {}
  913. for (const project of projects) {
  914. if (project.owner_ref != null) {
  915. users[project.owner_ref.toString()] = true
  916. }
  917. if (project.lastUpdatedBy != null) {
  918. users[project.lastUpdatedBy.toString()] = true
  919. }
  920. }
  921. const userIds = Object.keys(users)
  922. async.eachSeries(
  923. userIds,
  924. (userId, cb) => {
  925. UserGetter.getUser(
  926. userId,
  927. { first_name: 1, last_name: 1, email: 1 },
  928. (error, user) => {
  929. if (error != null) {
  930. return cb(error)
  931. }
  932. users[userId] = user
  933. cb()
  934. }
  935. )
  936. },
  937. error => {
  938. if (error != null) {
  939. return callback(error)
  940. }
  941. for (const project of projects) {
  942. if (project.owner_ref != null) {
  943. project.owner = users[project.owner_ref.toString()]
  944. }
  945. if (project.lastUpdatedBy != null) {
  946. project.lastUpdatedBy =
  947. users[project.lastUpdatedBy.toString()] || null
  948. }
  949. }
  950. callback(null, projects)
  951. }
  952. )
  953. },
  954. _buildPortalTemplatesList(affiliations) {
  955. if (affiliations == null) {
  956. affiliations = []
  957. }
  958. const portalTemplates = []
  959. for (let aff of affiliations) {
  960. if (
  961. aff.portal &&
  962. aff.portal.slug &&
  963. aff.portal.templates_count &&
  964. aff.portal.templates_count > 0
  965. ) {
  966. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  967. portalTemplates.push({
  968. name: aff.institution.name,
  969. url: Settings.siteUrl + portalPath + aff.portal.slug
  970. })
  971. }
  972. }
  973. return portalTemplates
  974. }
  975. }
  976. var defaultSettingsForAnonymousUser = userId => ({
  977. id: userId,
  978. ace: {
  979. mode: 'none',
  980. theme: 'textmate',
  981. fontSize: '12',
  982. autoComplete: true,
  983. spellCheckLanguage: '',
  984. pdfViewer: '',
  985. syntaxValidation: true
  986. },
  987. subscription: {
  988. freeTrial: {
  989. allowed: true
  990. }
  991. },
  992. featureSwitches: {
  993. github: false
  994. },
  995. alphaProgram: false,
  996. betaProgram: false
  997. })
  998. var THEME_LIST = []
  999. function generateThemeList() {
  1000. const files = fs.readdirSync(
  1001. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1002. )
  1003. const result = []
  1004. for (let file of files) {
  1005. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1006. const cleanName = file.slice(0, -3).slice(6)
  1007. result.push(THEME_LIST.push(cleanName))
  1008. } else {
  1009. result.push(undefined)
  1010. }
  1011. }
  1012. }
  1013. generateThemeList()
  1014. module.exports = ProjectController