ProjectController.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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(req.ip)
  521. }
  522. ProjectController._injectProjectUsers(projects, (error, projects) => {
  523. if (error != null) {
  524. return next(error)
  525. }
  526. const viewModel = {
  527. title: 'your_projects',
  528. priority_title: true,
  529. projects,
  530. tags,
  531. notifications: notifications || [],
  532. notificationsInstitution,
  533. allInReconfirmNotificationPeriods,
  534. portalTemplates,
  535. user,
  536. userAffiliations,
  537. userEmails,
  538. hasSubscription: results.hasSubscription,
  539. reconfirmedViaSAML,
  540. zipFileSizeLimit: Settings.maxUploadSize,
  541. isOverleaf: !!Settings.overleaf,
  542. }
  543. const paidUser =
  544. (user.features != null ? user.features.github : undefined) &&
  545. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  546. const freeUserProportion = 0.1
  547. const sampleFreeUser =
  548. parseInt(user._id.toString().slice(-2), 16) <
  549. freeUserProportion * 255
  550. const showFrontWidget = paidUser || sampleFreeUser
  551. if (showFrontWidget) {
  552. viewModel.frontChatWidgetRoomId =
  553. Settings.overleaf != null
  554. ? Settings.overleaf.front_chat_widget_room_id
  555. : undefined
  556. }
  557. res.render('project/list', viewModel)
  558. timer.done()
  559. })
  560. }
  561. )
  562. },
  563. loadEditor(req, res, next) {
  564. const timer = new metrics.Timer('load-editor')
  565. if (!Settings.editorIsOpen) {
  566. return res.render('general/closed', { title: 'updating_site' })
  567. }
  568. let anonymous, userId, sessionUser
  569. if (SessionManager.isUserLoggedIn(req.session)) {
  570. sessionUser = SessionManager.getSessionUser(req.session)
  571. userId = SessionManager.getLoggedInUserId(req.session)
  572. anonymous = false
  573. } else {
  574. sessionUser = null
  575. anonymous = true
  576. userId = null
  577. }
  578. const projectId = req.params.Project_id
  579. async.auto(
  580. {
  581. project(cb) {
  582. ProjectGetter.getProject(
  583. projectId,
  584. {
  585. name: 1,
  586. lastUpdated: 1,
  587. track_changes: 1,
  588. owner_ref: 1,
  589. brandVariationId: 1,
  590. overleaf: 1,
  591. tokens: 1,
  592. },
  593. (err, project) => {
  594. if (err != null) {
  595. return cb(err)
  596. }
  597. cb(null, project)
  598. }
  599. )
  600. },
  601. user(cb) {
  602. if (userId == null) {
  603. cb(null, defaultSettingsForAnonymousUser(userId))
  604. } else {
  605. User.findById(
  606. userId,
  607. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace',
  608. (err, user) => {
  609. // Handle case of deleted user
  610. if (user == null) {
  611. UserController.logout(req, res, next)
  612. return
  613. }
  614. if (err) {
  615. return cb(err)
  616. }
  617. logger.log({ projectId, userId }, 'got user')
  618. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  619. return cb(null, user)
  620. }
  621. ProjectController._refreshFeatures(req, user, cb)
  622. }
  623. )
  624. }
  625. },
  626. subscription(cb) {
  627. if (userId == null) {
  628. return cb()
  629. }
  630. SubscriptionLocator.getUsersSubscription(userId, cb)
  631. },
  632. activate(cb) {
  633. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  634. },
  635. markAsOpened(cb) {
  636. // don't need to wait for this to complete
  637. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  638. cb()
  639. },
  640. isTokenMember(cb) {
  641. if (userId == null) {
  642. return cb()
  643. }
  644. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  645. },
  646. brandVariation: [
  647. 'project',
  648. (cb, results) => {
  649. if (
  650. (results.project != null
  651. ? results.project.brandVariationId
  652. : undefined) == null
  653. ) {
  654. return cb()
  655. }
  656. BrandVariationsHandler.getBrandVariationById(
  657. results.project.brandVariationId,
  658. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  659. )
  660. },
  661. ],
  662. flushToTpds: cb => {
  663. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  664. },
  665. sharingModalSplitTest(cb) {
  666. SplitTestV2Handler.assignInLocalsContext(
  667. res,
  668. userId,
  669. 'project-share-modal-paywall',
  670. err => {
  671. cb(err, null)
  672. }
  673. )
  674. },
  675. },
  676. (err, { project, user, subscription, isTokenMember, brandVariation }) => {
  677. if (err != null) {
  678. OError.tag(err, 'error getting details for project page')
  679. return next(err)
  680. }
  681. const anonRequestToken = TokenAccessHandler.getRequestToken(
  682. req,
  683. projectId
  684. )
  685. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  686. sessionUser
  687. )
  688. AuthorizationManager.getPrivilegeLevelForProject(
  689. userId,
  690. projectId,
  691. anonRequestToken,
  692. (error, privilegeLevel) => {
  693. let allowedFreeTrial = true
  694. if (error != null) {
  695. return next(error)
  696. }
  697. if (
  698. privilegeLevel == null ||
  699. privilegeLevel === PrivilegeLevels.NONE
  700. ) {
  701. return res.sendStatus(401)
  702. }
  703. if (subscription != null) {
  704. allowedFreeTrial = false
  705. }
  706. let wsUrl = Settings.wsUrl
  707. let metricName = 'load-editor-ws'
  708. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  709. wsUrl = Settings.wsUrlBeta
  710. metricName += '-beta'
  711. } else if (
  712. Settings.wsUrlV2 &&
  713. Settings.wsUrlV2Percentage > 0 &&
  714. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  715. Settings.wsUrlV2Percentage
  716. ) {
  717. wsUrl = Settings.wsUrlV2
  718. metricName += '-v2'
  719. }
  720. if (req.query && req.query.ws === 'fallback') {
  721. // `?ws=fallback` will connect to the bare origin, and ignore
  722. // the custom wsUrl. Hence it must load the client side
  723. // javascript from there too.
  724. // Not resetting it here would possibly load a socket.io v2
  725. // client and connect to a v0 endpoint.
  726. wsUrl = undefined
  727. metricName += '-fallback'
  728. }
  729. metrics.inc(metricName)
  730. if (userId) {
  731. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  732. projectId: project._id,
  733. })
  734. }
  735. const logsUIVariant = getNewLogsUIVariantForUser(user)
  736. function shouldDisplayFeature(name, variantFlag) {
  737. if (req.query && req.query[name]) {
  738. return req.query[name] === 'true'
  739. } else {
  740. return variantFlag === true
  741. }
  742. }
  743. function partOfPdfCachingRollout(flag) {
  744. if (!Settings.enablePdfCaching) {
  745. // The feature is disabled globally.
  746. return false
  747. }
  748. // Let the user opt-in only.
  749. // The flag will opt-out of both caching and metrics collection,
  750. // as if this editing session never happened.
  751. return shouldDisplayFeature('enable_pdf_caching', false)
  752. }
  753. res.render('project/editor', {
  754. title: project.name,
  755. priority_title: true,
  756. bodyClasses: ['editor'],
  757. project_id: project._id,
  758. user: {
  759. id: userId,
  760. email: user.email,
  761. first_name: user.first_name,
  762. last_name: user.last_name,
  763. referal_id: user.referal_id,
  764. signUpDate: user.signUpDate,
  765. allowedFreeTrial: allowedFreeTrial,
  766. featureSwitches: user.featureSwitches,
  767. features: user.features,
  768. refProviders: _.mapValues(user.refProviders, Boolean),
  769. alphaProgram: user.alphaProgram,
  770. betaProgram: user.betaProgram,
  771. isAdmin: user.isAdmin,
  772. },
  773. userSettings: {
  774. mode: user.ace.mode,
  775. editorTheme: user.ace.theme,
  776. fontSize: user.ace.fontSize,
  777. autoComplete: user.ace.autoComplete,
  778. autoPairDelimiters: user.ace.autoPairDelimiters,
  779. pdfViewer: user.ace.pdfViewer,
  780. syntaxValidation: user.ace.syntaxValidation,
  781. fontFamily: user.ace.fontFamily || 'lucida',
  782. lineHeight: user.ace.lineHeight || 'normal',
  783. overallTheme: user.ace.overallTheme,
  784. },
  785. privilegeLevel,
  786. anonymous,
  787. anonymousAccessToken: anonymous ? anonRequestToken : null,
  788. isTokenMember,
  789. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  790. userId,
  791. privilegeLevel,
  792. isTokenMember
  793. ),
  794. languages: Settings.languages,
  795. editorThemes: THEME_LIST,
  796. maxDocLength: Settings.max_doc_length,
  797. useV2History:
  798. project.overleaf &&
  799. project.overleaf.history &&
  800. Boolean(project.overleaf.history.display),
  801. brandVariation,
  802. allowedImageNames,
  803. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  804. wsUrl,
  805. showSupport: Features.hasFeature('support'),
  806. showNewLogsUI: shouldDisplayFeature(
  807. 'new_logs_ui',
  808. logsUIVariant.newLogsUI
  809. ),
  810. logsUISubvariant: logsUIVariant.subvariant,
  811. showNewNavigationUI: shouldDisplayFeature(
  812. 'new_navigation_ui',
  813. true
  814. ),
  815. showNewPdfPreview: shouldDisplayFeature(
  816. 'new_pdf_preview',
  817. user.alphaProgram
  818. ),
  819. showSymbolPalette: shouldDisplayFeature(
  820. 'symbol_palette',
  821. user.alphaProgram || user.betaProgram
  822. ),
  823. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  824. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  825. resetServiceWorker:
  826. Boolean(Settings.resetServiceWorker) &&
  827. !shouldDisplayFeature('enable_pdf_caching', false),
  828. })
  829. timer.done()
  830. }
  831. )
  832. }
  833. )
  834. },
  835. _refreshFeatures(req, user, callback) {
  836. // If the feature refresh has failed in this session, don't retry
  837. // it - require the user to log in again.
  838. if (req.session.feature_refresh_failed) {
  839. metrics.inc('features-refresh', 1, {
  840. path: 'load-editor',
  841. status: 'skipped',
  842. })
  843. return callback(null, user)
  844. }
  845. // If the refresh takes too long then return the current
  846. // features. Note that the user.features property may still be
  847. // updated in the background after the callback is called.
  848. callback = _.once(callback)
  849. const refreshTimeoutHandler = setTimeout(() => {
  850. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  851. metrics.inc('features-refresh', 1, {
  852. path: 'load-editor',
  853. status: 'timeout',
  854. })
  855. callback(null, user)
  856. }, 5000)
  857. // try to refresh user features now
  858. const timer = new metrics.Timer('features-refresh-on-load-editor')
  859. FeaturesUpdater.refreshFeatures(
  860. user._id,
  861. 'load-editor',
  862. (err, features) => {
  863. clearTimeout(refreshTimeoutHandler)
  864. timer.done()
  865. if (err) {
  866. // keep a record to prevent unneceary retries and leave
  867. // the original features unmodified if the refresh failed
  868. req.session.feature_refresh_failed = {
  869. reason: 'error',
  870. at: new Date(),
  871. }
  872. metrics.inc('features-refresh', 1, {
  873. path: 'load-editor',
  874. status: 'error',
  875. })
  876. } else {
  877. user.features = features
  878. metrics.inc('features-refresh', 1, {
  879. path: 'load-editor',
  880. status: 'success',
  881. })
  882. }
  883. return callback(null, user)
  884. }
  885. )
  886. },
  887. _buildProjectList(allProjects, userId) {
  888. let project
  889. const {
  890. owned,
  891. readAndWrite,
  892. readOnly,
  893. tokenReadAndWrite,
  894. tokenReadOnly,
  895. } = allProjects
  896. const projects = []
  897. for (project of owned) {
  898. projects.push(
  899. ProjectController._buildProjectViewModel(
  900. project,
  901. 'owner',
  902. Sources.OWNER,
  903. userId
  904. )
  905. )
  906. }
  907. // Invite-access
  908. for (project of readAndWrite) {
  909. projects.push(
  910. ProjectController._buildProjectViewModel(
  911. project,
  912. 'readWrite',
  913. Sources.INVITE,
  914. userId
  915. )
  916. )
  917. }
  918. for (project of readOnly) {
  919. projects.push(
  920. ProjectController._buildProjectViewModel(
  921. project,
  922. 'readOnly',
  923. Sources.INVITE,
  924. userId
  925. )
  926. )
  927. }
  928. // Token-access
  929. // Only add these projects if they're not already present, this gives us cascading access
  930. // from 'owner' => 'token-read-only'
  931. for (project of tokenReadAndWrite) {
  932. if (
  933. projects.filter(p => p.id.toString() === project._id.toString())
  934. .length === 0
  935. ) {
  936. projects.push(
  937. ProjectController._buildProjectViewModel(
  938. project,
  939. 'readAndWrite',
  940. Sources.TOKEN,
  941. userId
  942. )
  943. )
  944. }
  945. }
  946. for (project of tokenReadOnly) {
  947. if (
  948. projects.filter(p => p.id.toString() === project._id.toString())
  949. .length === 0
  950. ) {
  951. projects.push(
  952. ProjectController._buildProjectViewModel(
  953. project,
  954. 'readOnly',
  955. Sources.TOKEN,
  956. userId
  957. )
  958. )
  959. }
  960. }
  961. return projects
  962. },
  963. _buildProjectViewModel(project, accessLevel, source, userId) {
  964. const archived = ProjectHelper.isArchived(project, userId)
  965. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  966. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  967. TokenAccessHandler.protectTokens(project, accessLevel)
  968. const model = {
  969. id: project._id,
  970. name: project.name,
  971. lastUpdated: project.lastUpdated,
  972. lastUpdatedBy: project.lastUpdatedBy,
  973. publicAccessLevel: project.publicAccesLevel,
  974. accessLevel,
  975. source,
  976. archived,
  977. trashed,
  978. owner_ref: project.owner_ref,
  979. isV1Project: false,
  980. }
  981. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  982. model.owner_ref = null
  983. model.lastUpdatedBy = null
  984. }
  985. return model
  986. },
  987. _injectProjectUsers(projects, callback) {
  988. const users = {}
  989. for (const project of projects) {
  990. if (project.owner_ref != null) {
  991. users[project.owner_ref.toString()] = true
  992. }
  993. if (project.lastUpdatedBy != null) {
  994. users[project.lastUpdatedBy.toString()] = true
  995. }
  996. }
  997. const userIds = Object.keys(users)
  998. async.eachSeries(
  999. userIds,
  1000. (userId, cb) => {
  1001. UserGetter.getUser(
  1002. userId,
  1003. { first_name: 1, last_name: 1, email: 1 },
  1004. (error, user) => {
  1005. if (error != null) {
  1006. return cb(error)
  1007. }
  1008. users[userId] = user
  1009. cb()
  1010. }
  1011. )
  1012. },
  1013. error => {
  1014. if (error != null) {
  1015. return callback(error)
  1016. }
  1017. for (const project of projects) {
  1018. if (project.owner_ref != null) {
  1019. project.owner = users[project.owner_ref.toString()]
  1020. }
  1021. if (project.lastUpdatedBy != null) {
  1022. project.lastUpdatedBy =
  1023. users[project.lastUpdatedBy.toString()] || null
  1024. }
  1025. }
  1026. callback(null, projects)
  1027. }
  1028. )
  1029. },
  1030. _buildPortalTemplatesList(affiliations) {
  1031. if (affiliations == null) {
  1032. affiliations = []
  1033. }
  1034. const portalTemplates = []
  1035. for (const aff of affiliations) {
  1036. if (
  1037. aff.portal &&
  1038. aff.portal.slug &&
  1039. aff.portal.templates_count &&
  1040. aff.portal.templates_count > 0
  1041. ) {
  1042. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1043. portalTemplates.push({
  1044. name: aff.institution.name,
  1045. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1046. })
  1047. }
  1048. }
  1049. return portalTemplates
  1050. },
  1051. }
  1052. const defaultSettingsForAnonymousUser = userId => ({
  1053. id: userId,
  1054. ace: {
  1055. mode: 'none',
  1056. theme: 'textmate',
  1057. fontSize: '12',
  1058. autoComplete: true,
  1059. spellCheckLanguage: '',
  1060. pdfViewer: '',
  1061. syntaxValidation: true,
  1062. },
  1063. subscription: {
  1064. freeTrial: {
  1065. allowed: true,
  1066. },
  1067. },
  1068. featureSwitches: {
  1069. github: false,
  1070. },
  1071. alphaProgram: false,
  1072. betaProgram: false,
  1073. })
  1074. const THEME_LIST = []
  1075. function generateThemeList() {
  1076. const files = fs.readdirSync(
  1077. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1078. )
  1079. const result = []
  1080. for (const file of files) {
  1081. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1082. const cleanName = file.slice(0, -3).slice(6)
  1083. result.push(THEME_LIST.push(cleanName))
  1084. } else {
  1085. result.push(undefined)
  1086. }
  1087. }
  1088. }
  1089. generateThemeList()
  1090. module.exports = ProjectController