ProjectController.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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('@overleaf/settings')
  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 SessionManager = require('../Authentication/SessionManager')
  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 SplitTestHandler = require('../SplitTests/SplitTestHandler')
  41. const { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
  42. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  43. if (!affiliation.institution) return false
  44. // institution.confirmed is for the domain being confirmed, not the email
  45. // Do not show SSO UI for unconfirmed domains
  46. if (!affiliation.institution.confirmed) return false
  47. // Could have multiple emails at the same institution, and if any are
  48. // linked to the institution then do not show notification for others
  49. if (
  50. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  51. ) {
  52. if (affiliation.institution.ssoEnabled) return true
  53. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  54. return false
  55. }
  56. return false
  57. }
  58. const ProjectController = {
  59. _isInPercentageRollout(rolloutName, objectId, percentage) {
  60. if (Settings.bypassPercentageRollouts === true) {
  61. return true
  62. }
  63. const data = `${rolloutName}:${objectId.toString()}`
  64. const md5hash = crypto.createHash('md5').update(data).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 = SessionManager.getSessionUser(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 (!SessionManager.isUserLoggedIn(req.session)) {
  222. return res.send({ redir: '/register' })
  223. }
  224. const currentUser = SessionManager.getSessionUser(req.session)
  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 = SessionManager.getSessionUser(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  345. const currentUser = SessionManager.getSessionUser(req.session)
  346. async.parallel(
  347. {
  348. tags(cb) {
  349. TagsHandler.getAllTags(userId, cb)
  350. },
  351. notifications(cb) {
  352. NotificationsHandler.getUserNotifications(userId, cb)
  353. },
  354. projects(cb) {
  355. ProjectGetter.findAllUsersProjects(
  356. userId,
  357. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  358. cb
  359. )
  360. },
  361. hasSubscription(cb) {
  362. LimitationsManager.hasPaidSubscription(
  363. currentUser,
  364. (error, hasPaidSubscription) => {
  365. if (error != null && error instanceof V1ConnectionError) {
  366. return cb(null, true)
  367. }
  368. cb(error, hasPaidSubscription)
  369. }
  370. )
  371. },
  372. user(cb) {
  373. User.findById(
  374. userId,
  375. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  376. cb
  377. )
  378. },
  379. userEmailsData(cb) {
  380. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  381. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  382. if (error && error instanceof V1ConnectionError) {
  383. return cb(null, result)
  384. }
  385. if (!Features.hasFeature('affiliations')) {
  386. result.list = fullEmails
  387. return cb(null, result)
  388. }
  389. Modules.hooks.fire(
  390. 'allInReconfirmNotificationPeriodsForUser',
  391. fullEmails,
  392. (error, results) => {
  393. // Module.hooks.fire accepts multiple methods
  394. // and does async.series
  395. const allInReconfirmNotificationPeriods =
  396. (results && results[0]) || []
  397. return cb(null, {
  398. list: fullEmails,
  399. allInReconfirmNotificationPeriods,
  400. })
  401. }
  402. )
  403. })
  404. },
  405. },
  406. (err, results) => {
  407. if (err != null) {
  408. OError.tag(err, 'error getting data for project list page')
  409. return next(err)
  410. }
  411. const { notifications, user, userEmailsData } = results
  412. const userEmails = userEmailsData.list || []
  413. const userAffiliations = userEmails
  414. .filter(emailData => !!emailData.affiliation)
  415. .map(emailData => {
  416. const result = emailData.affiliation
  417. result.email = emailData.email
  418. return result
  419. })
  420. const { allInReconfirmNotificationPeriods } = userEmailsData
  421. // Handle case of deleted user
  422. if (user == null) {
  423. UserController.logout(req, res, next)
  424. return
  425. }
  426. const tags = results.tags
  427. const notificationsInstitution = []
  428. for (const notification of notifications) {
  429. notification.html = req.i18n.translate(
  430. notification.templateKey,
  431. notification.messageOpts
  432. )
  433. }
  434. // Institution SSO Notifications
  435. let reconfirmedViaSAML
  436. if (Features.hasFeature('saml')) {
  437. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  438. const samlSession = req.session.saml
  439. // Notification: SSO Available
  440. const linkedInstitutionIds = []
  441. user.emails.forEach(email => {
  442. if (email.samlProviderId) {
  443. linkedInstitutionIds.push(email.samlProviderId)
  444. }
  445. })
  446. if (Array.isArray(userAffiliations)) {
  447. userAffiliations.forEach(affiliation => {
  448. if (
  449. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  450. ) {
  451. notificationsInstitution.push({
  452. email: affiliation.email,
  453. institutionId: affiliation.institution.id,
  454. institutionName: affiliation.institution.name,
  455. templateKey: 'notification_institution_sso_available',
  456. })
  457. }
  458. })
  459. }
  460. if (samlSession) {
  461. // Notification: After SSO Linked
  462. if (samlSession.linked) {
  463. notificationsInstitution.push({
  464. email: samlSession.institutionEmail,
  465. institutionName: samlSession.linked.universityName,
  466. templateKey: 'notification_institution_sso_linked',
  467. })
  468. }
  469. // Notification: After SSO Linked or Logging in
  470. // The requested email does not match primary email returned from
  471. // the institution
  472. if (
  473. samlSession.requestedEmail &&
  474. samlSession.emailNonCanonical &&
  475. !samlSession.error
  476. ) {
  477. notificationsInstitution.push({
  478. institutionEmail: samlSession.emailNonCanonical,
  479. requestedEmail: samlSession.requestedEmail,
  480. templateKey: 'notification_institution_sso_non_canonical',
  481. })
  482. }
  483. // Notification: Tried to register, but account already existed
  484. // registerIntercept is set before the institution callback.
  485. // institutionEmail is set after institution callback.
  486. // Check for both in case SSO flow was abandoned
  487. if (
  488. samlSession.registerIntercept &&
  489. samlSession.institutionEmail &&
  490. !samlSession.error
  491. ) {
  492. notificationsInstitution.push({
  493. email: samlSession.institutionEmail,
  494. templateKey: 'notification_institution_sso_already_registered',
  495. })
  496. }
  497. // Notification: When there is a session error
  498. if (samlSession.error) {
  499. notificationsInstitution.push({
  500. templateKey: 'notification_institution_sso_error',
  501. error: samlSession.error,
  502. })
  503. }
  504. }
  505. delete req.session.saml
  506. }
  507. const portalTemplates = ProjectController._buildPortalTemplatesList(
  508. userAffiliations
  509. )
  510. const projects = ProjectController._buildProjectList(
  511. results.projects,
  512. userId
  513. )
  514. // in v2 add notifications for matching university IPs
  515. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  516. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  517. }
  518. ProjectController._injectProjectUsers(projects, (error, projects) => {
  519. if (error != null) {
  520. return next(error)
  521. }
  522. const viewModel = {
  523. title: 'your_projects',
  524. priority_title: true,
  525. projects,
  526. tags,
  527. notifications: notifications || [],
  528. notificationsInstitution,
  529. allInReconfirmNotificationPeriods,
  530. portalTemplates,
  531. user,
  532. userAffiliations,
  533. userEmails,
  534. hasSubscription: results.hasSubscription,
  535. reconfirmedViaSAML,
  536. zipFileSizeLimit: Settings.maxUploadSize,
  537. isOverleaf: !!Settings.overleaf,
  538. }
  539. const paidUser =
  540. (user.features != null ? user.features.github : undefined) &&
  541. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  542. const freeUserProportion = 0.1
  543. const sampleFreeUser =
  544. parseInt(user._id.toString().slice(-2), 16) <
  545. freeUserProportion * 255
  546. const showFrontWidget = paidUser || sampleFreeUser
  547. if (showFrontWidget) {
  548. viewModel.frontChatWidgetRoomId =
  549. Settings.overleaf != null
  550. ? Settings.overleaf.front_chat_widget_room_id
  551. : undefined
  552. }
  553. res.render('project/list', viewModel)
  554. timer.done()
  555. })
  556. }
  557. )
  558. },
  559. loadEditor(req, res, next) {
  560. const timer = new metrics.Timer('load-editor')
  561. if (!Settings.editorIsOpen) {
  562. return res.render('general/closed', { title: 'updating_site' })
  563. }
  564. let anonymous, userId, sessionUser
  565. if (SessionManager.isUserLoggedIn(req.session)) {
  566. sessionUser = SessionManager.getSessionUser(req.session)
  567. userId = SessionManager.getLoggedInUserId(req.session)
  568. anonymous = false
  569. } else {
  570. sessionUser = null
  571. anonymous = true
  572. userId = null
  573. }
  574. const projectId = req.params.Project_id
  575. async.auto(
  576. {
  577. project(cb) {
  578. ProjectGetter.getProject(
  579. projectId,
  580. {
  581. name: 1,
  582. lastUpdated: 1,
  583. track_changes: 1,
  584. owner_ref: 1,
  585. brandVariationId: 1,
  586. overleaf: 1,
  587. tokens: 1,
  588. },
  589. (err, project) => {
  590. if (err != null) {
  591. return cb(err)
  592. }
  593. cb(null, project)
  594. }
  595. )
  596. },
  597. user(cb) {
  598. if (userId == null) {
  599. cb(null, defaultSettingsForAnonymousUser(userId))
  600. } else {
  601. User.findById(
  602. userId,
  603. 'email first_name last_name referal_id signUpDate featureSwitches features refProviders alphaProgram betaProgram isAdmin ace',
  604. (err, user) => {
  605. // Handle case of deleted user
  606. if (user == null) {
  607. UserController.logout(req, res, next)
  608. return
  609. }
  610. logger.log({ projectId, userId }, 'got user')
  611. cb(err, user)
  612. }
  613. )
  614. }
  615. },
  616. subscription(cb) {
  617. if (userId == null) {
  618. return cb()
  619. }
  620. SubscriptionLocator.getUsersSubscription(userId, cb)
  621. },
  622. activate(cb) {
  623. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  624. },
  625. markAsOpened(cb) {
  626. // don't need to wait for this to complete
  627. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  628. cb()
  629. },
  630. isTokenMember(cb) {
  631. if (userId == null) {
  632. return cb()
  633. }
  634. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  635. },
  636. brandVariation: [
  637. 'project',
  638. (cb, results) => {
  639. if (
  640. (results.project != null
  641. ? results.project.brandVariationId
  642. : undefined) == null
  643. ) {
  644. return cb()
  645. }
  646. BrandVariationsHandler.getBrandVariationById(
  647. results.project.brandVariationId,
  648. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  649. )
  650. },
  651. ],
  652. flushToTpds: cb => {
  653. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  654. },
  655. pdfCachingFeatureFlag(cb) {
  656. if (!Settings.enablePdfCaching) return cb(null, '')
  657. if (!userId) return cb(null, 'enable-caching-only')
  658. SplitTestHandler.getTestSegmentation(
  659. userId,
  660. 'pdf_caching_full',
  661. (err, segmentation) => {
  662. if (err) {
  663. // Do not fail loading the editor.
  664. return cb(null, '')
  665. }
  666. cb(null, (segmentation && segmentation.variant) || '')
  667. }
  668. )
  669. },
  670. },
  671. (err, results) => {
  672. if (err != null) {
  673. OError.tag(err, 'error getting details for project page')
  674. return next(err)
  675. }
  676. const { project } = results
  677. const { user } = results
  678. const { subscription } = results
  679. const { brandVariation } = results
  680. const { pdfCachingFeatureFlag } = results
  681. const anonRequestToken = TokenAccessHandler.getRequestToken(
  682. req,
  683. projectId
  684. )
  685. const { isTokenMember } = results
  686. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  687. sessionUser
  688. )
  689. AuthorizationManager.getPrivilegeLevelForProject(
  690. userId,
  691. projectId,
  692. anonRequestToken,
  693. (error, privilegeLevel) => {
  694. let allowedFreeTrial = true
  695. if (error != null) {
  696. return next(error)
  697. }
  698. if (
  699. privilegeLevel == null ||
  700. privilegeLevel === PrivilegeLevels.NONE
  701. ) {
  702. return res.sendStatus(401)
  703. }
  704. if (subscription != null) {
  705. allowedFreeTrial = false
  706. }
  707. let wsUrl = Settings.wsUrl
  708. let metricName = 'load-editor-ws'
  709. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  710. wsUrl = Settings.wsUrlBeta
  711. metricName += '-beta'
  712. } else if (
  713. Settings.wsUrlV2 &&
  714. Settings.wsUrlV2Percentage > 0 &&
  715. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  716. Settings.wsUrlV2Percentage
  717. ) {
  718. wsUrl = Settings.wsUrlV2
  719. metricName += '-v2'
  720. }
  721. if (req.query && req.query.ws === 'fallback') {
  722. // `?ws=fallback` will connect to the bare origin, and ignore
  723. // the custom wsUrl. Hence it must load the client side
  724. // javascript from there too.
  725. // Not resetting it here would possibly load a socket.io v2
  726. // client and connect to a v0 endpoint.
  727. wsUrl = undefined
  728. metricName += '-fallback'
  729. }
  730. metrics.inc(metricName)
  731. if (userId) {
  732. AnalyticsManager.recordEvent(userId, 'project-opened', {
  733. projectId: project._id,
  734. })
  735. }
  736. const logsUIVariant = getNewLogsUIVariantForUser(user)
  737. function shouldDisplayFeature(name, variantFlag) {
  738. if (req.query && req.query[name]) {
  739. return req.query[name] === 'true'
  740. } else {
  741. return variantFlag === true
  742. }
  743. }
  744. function partOfPdfCachingRollout(flag) {
  745. if (!Settings.enablePdfCaching) {
  746. // The feature is disabled globally.
  747. return false
  748. }
  749. const canSeeFeaturePreview = pdfCachingFeatureFlag.includes(flag)
  750. if (!canSeeFeaturePreview) {
  751. // The user is not in the target group.
  752. return false
  753. }
  754. // Optionally let the user opt-out.
  755. // The will opt-out of both caching and metrics collection,
  756. // as if this editing session never happened.
  757. return shouldDisplayFeature('enable_pdf_caching', true)
  758. }
  759. res.render('project/editor', {
  760. title: project.name,
  761. priority_title: true,
  762. bodyClasses: ['editor'],
  763. project_id: project._id,
  764. user: {
  765. id: userId,
  766. email: user.email,
  767. first_name: user.first_name,
  768. last_name: user.last_name,
  769. referal_id: user.referal_id,
  770. signUpDate: user.signUpDate,
  771. allowedFreeTrial: allowedFreeTrial,
  772. featureSwitches: user.featureSwitches,
  773. features: user.features,
  774. refProviders: _.mapValues(user.refProviders, Boolean),
  775. alphaProgram: user.alphaProgram,
  776. betaProgram: user.betaProgram,
  777. isAdmin: user.isAdmin,
  778. },
  779. userSettings: {
  780. mode: user.ace.mode,
  781. editorTheme: user.ace.theme,
  782. fontSize: user.ace.fontSize,
  783. autoComplete: user.ace.autoComplete,
  784. autoPairDelimiters: user.ace.autoPairDelimiters,
  785. pdfViewer: user.ace.pdfViewer,
  786. syntaxValidation: user.ace.syntaxValidation,
  787. fontFamily: user.ace.fontFamily || 'lucida',
  788. lineHeight: user.ace.lineHeight || 'normal',
  789. overallTheme: user.ace.overallTheme,
  790. },
  791. privilegeLevel,
  792. anonymous,
  793. anonymousAccessToken: anonymous ? anonRequestToken : null,
  794. isTokenMember,
  795. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  796. userId,
  797. privilegeLevel,
  798. isTokenMember
  799. ),
  800. languages: Settings.languages,
  801. editorThemes: THEME_LIST,
  802. maxDocLength: Settings.max_doc_length,
  803. useV2History:
  804. project.overleaf &&
  805. project.overleaf.history &&
  806. Boolean(project.overleaf.history.display),
  807. brandVariation,
  808. allowedImageNames,
  809. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  810. wsUrl,
  811. showSupport: Features.hasFeature('support'),
  812. showNewLogsUI: shouldDisplayFeature(
  813. 'new_logs_ui',
  814. logsUIVariant.newLogsUI
  815. ),
  816. logsUISubvariant: logsUIVariant.subvariant,
  817. showNewNavigationUI: shouldDisplayFeature(
  818. 'new_navigation_ui',
  819. true
  820. ),
  821. showNewFileViewUI: shouldDisplayFeature(
  822. 'new_file_view',
  823. user.alphaProgram || user.betaProgram
  824. ),
  825. showSymbolPalette: shouldDisplayFeature(
  826. 'symbol_palette',
  827. user.alphaProgram || user.betaProgram
  828. ),
  829. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  830. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  831. resetServiceWorker: Boolean(Settings.resetServiceWorker),
  832. })
  833. timer.done()
  834. }
  835. )
  836. }
  837. )
  838. },
  839. _buildProjectList(allProjects, userId) {
  840. let project
  841. const {
  842. owned,
  843. readAndWrite,
  844. readOnly,
  845. tokenReadAndWrite,
  846. tokenReadOnly,
  847. } = allProjects
  848. const projects = []
  849. for (project of owned) {
  850. projects.push(
  851. ProjectController._buildProjectViewModel(
  852. project,
  853. 'owner',
  854. Sources.OWNER,
  855. userId
  856. )
  857. )
  858. }
  859. // Invite-access
  860. for (project of readAndWrite) {
  861. projects.push(
  862. ProjectController._buildProjectViewModel(
  863. project,
  864. 'readWrite',
  865. Sources.INVITE,
  866. userId
  867. )
  868. )
  869. }
  870. for (project of readOnly) {
  871. projects.push(
  872. ProjectController._buildProjectViewModel(
  873. project,
  874. 'readOnly',
  875. Sources.INVITE,
  876. userId
  877. )
  878. )
  879. }
  880. // Token-access
  881. // Only add these projects if they're not already present, this gives us cascading access
  882. // from 'owner' => 'token-read-only'
  883. for (project of tokenReadAndWrite) {
  884. if (
  885. projects.filter(p => p.id.toString() === project._id.toString())
  886. .length === 0
  887. ) {
  888. projects.push(
  889. ProjectController._buildProjectViewModel(
  890. project,
  891. 'readAndWrite',
  892. Sources.TOKEN,
  893. userId
  894. )
  895. )
  896. }
  897. }
  898. for (project of tokenReadOnly) {
  899. if (
  900. projects.filter(p => p.id.toString() === project._id.toString())
  901. .length === 0
  902. ) {
  903. projects.push(
  904. ProjectController._buildProjectViewModel(
  905. project,
  906. 'readOnly',
  907. Sources.TOKEN,
  908. userId
  909. )
  910. )
  911. }
  912. }
  913. return projects
  914. },
  915. _buildProjectViewModel(project, accessLevel, source, userId) {
  916. const archived = ProjectHelper.isArchived(project, userId)
  917. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  918. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  919. TokenAccessHandler.protectTokens(project, accessLevel)
  920. const model = {
  921. id: project._id,
  922. name: project.name,
  923. lastUpdated: project.lastUpdated,
  924. lastUpdatedBy: project.lastUpdatedBy,
  925. publicAccessLevel: project.publicAccesLevel,
  926. accessLevel,
  927. source,
  928. archived,
  929. trashed,
  930. owner_ref: project.owner_ref,
  931. isV1Project: false,
  932. }
  933. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  934. model.owner_ref = null
  935. model.lastUpdatedBy = null
  936. }
  937. return model
  938. },
  939. _injectProjectUsers(projects, callback) {
  940. const users = {}
  941. for (const project of projects) {
  942. if (project.owner_ref != null) {
  943. users[project.owner_ref.toString()] = true
  944. }
  945. if (project.lastUpdatedBy != null) {
  946. users[project.lastUpdatedBy.toString()] = true
  947. }
  948. }
  949. const userIds = Object.keys(users)
  950. async.eachSeries(
  951. userIds,
  952. (userId, cb) => {
  953. UserGetter.getUser(
  954. userId,
  955. { first_name: 1, last_name: 1, email: 1 },
  956. (error, user) => {
  957. if (error != null) {
  958. return cb(error)
  959. }
  960. users[userId] = user
  961. cb()
  962. }
  963. )
  964. },
  965. error => {
  966. if (error != null) {
  967. return callback(error)
  968. }
  969. for (const project of projects) {
  970. if (project.owner_ref != null) {
  971. project.owner = users[project.owner_ref.toString()]
  972. }
  973. if (project.lastUpdatedBy != null) {
  974. project.lastUpdatedBy =
  975. users[project.lastUpdatedBy.toString()] || null
  976. }
  977. }
  978. callback(null, projects)
  979. }
  980. )
  981. },
  982. _buildPortalTemplatesList(affiliations) {
  983. if (affiliations == null) {
  984. affiliations = []
  985. }
  986. const portalTemplates = []
  987. for (const aff of affiliations) {
  988. if (
  989. aff.portal &&
  990. aff.portal.slug &&
  991. aff.portal.templates_count &&
  992. aff.portal.templates_count > 0
  993. ) {
  994. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  995. portalTemplates.push({
  996. name: aff.institution.name,
  997. url: Settings.siteUrl + portalPath + aff.portal.slug,
  998. })
  999. }
  1000. }
  1001. return portalTemplates
  1002. },
  1003. }
  1004. var defaultSettingsForAnonymousUser = userId => ({
  1005. id: userId,
  1006. ace: {
  1007. mode: 'none',
  1008. theme: 'textmate',
  1009. fontSize: '12',
  1010. autoComplete: true,
  1011. spellCheckLanguage: '',
  1012. pdfViewer: '',
  1013. syntaxValidation: true,
  1014. },
  1015. subscription: {
  1016. freeTrial: {
  1017. allowed: true,
  1018. },
  1019. },
  1020. featureSwitches: {
  1021. github: false,
  1022. },
  1023. alphaProgram: false,
  1024. betaProgram: false,
  1025. })
  1026. var THEME_LIST = []
  1027. function generateThemeList() {
  1028. const files = fs.readdirSync(
  1029. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1030. )
  1031. const result = []
  1032. for (const file of files) {
  1033. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1034. const cleanName = file.slice(0, -3).slice(6)
  1035. result.push(THEME_LIST.push(cleanName))
  1036. } else {
  1037. result.push(undefined)
  1038. }
  1039. }
  1040. }
  1041. generateThemeList()
  1042. module.exports = ProjectController