ProjectController.js 33 KB

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