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.createHash('md5').update(data).digest('hex')
  64. const counter = parseInt(md5hash.slice(26, 32), 16)
  65. return counter % 100 < percentage
  66. },
  67. updateProjectSettings(req, res, next) {
  68. const projectId = req.params.Project_id
  69. const jobs = []
  70. if (req.body.compiler != null) {
  71. jobs.push(callback =>
  72. EditorController.setCompiler(projectId, req.body.compiler, callback)
  73. )
  74. }
  75. if (req.body.imageName != null) {
  76. jobs.push(callback =>
  77. EditorController.setImageName(projectId, req.body.imageName, callback)
  78. )
  79. }
  80. if (req.body.name != null) {
  81. jobs.push(callback =>
  82. EditorController.renameProject(projectId, req.body.name, callback)
  83. )
  84. }
  85. if (req.body.spellCheckLanguage != null) {
  86. jobs.push(callback =>
  87. EditorController.setSpellCheckLanguage(
  88. projectId,
  89. req.body.spellCheckLanguage,
  90. callback
  91. )
  92. )
  93. }
  94. if (req.body.rootDocId != null) {
  95. jobs.push(callback =>
  96. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  97. )
  98. }
  99. async.series(jobs, error => {
  100. if (error != null) {
  101. return next(error)
  102. }
  103. res.sendStatus(204)
  104. })
  105. },
  106. updateProjectAdminSettings(req, res, next) {
  107. const projectId = req.params.Project_id
  108. const jobs = []
  109. if (req.body.publicAccessLevel != null) {
  110. jobs.push(callback =>
  111. EditorController.setPublicAccessLevel(
  112. projectId,
  113. req.body.publicAccessLevel,
  114. callback
  115. )
  116. )
  117. }
  118. async.series(jobs, error => {
  119. if (error != null) {
  120. return next(error)
  121. }
  122. res.sendStatus(204)
  123. })
  124. },
  125. deleteProject(req, res) {
  126. const projectId = req.params.Project_id
  127. const user = AuthenticationController.getSessionUser(req)
  128. const cb = err => {
  129. if (err != null) {
  130. res.sendStatus(500)
  131. } else {
  132. res.sendStatus(200)
  133. }
  134. }
  135. ProjectDeleter.deleteProject(
  136. projectId,
  137. { deleterUser: user, ipAddress: req.ip },
  138. cb
  139. )
  140. },
  141. archiveProject(req, res, next) {
  142. const projectId = req.params.Project_id
  143. const userId = AuthenticationController.getLoggedInUserId(req)
  144. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  145. if (err != null) {
  146. return next(err)
  147. } else {
  148. return res.sendStatus(200)
  149. }
  150. })
  151. },
  152. unarchiveProject(req, res, next) {
  153. const projectId = req.params.Project_id
  154. const userId = AuthenticationController.getLoggedInUserId(req)
  155. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  156. if (err != null) {
  157. return next(err)
  158. } else {
  159. return res.sendStatus(200)
  160. }
  161. })
  162. },
  163. trashProject(req, res, next) {
  164. const projectId = req.params.project_id
  165. const userId = AuthenticationController.getLoggedInUserId(req)
  166. ProjectDeleter.trashProject(projectId, userId, function (err) {
  167. if (err != null) {
  168. return next(err)
  169. } else {
  170. return res.sendStatus(200)
  171. }
  172. })
  173. },
  174. untrashProject(req, res, next) {
  175. const projectId = req.params.project_id
  176. const userId = AuthenticationController.getLoggedInUserId(req)
  177. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  178. if (err != null) {
  179. return next(err)
  180. } else {
  181. return res.sendStatus(200)
  182. }
  183. })
  184. },
  185. expireDeletedProjectsAfterDuration(req, res) {
  186. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  187. if (err != null) {
  188. res.sendStatus(500)
  189. } else {
  190. res.sendStatus(200)
  191. }
  192. })
  193. },
  194. expireDeletedProject(req, res, next) {
  195. const { projectId } = req.params
  196. ProjectDeleter.expireDeletedProject(projectId, err => {
  197. if (err != null) {
  198. next(err)
  199. } else {
  200. res.sendStatus(200)
  201. }
  202. })
  203. },
  204. restoreProject(req, res) {
  205. const projectId = req.params.Project_id
  206. ProjectDeleter.restoreProject(projectId, err => {
  207. if (err != null) {
  208. res.sendStatus(500)
  209. } else {
  210. res.sendStatus(200)
  211. }
  212. })
  213. },
  214. cloneProject(req, res, next) {
  215. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  216. metrics.inc('cloned-project')
  217. const projectId = req.params.Project_id
  218. const { projectName } = req.body
  219. logger.log({ projectId, projectName }, 'cloning project')
  220. if (!AuthenticationController.isUserLoggedIn(req)) {
  221. return res.send({ redir: '/register' })
  222. }
  223. const currentUser = AuthenticationController.getSessionUser(req)
  224. const { first_name: firstName, last_name: lastName, email } = currentUser
  225. ProjectDuplicator.duplicate(
  226. currentUser,
  227. projectId,
  228. projectName,
  229. (err, project) => {
  230. if (err != null) {
  231. OError.tag(err, 'error cloning project', {
  232. projectId,
  233. userId: currentUser._id
  234. })
  235. return next(err)
  236. }
  237. res.send({
  238. name: project.name,
  239. project_id: project._id,
  240. owner_ref: project.owner_ref,
  241. owner: {
  242. first_name: firstName,
  243. last_name: lastName,
  244. email,
  245. _id: currentUser._id
  246. }
  247. })
  248. }
  249. )
  250. },
  251. newProject(req, res, next) {
  252. const currentUser = AuthenticationController.getSessionUser(req)
  253. const {
  254. first_name: firstName,
  255. last_name: lastName,
  256. email,
  257. _id: userId
  258. } = currentUser
  259. const projectName =
  260. req.body.projectName != null ? req.body.projectName.trim() : undefined
  261. const { template } = req.body
  262. async.waterfall(
  263. [
  264. cb => {
  265. if (template === 'example') {
  266. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  267. } else {
  268. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  269. }
  270. }
  271. ],
  272. (err, project) => {
  273. if (err != null) {
  274. return next(err)
  275. }
  276. res.send({
  277. project_id: project._id,
  278. owner_ref: project.owner_ref,
  279. owner: {
  280. first_name: firstName,
  281. last_name: lastName,
  282. email,
  283. _id: userId
  284. }
  285. })
  286. }
  287. )
  288. },
  289. renameProject(req, res, next) {
  290. const projectId = req.params.Project_id
  291. const newName = req.body.newProjectName
  292. EditorController.renameProject(projectId, newName, err => {
  293. if (err != null) {
  294. return next(err)
  295. }
  296. res.sendStatus(200)
  297. })
  298. },
  299. userProjectsJson(req, res, next) {
  300. const userId = AuthenticationController.getLoggedInUserId(req)
  301. ProjectGetter.findAllUsersProjects(
  302. userId,
  303. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  304. (err, projects) => {
  305. if (err != null) {
  306. return next(err)
  307. }
  308. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  309. projects = ProjectController._buildProjectList(projects, userId)
  310. .filter(p => !(p.archived || p.trashed))
  311. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  312. res.json({ projects })
  313. }
  314. )
  315. },
  316. projectEntitiesJson(req, res, next) {
  317. const projectId = req.params.Project_id
  318. ProjectGetter.getProject(projectId, (err, project) => {
  319. if (err != null) {
  320. return next(err)
  321. }
  322. ProjectEntityHandler.getAllEntitiesFromProject(
  323. project,
  324. (err, docs, files) => {
  325. if (err != null) {
  326. return next(err)
  327. }
  328. const entities = docs
  329. .concat(files)
  330. // Sort by path ascending
  331. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  332. .map(e => ({
  333. path: e.path,
  334. type: e.doc != null ? 'doc' : 'file'
  335. }))
  336. res.json({ project_id: projectId, entities })
  337. }
  338. )
  339. })
  340. },
  341. projectListPage(req, res, next) {
  342. const timer = new metrics.Timer('project-list')
  343. const userId = AuthenticationController.getLoggedInUserId(req)
  344. const currentUser = AuthenticationController.getSessionUser(req)
  345. async.parallel(
  346. {
  347. tags(cb) {
  348. TagsHandler.getAllTags(userId, cb)
  349. },
  350. notifications(cb) {
  351. NotificationsHandler.getUserNotifications(userId, cb)
  352. },
  353. projects(cb) {
  354. ProjectGetter.findAllUsersProjects(
  355. userId,
  356. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  357. cb
  358. )
  359. },
  360. hasSubscription(cb) {
  361. LimitationsManager.hasPaidSubscription(
  362. currentUser,
  363. (error, hasPaidSubscription) => {
  364. if (error != null && error instanceof V1ConnectionError) {
  365. return cb(null, true)
  366. }
  367. cb(error, hasPaidSubscription)
  368. }
  369. )
  370. },
  371. user(cb) {
  372. User.findById(
  373. userId,
  374. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  375. cb
  376. )
  377. },
  378. userEmailsData(cb) {
  379. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  380. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  381. if (error && error instanceof V1ConnectionError) {
  382. return cb(null, result)
  383. }
  384. if (!Features.hasFeature('affiliations')) {
  385. result.list = fullEmails
  386. return cb(null, result)
  387. }
  388. Modules.hooks.fire(
  389. 'allInReconfirmNotificationPeriodsForUser',
  390. fullEmails,
  391. (error, results) => {
  392. // Module.hooks.fire accepts multiple methods
  393. // and does async.series
  394. const allInReconfirmNotificationPeriods =
  395. (results && results[0]) || []
  396. return cb(null, {
  397. list: fullEmails,
  398. allInReconfirmNotificationPeriods
  399. })
  400. }
  401. )
  402. })
  403. }
  404. },
  405. (err, results) => {
  406. if (err != null) {
  407. OError.tag(err, 'error getting data for project list page')
  408. return next(err)
  409. }
  410. const { notifications, user, userEmailsData } = results
  411. const userEmails = userEmailsData.list || []
  412. const userAffiliations = userEmails
  413. .filter(emailData => !!emailData.affiliation)
  414. .map(emailData => {
  415. const result = emailData.affiliation
  416. result.email = emailData.email
  417. return result
  418. })
  419. const { allInReconfirmNotificationPeriods } = userEmailsData
  420. // Handle case of deleted user
  421. if (user == null) {
  422. UserController.logout(req, res, next)
  423. return
  424. }
  425. const tags = results.tags
  426. const notificationsInstitution = []
  427. for (const notification of notifications) {
  428. notification.html = req.i18n.translate(
  429. notification.templateKey,
  430. notification.messageOpts
  431. )
  432. }
  433. // Institution SSO Notifications
  434. let reconfirmedViaSAML
  435. if (Features.hasFeature('saml')) {
  436. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  437. const samlSession = req.session.saml
  438. // Notification: SSO Available
  439. const linkedInstitutionIds = []
  440. user.emails.forEach(email => {
  441. if (email.samlProviderId) {
  442. linkedInstitutionIds.push(email.samlProviderId)
  443. }
  444. })
  445. if (Array.isArray(userAffiliations)) {
  446. userAffiliations.forEach(affiliation => {
  447. if (
  448. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  449. ) {
  450. notificationsInstitution.push({
  451. email: affiliation.email,
  452. institutionId: affiliation.institution.id,
  453. institutionName: affiliation.institution.name,
  454. templateKey: 'notification_institution_sso_available'
  455. })
  456. }
  457. })
  458. }
  459. if (samlSession) {
  460. // Notification: After SSO Linked
  461. if (samlSession.linked) {
  462. notificationsInstitution.push({
  463. email: samlSession.institutionEmail,
  464. institutionName: samlSession.linked.universityName,
  465. templateKey: 'notification_institution_sso_linked'
  466. })
  467. }
  468. // Notification: After SSO Linked or Logging in
  469. // The requested email does not match primary email returned from
  470. // the institution
  471. if (
  472. samlSession.requestedEmail &&
  473. samlSession.emailNonCanonical &&
  474. !samlSession.error
  475. ) {
  476. notificationsInstitution.push({
  477. institutionEmail: samlSession.emailNonCanonical,
  478. requestedEmail: samlSession.requestedEmail,
  479. templateKey: 'notification_institution_sso_non_canonical'
  480. })
  481. }
  482. // Notification: Tried to register, but account already existed
  483. // registerIntercept is set before the institution callback.
  484. // institutionEmail is set after institution callback.
  485. // Check for both in case SSO flow was abandoned
  486. if (
  487. samlSession.registerIntercept &&
  488. samlSession.institutionEmail &&
  489. !samlSession.error
  490. ) {
  491. notificationsInstitution.push({
  492. email: samlSession.institutionEmail,
  493. templateKey: 'notification_institution_sso_already_registered'
  494. })
  495. }
  496. // Notification: When there is a session error
  497. if (samlSession.error) {
  498. notificationsInstitution.push({
  499. templateKey: 'notification_institution_sso_error',
  500. error: samlSession.error
  501. })
  502. }
  503. }
  504. delete req.session.saml
  505. }
  506. const portalTemplates = ProjectController._buildPortalTemplatesList(
  507. userAffiliations
  508. )
  509. const projects = ProjectController._buildProjectList(
  510. results.projects,
  511. userId
  512. )
  513. // in v2 add notifications for matching university IPs
  514. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  515. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  516. }
  517. ProjectController._injectProjectUsers(projects, (error, projects) => {
  518. if (error != null) {
  519. return next(error)
  520. }
  521. const viewModel = {
  522. title: 'your_projects',
  523. priority_title: true,
  524. projects,
  525. tags,
  526. notifications: notifications || [],
  527. notificationsInstitution,
  528. allInReconfirmNotificationPeriods,
  529. portalTemplates,
  530. user,
  531. userAffiliations,
  532. userEmails,
  533. hasSubscription: results.hasSubscription,
  534. reconfirmedViaSAML,
  535. zipFileSizeLimit: Settings.maxUploadSize
  536. }
  537. if (
  538. Settings.algolia &&
  539. Settings.algolia.app_id &&
  540. Settings.algolia.read_only_api_key
  541. ) {
  542. viewModel.showUserDetailsArea = true
  543. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  544. viewModel.algolia_app_id = Settings.algolia.app_id
  545. } else {
  546. viewModel.showUserDetailsArea = false
  547. }
  548. const paidUser =
  549. (user.features != null ? user.features.github : undefined) &&
  550. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  551. const freeUserProportion = 0.1
  552. const sampleFreeUser =
  553. parseInt(user._id.toString().slice(-2), 16) <
  554. freeUserProportion * 255
  555. const showFrontWidget = paidUser || sampleFreeUser
  556. if (showFrontWidget) {
  557. viewModel.frontChatWidgetRoomId =
  558. Settings.overleaf != null
  559. ? Settings.overleaf.front_chat_widget_room_id
  560. : undefined
  561. }
  562. res.render('project/list', viewModel)
  563. timer.done()
  564. })
  565. }
  566. )
  567. },
  568. loadEditor(req, res, next) {
  569. const timer = new metrics.Timer('load-editor')
  570. if (!Settings.editorIsOpen) {
  571. return res.render('general/closed', { title: 'updating_site' })
  572. }
  573. let anonymous, userId, sessionUser
  574. if (AuthenticationController.isUserLoggedIn(req)) {
  575. sessionUser = AuthenticationController.getSessionUser(req)
  576. userId = AuthenticationController.getLoggedInUserId(req)
  577. anonymous = false
  578. } else {
  579. sessionUser = null
  580. anonymous = true
  581. userId = null
  582. }
  583. const projectId = req.params.Project_id
  584. async.auto(
  585. {
  586. project(cb) {
  587. ProjectGetter.getProject(
  588. projectId,
  589. {
  590. name: 1,
  591. lastUpdated: 1,
  592. track_changes: 1,
  593. owner_ref: 1,
  594. brandVariationId: 1,
  595. overleaf: 1,
  596. tokens: 1
  597. },
  598. (err, project) => {
  599. if (err != null) {
  600. return cb(err)
  601. }
  602. cb(null, project)
  603. }
  604. )
  605. },
  606. user(cb) {
  607. if (userId == null) {
  608. cb(null, defaultSettingsForAnonymousUser(userId))
  609. } else {
  610. User.findById(
  611. userId,
  612. 'email first_name last_name referal_id signUpDate featureSwitches features refProviders alphaProgram betaProgram isAdmin ace',
  613. (err, user) => {
  614. // Handle case of deleted user
  615. if (user == null) {
  616. UserController.logout(req, res, next)
  617. return
  618. }
  619. logger.log({ projectId, userId }, 'got user')
  620. cb(err, user)
  621. }
  622. )
  623. }
  624. },
  625. subscription(cb) {
  626. if (userId == null) {
  627. return cb()
  628. }
  629. SubscriptionLocator.getUsersSubscription(userId, cb)
  630. },
  631. activate(cb) {
  632. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  633. },
  634. markAsOpened(cb) {
  635. // don't need to wait for this to complete
  636. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  637. cb()
  638. },
  639. isTokenMember(cb) {
  640. if (userId == null) {
  641. return cb()
  642. }
  643. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  644. },
  645. brandVariation: [
  646. 'project',
  647. (cb, results) => {
  648. if (
  649. (results.project != null
  650. ? results.project.brandVariationId
  651. : undefined) == null
  652. ) {
  653. return cb()
  654. }
  655. BrandVariationsHandler.getBrandVariationById(
  656. results.project.brandVariationId,
  657. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  658. )
  659. }
  660. ],
  661. flushToTpds: cb => {
  662. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  663. }
  664. },
  665. (err, results) => {
  666. if (err != null) {
  667. OError.tag(err, 'error getting details for project page')
  668. return next(err)
  669. }
  670. const { project } = results
  671. const { user } = results
  672. const { subscription } = results
  673. const { brandVariation } = results
  674. const anonRequestToken = TokenAccessHandler.getRequestToken(
  675. req,
  676. projectId
  677. )
  678. const { isTokenMember } = results
  679. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  680. sessionUser
  681. )
  682. const wantsOldFileTreeUI =
  683. req.query && req.query.new_file_tree_ui === 'false'
  684. const wantsOldShareModalUI =
  685. req.query && req.query.new_share_modal_ui === 'false'
  686. const wantsOldAddFilesModalUI =
  687. req.query && req.query.new_add_files_modal_ui === 'false'
  688. const wantsOldGithubSyncUI =
  689. req.query && req.query.new_github_sync_ui === 'false'
  690. AuthorizationManager.getPrivilegeLevelForProject(
  691. userId,
  692. projectId,
  693. anonRequestToken,
  694. (error, privilegeLevel) => {
  695. let allowedFreeTrial = true
  696. if (error != null) {
  697. return next(error)
  698. }
  699. if (
  700. privilegeLevel == null ||
  701. privilegeLevel === PrivilegeLevels.NONE
  702. ) {
  703. return res.sendStatus(401)
  704. }
  705. if (subscription != null) {
  706. allowedFreeTrial = false
  707. }
  708. let wsUrl = Settings.wsUrl
  709. let metricName = 'load-editor-ws'
  710. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  711. wsUrl = Settings.wsUrlBeta
  712. metricName += '-beta'
  713. } else if (
  714. Settings.wsUrlV2 &&
  715. Settings.wsUrlV2Percentage > 0 &&
  716. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  717. Settings.wsUrlV2Percentage
  718. ) {
  719. wsUrl = Settings.wsUrlV2
  720. metricName += '-v2'
  721. }
  722. if (req.query && req.query.ws === 'fallback') {
  723. // `?ws=fallback` will connect to the bare origin, and ignore
  724. // the custom wsUrl. Hence it must load the client side
  725. // javascript from there too.
  726. // Not resetting it here would possibly load a socket.io v2
  727. // client and connect to a v0 endpoint.
  728. wsUrl = undefined
  729. metricName += '-fallback'
  730. }
  731. metrics.inc(metricName)
  732. if (userId) {
  733. AnalyticsManager.recordEvent(userId, 'project-opened', {
  734. projectId: project._id
  735. })
  736. }
  737. const logsUIVariant = getNewLogsUIVariantForUser(user)
  738. const userShouldSeeNewLogsUI = logsUIVariant.newLogsUI
  739. const wantsOldLogsUI =
  740. req.query && req.query.new_logs_ui === 'false'
  741. res.render('project/editor', {
  742. title: project.name,
  743. priority_title: true,
  744. bodyClasses: ['editor'],
  745. project_id: project._id,
  746. user: {
  747. id: userId,
  748. email: user.email,
  749. first_name: user.first_name,
  750. last_name: user.last_name,
  751. referal_id: user.referal_id,
  752. signUpDate: user.signUpDate,
  753. allowedFreeTrial: allowedFreeTrial,
  754. featureSwitches: user.featureSwitches,
  755. features: user.features,
  756. refProviders: _.mapValues(user.refProviders, Boolean),
  757. alphaProgram: user.alphaProgram,
  758. betaProgram: user.betaProgram,
  759. isAdmin: user.isAdmin
  760. },
  761. userSettings: {
  762. mode: user.ace.mode,
  763. editorTheme: user.ace.theme,
  764. fontSize: user.ace.fontSize,
  765. autoComplete: user.ace.autoComplete,
  766. autoPairDelimiters: user.ace.autoPairDelimiters,
  767. pdfViewer: user.ace.pdfViewer,
  768. syntaxValidation: user.ace.syntaxValidation,
  769. fontFamily: user.ace.fontFamily || 'lucida',
  770. lineHeight: user.ace.lineHeight || 'normal',
  771. overallTheme: user.ace.overallTheme
  772. },
  773. privilegeLevel,
  774. chatUrl: Settings.apis.chat.url,
  775. anonymous,
  776. anonymousAccessToken: anonymous ? anonRequestToken : null,
  777. isTokenMember,
  778. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  779. userId,
  780. privilegeLevel,
  781. isTokenMember
  782. ),
  783. languages: Settings.languages,
  784. editorThemes: THEME_LIST,
  785. maxDocLength: Settings.max_doc_length,
  786. useV2History:
  787. project.overleaf &&
  788. project.overleaf.history &&
  789. Boolean(project.overleaf.history.display),
  790. brandVariation,
  791. allowedImageNames,
  792. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  793. wsUrl,
  794. showSupport: Features.hasFeature('support'),
  795. showNewLogsUI: userShouldSeeNewLogsUI && !wantsOldLogsUI,
  796. logsUISubvariant: logsUIVariant.subvariant,
  797. showNewNavigationUI:
  798. req.query && req.query.new_navigation_ui === 'true',
  799. showReactFileTree: !wantsOldFileTreeUI,
  800. showReactShareModal: user.betaProgram && !wantsOldShareModalUI,
  801. showReactAddFilesModal:
  802. user.betaProgram && !wantsOldAddFilesModalUI,
  803. showReactGithubSync: !wantsOldGithubSyncUI && user.alphaProgram
  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