ProjectController.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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 SplitTestV2Handler = require('../SplitTests/SplitTestV2Handler')
  41. const { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
  42. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  43. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  44. if (!affiliation.institution) return false
  45. // institution.confirmed is for the domain being confirmed, not the email
  46. // Do not show SSO UI for unconfirmed domains
  47. if (!affiliation.institution.confirmed) return false
  48. // Could have multiple emails at the same institution, and if any are
  49. // linked to the institution then do not show notification for others
  50. if (
  51. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  52. ) {
  53. if (affiliation.institution.ssoEnabled) return true
  54. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  55. return false
  56. }
  57. return false
  58. }
  59. const ProjectController = {
  60. _isInPercentageRollout(rolloutName, objectId, percentage) {
  61. if (Settings.bypassPercentageRollouts === true) {
  62. return true
  63. }
  64. const data = `${rolloutName}:${objectId.toString()}`
  65. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  66. const counter = parseInt(md5hash.slice(26, 32), 16)
  67. return counter % 100 < percentage
  68. },
  69. updateProjectSettings(req, res, next) {
  70. const projectId = req.params.Project_id
  71. const jobs = []
  72. if (req.body.compiler != null) {
  73. jobs.push(callback =>
  74. EditorController.setCompiler(projectId, req.body.compiler, callback)
  75. )
  76. }
  77. if (req.body.imageName != null) {
  78. jobs.push(callback =>
  79. EditorController.setImageName(projectId, req.body.imageName, callback)
  80. )
  81. }
  82. if (req.body.name != null) {
  83. jobs.push(callback =>
  84. EditorController.renameProject(projectId, req.body.name, callback)
  85. )
  86. }
  87. if (req.body.spellCheckLanguage != null) {
  88. jobs.push(callback =>
  89. EditorController.setSpellCheckLanguage(
  90. projectId,
  91. req.body.spellCheckLanguage,
  92. callback
  93. )
  94. )
  95. }
  96. if (req.body.rootDocId != null) {
  97. jobs.push(callback =>
  98. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  99. )
  100. }
  101. async.series(jobs, error => {
  102. if (error != null) {
  103. return next(error)
  104. }
  105. res.sendStatus(204)
  106. })
  107. },
  108. updateProjectAdminSettings(req, res, next) {
  109. const projectId = req.params.Project_id
  110. const jobs = []
  111. if (req.body.publicAccessLevel != null) {
  112. jobs.push(callback =>
  113. EditorController.setPublicAccessLevel(
  114. projectId,
  115. req.body.publicAccessLevel,
  116. callback
  117. )
  118. )
  119. }
  120. async.series(jobs, error => {
  121. if (error != null) {
  122. return next(error)
  123. }
  124. res.sendStatus(204)
  125. })
  126. },
  127. deleteProject(req, res) {
  128. const projectId = req.params.Project_id
  129. const user = SessionManager.getSessionUser(req.session)
  130. const cb = err => {
  131. if (err != null) {
  132. res.sendStatus(500)
  133. } else {
  134. res.sendStatus(200)
  135. }
  136. }
  137. ProjectDeleter.deleteProject(
  138. projectId,
  139. { deleterUser: user, ipAddress: req.ip },
  140. cb
  141. )
  142. },
  143. archiveProject(req, res, next) {
  144. const projectId = req.params.Project_id
  145. const userId = SessionManager.getLoggedInUserId(req.session)
  146. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  147. if (err != null) {
  148. return next(err)
  149. } else {
  150. return res.sendStatus(200)
  151. }
  152. })
  153. },
  154. unarchiveProject(req, res, next) {
  155. const projectId = req.params.Project_id
  156. const userId = SessionManager.getLoggedInUserId(req.session)
  157. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  158. if (err != null) {
  159. return next(err)
  160. } else {
  161. return res.sendStatus(200)
  162. }
  163. })
  164. },
  165. trashProject(req, res, next) {
  166. const projectId = req.params.project_id
  167. const userId = SessionManager.getLoggedInUserId(req.session)
  168. ProjectDeleter.trashProject(projectId, userId, function (err) {
  169. if (err != null) {
  170. return next(err)
  171. } else {
  172. return res.sendStatus(200)
  173. }
  174. })
  175. },
  176. untrashProject(req, res, next) {
  177. const projectId = req.params.project_id
  178. const userId = SessionManager.getLoggedInUserId(req.session)
  179. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  180. if (err != null) {
  181. return next(err)
  182. } else {
  183. return res.sendStatus(200)
  184. }
  185. })
  186. },
  187. expireDeletedProjectsAfterDuration(req, res) {
  188. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  189. if (err != null) {
  190. res.sendStatus(500)
  191. } else {
  192. res.sendStatus(200)
  193. }
  194. })
  195. },
  196. expireDeletedProject(req, res, next) {
  197. const { projectId } = req.params
  198. ProjectDeleter.expireDeletedProject(projectId, err => {
  199. if (err != null) {
  200. next(err)
  201. } else {
  202. res.sendStatus(200)
  203. }
  204. })
  205. },
  206. restoreProject(req, res) {
  207. const projectId = req.params.Project_id
  208. ProjectDeleter.restoreProject(projectId, err => {
  209. if (err != null) {
  210. res.sendStatus(500)
  211. } else {
  212. res.sendStatus(200)
  213. }
  214. })
  215. },
  216. cloneProject(req, res, next) {
  217. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  218. metrics.inc('cloned-project')
  219. const projectId = req.params.Project_id
  220. const { projectName } = req.body
  221. logger.log({ projectId, projectName }, 'cloning project')
  222. if (!SessionManager.isUserLoggedIn(req.session)) {
  223. return res.send({ redir: '/register' })
  224. }
  225. const currentUser = SessionManager.getSessionUser(req.session)
  226. const { first_name: firstName, last_name: lastName, email } = currentUser
  227. ProjectDuplicator.duplicate(
  228. currentUser,
  229. projectId,
  230. projectName,
  231. (err, project) => {
  232. if (err != null) {
  233. OError.tag(err, 'error cloning project', {
  234. projectId,
  235. userId: currentUser._id,
  236. })
  237. return next(err)
  238. }
  239. res.send({
  240. name: project.name,
  241. project_id: project._id,
  242. owner_ref: project.owner_ref,
  243. owner: {
  244. first_name: firstName,
  245. last_name: lastName,
  246. email,
  247. _id: currentUser._id,
  248. },
  249. })
  250. }
  251. )
  252. },
  253. newProject(req, res, next) {
  254. const currentUser = SessionManager.getSessionUser(req.session)
  255. const {
  256. first_name: firstName,
  257. last_name: lastName,
  258. email,
  259. _id: userId,
  260. } = currentUser
  261. const projectName =
  262. req.body.projectName != null ? req.body.projectName.trim() : undefined
  263. const { template } = req.body
  264. async.waterfall(
  265. [
  266. cb => {
  267. if (template === 'example') {
  268. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  269. } else {
  270. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  271. }
  272. },
  273. ],
  274. (err, project) => {
  275. if (err != null) {
  276. return next(err)
  277. }
  278. res.send({
  279. project_id: project._id,
  280. owner_ref: project.owner_ref,
  281. owner: {
  282. first_name: firstName,
  283. last_name: lastName,
  284. email,
  285. _id: userId,
  286. },
  287. })
  288. }
  289. )
  290. },
  291. renameProject(req, res, next) {
  292. const projectId = req.params.Project_id
  293. const newName = req.body.newProjectName
  294. EditorController.renameProject(projectId, newName, err => {
  295. if (err != null) {
  296. return next(err)
  297. }
  298. res.sendStatus(200)
  299. })
  300. },
  301. userProjectsJson(req, res, next) {
  302. const userId = SessionManager.getLoggedInUserId(req.session)
  303. ProjectGetter.findAllUsersProjects(
  304. userId,
  305. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  306. (err, projects) => {
  307. if (err != null) {
  308. return next(err)
  309. }
  310. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  311. projects = ProjectController._buildProjectList(projects, userId)
  312. .filter(p => !(p.archived || p.trashed))
  313. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  314. res.json({ projects })
  315. }
  316. )
  317. },
  318. projectEntitiesJson(req, res, next) {
  319. const projectId = req.params.Project_id
  320. ProjectGetter.getProject(projectId, (err, project) => {
  321. if (err != null) {
  322. return next(err)
  323. }
  324. ProjectEntityHandler.getAllEntitiesFromProject(
  325. project,
  326. (err, docs, files) => {
  327. if (err != null) {
  328. return next(err)
  329. }
  330. const entities = docs
  331. .concat(files)
  332. // Sort by path ascending
  333. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  334. .map(e => ({
  335. path: e.path,
  336. type: e.doc != null ? 'doc' : 'file',
  337. }))
  338. res.json({ project_id: projectId, entities })
  339. }
  340. )
  341. })
  342. },
  343. projectListPage(req, res, next) {
  344. const timer = new metrics.Timer('project-list')
  345. const userId = SessionManager.getLoggedInUserId(req.session)
  346. const currentUser = SessionManager.getSessionUser(req.session)
  347. async.parallel(
  348. {
  349. tags(cb) {
  350. TagsHandler.getAllTags(userId, cb)
  351. },
  352. notifications(cb) {
  353. NotificationsHandler.getUserNotifications(userId, cb)
  354. },
  355. projects(cb) {
  356. ProjectGetter.findAllUsersProjects(
  357. userId,
  358. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  359. cb
  360. )
  361. },
  362. hasSubscription(cb) {
  363. LimitationsManager.hasPaidSubscription(
  364. currentUser,
  365. (error, hasPaidSubscription) => {
  366. if (error != null && error instanceof V1ConnectionError) {
  367. return cb(null, true)
  368. }
  369. cb(error, hasPaidSubscription)
  370. }
  371. )
  372. },
  373. user(cb) {
  374. User.findById(
  375. userId,
  376. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  377. cb
  378. )
  379. },
  380. userEmailsData(cb) {
  381. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  382. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  383. if (error && error instanceof V1ConnectionError) {
  384. return cb(null, result)
  385. }
  386. if (!Features.hasFeature('affiliations')) {
  387. result.list = fullEmails
  388. return cb(null, result)
  389. }
  390. Modules.hooks.fire(
  391. 'allInReconfirmNotificationPeriodsForUser',
  392. fullEmails,
  393. (error, results) => {
  394. if (error != null) {
  395. return cb(error)
  396. }
  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. let reconfirmedViaSAML
  440. if (Features.hasFeature('saml')) {
  441. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  442. const samlSession = req.session.saml
  443. // Notification: SSO Available
  444. const linkedInstitutionIds = []
  445. user.emails.forEach(email => {
  446. if (email.samlProviderId) {
  447. linkedInstitutionIds.push(email.samlProviderId)
  448. }
  449. })
  450. if (Array.isArray(userAffiliations)) {
  451. userAffiliations.forEach(affiliation => {
  452. if (
  453. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  454. ) {
  455. notificationsInstitution.push({
  456. email: affiliation.email,
  457. institutionId: affiliation.institution.id,
  458. institutionName: affiliation.institution.name,
  459. templateKey: 'notification_institution_sso_available',
  460. })
  461. }
  462. })
  463. }
  464. if (samlSession) {
  465. // Notification: After SSO Linked
  466. if (samlSession.linked) {
  467. notificationsInstitution.push({
  468. email: samlSession.institutionEmail,
  469. institutionName: samlSession.linked.universityName,
  470. templateKey: 'notification_institution_sso_linked',
  471. })
  472. }
  473. // Notification: After SSO Linked or Logging in
  474. // The requested email does not match primary email returned from
  475. // the institution
  476. if (
  477. samlSession.requestedEmail &&
  478. samlSession.emailNonCanonical &&
  479. !samlSession.error
  480. ) {
  481. notificationsInstitution.push({
  482. institutionEmail: samlSession.emailNonCanonical,
  483. requestedEmail: samlSession.requestedEmail,
  484. templateKey: 'notification_institution_sso_non_canonical',
  485. })
  486. }
  487. // Notification: Tried to register, but account already existed
  488. // registerIntercept is set before the institution callback.
  489. // institutionEmail is set after institution callback.
  490. // Check for both in case SSO flow was abandoned
  491. if (
  492. samlSession.registerIntercept &&
  493. samlSession.institutionEmail &&
  494. !samlSession.error
  495. ) {
  496. notificationsInstitution.push({
  497. email: samlSession.institutionEmail,
  498. templateKey: 'notification_institution_sso_already_registered',
  499. })
  500. }
  501. // Notification: When there is a session error
  502. if (samlSession.error) {
  503. notificationsInstitution.push({
  504. templateKey: 'notification_institution_sso_error',
  505. error: samlSession.error,
  506. })
  507. }
  508. }
  509. delete req.session.saml
  510. }
  511. const portalTemplates = ProjectController._buildPortalTemplatesList(
  512. userAffiliations
  513. )
  514. const projects = ProjectController._buildProjectList(
  515. results.projects,
  516. userId
  517. )
  518. // in v2 add notifications for matching university IPs
  519. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  520. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  521. req.ip,
  522. () => {}
  523. )
  524. }
  525. ProjectController._injectProjectUsers(projects, (error, projects) => {
  526. if (error != null) {
  527. return next(error)
  528. }
  529. const viewModel = {
  530. title: 'your_projects',
  531. priority_title: true,
  532. projects,
  533. tags,
  534. notifications: notifications || [],
  535. notificationsInstitution,
  536. allInReconfirmNotificationPeriods,
  537. portalTemplates,
  538. user,
  539. userAffiliations,
  540. userEmails,
  541. hasSubscription: results.hasSubscription,
  542. reconfirmedViaSAML,
  543. zipFileSizeLimit: Settings.maxUploadSize,
  544. isOverleaf: !!Settings.overleaf,
  545. }
  546. const paidUser =
  547. (user.features != null ? user.features.github : undefined) &&
  548. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  549. const freeUserProportion = 0.1
  550. const sampleFreeUser =
  551. parseInt(user._id.toString().slice(-2), 16) <
  552. freeUserProportion * 255
  553. const showFrontWidget = paidUser || sampleFreeUser
  554. if (showFrontWidget) {
  555. viewModel.frontChatWidgetRoomId =
  556. Settings.overleaf != null
  557. ? Settings.overleaf.front_chat_widget_room_id
  558. : undefined
  559. }
  560. res.render('project/list', viewModel)
  561. timer.done()
  562. })
  563. }
  564. )
  565. },
  566. loadEditor(req, res, next) {
  567. const timer = new metrics.Timer('load-editor')
  568. if (!Settings.editorIsOpen) {
  569. return res.render('general/closed', { title: 'updating_site' })
  570. }
  571. let anonymous, userId, sessionUser
  572. if (SessionManager.isUserLoggedIn(req.session)) {
  573. sessionUser = SessionManager.getSessionUser(req.session)
  574. userId = SessionManager.getLoggedInUserId(req.session)
  575. anonymous = false
  576. } else {
  577. sessionUser = null
  578. anonymous = true
  579. userId = null
  580. }
  581. const projectId = req.params.Project_id
  582. async.auto(
  583. {
  584. project(cb) {
  585. ProjectGetter.getProject(
  586. projectId,
  587. {
  588. name: 1,
  589. lastUpdated: 1,
  590. track_changes: 1,
  591. owner_ref: 1,
  592. brandVariationId: 1,
  593. overleaf: 1,
  594. tokens: 1,
  595. },
  596. (err, project) => {
  597. if (err != null) {
  598. return cb(err)
  599. }
  600. cb(null, project)
  601. }
  602. )
  603. },
  604. user(cb) {
  605. if (userId == null) {
  606. cb(null, defaultSettingsForAnonymousUser(userId))
  607. } else {
  608. User.findById(
  609. userId,
  610. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace',
  611. (err, user) => {
  612. // Handle case of deleted user
  613. if (user == null) {
  614. UserController.logout(req, res, next)
  615. return
  616. }
  617. if (err) {
  618. return cb(err)
  619. }
  620. logger.log({ projectId, userId }, 'got user')
  621. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  622. return cb(null, user)
  623. }
  624. ProjectController._refreshFeatures(req, user, cb)
  625. }
  626. )
  627. }
  628. },
  629. subscription(cb) {
  630. if (userId == null) {
  631. return cb()
  632. }
  633. SubscriptionLocator.getUsersSubscription(userId, cb)
  634. },
  635. activate(cb) {
  636. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  637. },
  638. markAsOpened(cb) {
  639. // don't need to wait for this to complete
  640. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  641. cb()
  642. },
  643. isTokenMember(cb) {
  644. if (userId == null) {
  645. return cb()
  646. }
  647. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  648. },
  649. brandVariation: [
  650. 'project',
  651. (cb, results) => {
  652. if (
  653. (results.project != null
  654. ? results.project.brandVariationId
  655. : undefined) == null
  656. ) {
  657. return cb()
  658. }
  659. BrandVariationsHandler.getBrandVariationById(
  660. results.project.brandVariationId,
  661. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  662. )
  663. },
  664. ],
  665. flushToTpds: cb => {
  666. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  667. },
  668. sharingModalSplitTest(cb) {
  669. SplitTestV2Handler.assignInLocalsContext(
  670. res,
  671. userId,
  672. 'project-share-modal-paywall',
  673. err => {
  674. cb(err, null)
  675. }
  676. )
  677. },
  678. },
  679. (err, { project, user, subscription, isTokenMember, brandVariation }) => {
  680. if (err != null) {
  681. OError.tag(err, 'error getting details for project page')
  682. return next(err)
  683. }
  684. const anonRequestToken = TokenAccessHandler.getRequestToken(
  685. req,
  686. projectId
  687. )
  688. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  689. sessionUser
  690. )
  691. AuthorizationManager.getPrivilegeLevelForProject(
  692. userId,
  693. projectId,
  694. anonRequestToken,
  695. (error, privilegeLevel) => {
  696. let allowedFreeTrial = true
  697. if (error != null) {
  698. return next(error)
  699. }
  700. if (
  701. privilegeLevel == null ||
  702. privilegeLevel === PrivilegeLevels.NONE
  703. ) {
  704. return res.sendStatus(401)
  705. }
  706. if (subscription != null) {
  707. allowedFreeTrial = false
  708. }
  709. let wsUrl = Settings.wsUrl
  710. let metricName = 'load-editor-ws'
  711. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  712. wsUrl = Settings.wsUrlBeta
  713. metricName += '-beta'
  714. } else if (
  715. Settings.wsUrlV2 &&
  716. Settings.wsUrlV2Percentage > 0 &&
  717. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  718. Settings.wsUrlV2Percentage
  719. ) {
  720. wsUrl = Settings.wsUrlV2
  721. metricName += '-v2'
  722. }
  723. if (req.query && req.query.ws === 'fallback') {
  724. // `?ws=fallback` will connect to the bare origin, and ignore
  725. // the custom wsUrl. Hence it must load the client side
  726. // javascript from there too.
  727. // Not resetting it here would possibly load a socket.io v2
  728. // client and connect to a v0 endpoint.
  729. wsUrl = undefined
  730. metricName += '-fallback'
  731. }
  732. metrics.inc(metricName)
  733. if (userId) {
  734. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  735. projectId: project._id,
  736. })
  737. }
  738. const logsUIVariant = getNewLogsUIVariantForUser(user)
  739. function shouldDisplayFeature(name, variantFlag) {
  740. if (req.query && req.query[name]) {
  741. return req.query[name] === 'true'
  742. } else {
  743. return variantFlag === true
  744. }
  745. }
  746. function partOfPdfCachingRollout(flag) {
  747. if (!Settings.enablePdfCaching) {
  748. // The feature is disabled globally.
  749. return false
  750. }
  751. // Let the user opt-in only.
  752. // The flag will opt-out of both caching and metrics collection,
  753. // as if this editing session never happened.
  754. return shouldDisplayFeature('enable_pdf_caching', false)
  755. }
  756. res.render('project/editor', {
  757. title: project.name,
  758. priority_title: true,
  759. bodyClasses: ['editor'],
  760. project_id: project._id,
  761. user: {
  762. id: userId,
  763. email: user.email,
  764. first_name: user.first_name,
  765. last_name: user.last_name,
  766. referal_id: user.referal_id,
  767. signUpDate: user.signUpDate,
  768. allowedFreeTrial: allowedFreeTrial,
  769. featureSwitches: user.featureSwitches,
  770. features: user.features,
  771. refProviders: _.mapValues(user.refProviders, Boolean),
  772. alphaProgram: user.alphaProgram,
  773. betaProgram: user.betaProgram,
  774. isAdmin: user.isAdmin,
  775. },
  776. userSettings: {
  777. mode: user.ace.mode,
  778. editorTheme: user.ace.theme,
  779. fontSize: user.ace.fontSize,
  780. autoComplete: user.ace.autoComplete,
  781. autoPairDelimiters: user.ace.autoPairDelimiters,
  782. pdfViewer: user.ace.pdfViewer,
  783. syntaxValidation: user.ace.syntaxValidation,
  784. fontFamily: user.ace.fontFamily || 'lucida',
  785. lineHeight: user.ace.lineHeight || 'normal',
  786. overallTheme: user.ace.overallTheme,
  787. },
  788. privilegeLevel,
  789. anonymous,
  790. anonymousAccessToken: anonymous ? anonRequestToken : null,
  791. isTokenMember,
  792. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  793. userId,
  794. privilegeLevel,
  795. isTokenMember
  796. ),
  797. languages: Settings.languages,
  798. editorThemes: THEME_LIST,
  799. maxDocLength: Settings.max_doc_length,
  800. useV2History:
  801. project.overleaf &&
  802. project.overleaf.history &&
  803. Boolean(project.overleaf.history.display),
  804. brandVariation,
  805. allowedImageNames,
  806. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  807. wsUrl,
  808. showSupport: Features.hasFeature('support'),
  809. showNewLogsUI: shouldDisplayFeature(
  810. 'new_logs_ui',
  811. logsUIVariant.newLogsUI
  812. ),
  813. logsUISubvariant: logsUIVariant.subvariant,
  814. showNewNavigationUI: shouldDisplayFeature(
  815. 'new_navigation_ui',
  816. true
  817. ),
  818. showNewPdfPreview: shouldDisplayFeature(
  819. 'new_pdf_preview',
  820. user.alphaProgram
  821. ),
  822. showSymbolPalette: shouldDisplayFeature(
  823. 'symbol_palette',
  824. user.alphaProgram || user.betaProgram
  825. ),
  826. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  827. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  828. resetServiceWorker:
  829. Boolean(Settings.resetServiceWorker) &&
  830. !shouldDisplayFeature('enable_pdf_caching', false),
  831. })
  832. timer.done()
  833. }
  834. )
  835. }
  836. )
  837. },
  838. _refreshFeatures(req, user, callback) {
  839. // If the feature refresh has failed in this session, don't retry
  840. // it - require the user to log in again.
  841. if (req.session.feature_refresh_failed) {
  842. metrics.inc('features-refresh', 1, {
  843. path: 'load-editor',
  844. status: 'skipped',
  845. })
  846. return callback(null, user)
  847. }
  848. // If the refresh takes too long then return the current
  849. // features. Note that the user.features property may still be
  850. // updated in the background after the callback is called.
  851. callback = _.once(callback)
  852. const refreshTimeoutHandler = setTimeout(() => {
  853. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  854. metrics.inc('features-refresh', 1, {
  855. path: 'load-editor',
  856. status: 'timeout',
  857. })
  858. callback(null, user)
  859. }, 5000)
  860. // try to refresh user features now
  861. const timer = new metrics.Timer('features-refresh-on-load-editor')
  862. FeaturesUpdater.refreshFeatures(
  863. user._id,
  864. 'load-editor',
  865. (err, features) => {
  866. clearTimeout(refreshTimeoutHandler)
  867. timer.done()
  868. if (err) {
  869. // keep a record to prevent unneceary retries and leave
  870. // the original features unmodified if the refresh failed
  871. req.session.feature_refresh_failed = {
  872. reason: 'error',
  873. at: new Date(),
  874. }
  875. metrics.inc('features-refresh', 1, {
  876. path: 'load-editor',
  877. status: 'error',
  878. })
  879. } else {
  880. user.features = features
  881. metrics.inc('features-refresh', 1, {
  882. path: 'load-editor',
  883. status: 'success',
  884. })
  885. }
  886. return callback(null, user)
  887. }
  888. )
  889. },
  890. _buildProjectList(allProjects, userId) {
  891. let project
  892. const {
  893. owned,
  894. readAndWrite,
  895. readOnly,
  896. tokenReadAndWrite,
  897. tokenReadOnly,
  898. } = allProjects
  899. const projects = []
  900. for (project of owned) {
  901. projects.push(
  902. ProjectController._buildProjectViewModel(
  903. project,
  904. 'owner',
  905. Sources.OWNER,
  906. userId
  907. )
  908. )
  909. }
  910. // Invite-access
  911. for (project of readAndWrite) {
  912. projects.push(
  913. ProjectController._buildProjectViewModel(
  914. project,
  915. 'readWrite',
  916. Sources.INVITE,
  917. userId
  918. )
  919. )
  920. }
  921. for (project of readOnly) {
  922. projects.push(
  923. ProjectController._buildProjectViewModel(
  924. project,
  925. 'readOnly',
  926. Sources.INVITE,
  927. userId
  928. )
  929. )
  930. }
  931. // Token-access
  932. // Only add these projects if they're not already present, this gives us cascading access
  933. // from 'owner' => 'token-read-only'
  934. for (project of tokenReadAndWrite) {
  935. if (
  936. projects.filter(p => p.id.toString() === project._id.toString())
  937. .length === 0
  938. ) {
  939. projects.push(
  940. ProjectController._buildProjectViewModel(
  941. project,
  942. 'readAndWrite',
  943. Sources.TOKEN,
  944. userId
  945. )
  946. )
  947. }
  948. }
  949. for (project of tokenReadOnly) {
  950. if (
  951. projects.filter(p => p.id.toString() === project._id.toString())
  952. .length === 0
  953. ) {
  954. projects.push(
  955. ProjectController._buildProjectViewModel(
  956. project,
  957. 'readOnly',
  958. Sources.TOKEN,
  959. userId
  960. )
  961. )
  962. }
  963. }
  964. return projects
  965. },
  966. _buildProjectViewModel(project, accessLevel, source, userId) {
  967. const archived = ProjectHelper.isArchived(project, userId)
  968. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  969. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  970. TokenAccessHandler.protectTokens(project, accessLevel)
  971. const model = {
  972. id: project._id,
  973. name: project.name,
  974. lastUpdated: project.lastUpdated,
  975. lastUpdatedBy: project.lastUpdatedBy,
  976. publicAccessLevel: project.publicAccesLevel,
  977. accessLevel,
  978. source,
  979. archived,
  980. trashed,
  981. owner_ref: project.owner_ref,
  982. isV1Project: false,
  983. }
  984. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  985. model.owner_ref = null
  986. model.lastUpdatedBy = null
  987. }
  988. return model
  989. },
  990. _injectProjectUsers(projects, callback) {
  991. const users = {}
  992. for (const project of projects) {
  993. if (project.owner_ref != null) {
  994. users[project.owner_ref.toString()] = true
  995. }
  996. if (project.lastUpdatedBy != null) {
  997. users[project.lastUpdatedBy.toString()] = true
  998. }
  999. }
  1000. const userIds = Object.keys(users)
  1001. async.eachSeries(
  1002. userIds,
  1003. (userId, cb) => {
  1004. UserGetter.getUser(
  1005. userId,
  1006. { first_name: 1, last_name: 1, email: 1 },
  1007. (error, user) => {
  1008. if (error != null) {
  1009. return cb(error)
  1010. }
  1011. users[userId] = user
  1012. cb()
  1013. }
  1014. )
  1015. },
  1016. error => {
  1017. if (error != null) {
  1018. return callback(error)
  1019. }
  1020. for (const project of projects) {
  1021. if (project.owner_ref != null) {
  1022. project.owner = users[project.owner_ref.toString()]
  1023. }
  1024. if (project.lastUpdatedBy != null) {
  1025. project.lastUpdatedBy =
  1026. users[project.lastUpdatedBy.toString()] || null
  1027. }
  1028. }
  1029. callback(null, projects)
  1030. }
  1031. )
  1032. },
  1033. _buildPortalTemplatesList(affiliations) {
  1034. if (affiliations == null) {
  1035. affiliations = []
  1036. }
  1037. const portalTemplates = []
  1038. for (const aff of affiliations) {
  1039. if (
  1040. aff.portal &&
  1041. aff.portal.slug &&
  1042. aff.portal.templates_count &&
  1043. aff.portal.templates_count > 0
  1044. ) {
  1045. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1046. portalTemplates.push({
  1047. name: aff.institution.name,
  1048. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1049. })
  1050. }
  1051. }
  1052. return portalTemplates
  1053. },
  1054. }
  1055. const defaultSettingsForAnonymousUser = userId => ({
  1056. id: userId,
  1057. ace: {
  1058. mode: 'none',
  1059. theme: 'textmate',
  1060. fontSize: '12',
  1061. autoComplete: true,
  1062. spellCheckLanguage: '',
  1063. pdfViewer: '',
  1064. syntaxValidation: true,
  1065. },
  1066. subscription: {
  1067. freeTrial: {
  1068. allowed: true,
  1069. },
  1070. },
  1071. featureSwitches: {
  1072. github: false,
  1073. },
  1074. alphaProgram: false,
  1075. betaProgram: false,
  1076. })
  1077. const THEME_LIST = []
  1078. function generateThemeList() {
  1079. const files = fs.readdirSync(
  1080. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1081. )
  1082. const result = []
  1083. for (const file of files) {
  1084. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1085. const cleanName = file.slice(0, -3).slice(6)
  1086. result.push(THEME_LIST.push(cleanName))
  1087. } else {
  1088. result.push(undefined)
  1089. }
  1090. }
  1091. }
  1092. generateThemeList()
  1093. module.exports = ProjectController