ProjectController.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. const _ = require('lodash')
  2. const Path = require('path')
  3. const OError = require('@overleaf/o-error')
  4. const fs = require('fs')
  5. const crypto = require('crypto')
  6. const async = require('async')
  7. const logger = require('logger-sharelatex')
  8. const { ObjectId } = require('mongodb')
  9. const ProjectDeleter = require('./ProjectDeleter')
  10. const ProjectDuplicator = require('./ProjectDuplicator')
  11. const ProjectCreationHandler = require('./ProjectCreationHandler')
  12. const EditorController = require('../Editor/EditorController')
  13. const ProjectHelper = require('./ProjectHelper')
  14. const metrics = require('@overleaf/metrics')
  15. const { User } = require('../../models/User')
  16. const TagsHandler = require('../Tags/TagsHandler')
  17. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  18. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  19. const LimitationsManager = require('../Subscription/LimitationsManager')
  20. const Settings = require('settings-sharelatex')
  21. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  22. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  23. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  24. const ProjectGetter = require('./ProjectGetter')
  25. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  26. const AuthenticationController = require('../Authentication/AuthenticationController')
  27. const Sources = require('../Authorization/Sources')
  28. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  29. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  30. const ProjectEntityHandler = require('./ProjectEntityHandler')
  31. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  32. const UserGetter = require('../User/UserGetter')
  33. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  34. const { V1ConnectionError } = require('../Errors/Errors')
  35. const Features = require('../../infrastructure/Features')
  36. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  37. const UserController = require('../User/UserController')
  38. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  39. const Modules = require('../../infrastructure/Modules')
  40. const 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 = AuthenticationController.getSessionUser(req)
  129. const cb = err => {
  130. if (err != null) {
  131. res.sendStatus(500)
  132. } else {
  133. res.sendStatus(200)
  134. }
  135. }
  136. ProjectDeleter.deleteProject(
  137. projectId,
  138. { deleterUser: user, ipAddress: req.ip },
  139. cb
  140. )
  141. },
  142. archiveProject(req, res, next) {
  143. const projectId = req.params.Project_id
  144. const userId = AuthenticationController.getLoggedInUserId(req)
  145. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  146. if (err != null) {
  147. return next(err)
  148. } else {
  149. return res.sendStatus(200)
  150. }
  151. })
  152. },
  153. unarchiveProject(req, res, next) {
  154. const projectId = req.params.Project_id
  155. const userId = AuthenticationController.getLoggedInUserId(req)
  156. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  157. if (err != null) {
  158. return next(err)
  159. } else {
  160. return res.sendStatus(200)
  161. }
  162. })
  163. },
  164. trashProject(req, res, next) {
  165. const projectId = req.params.project_id
  166. const userId = AuthenticationController.getLoggedInUserId(req)
  167. ProjectDeleter.trashProject(projectId, userId, function (err) {
  168. if (err != null) {
  169. return next(err)
  170. } else {
  171. return res.sendStatus(200)
  172. }
  173. })
  174. },
  175. untrashProject(req, res, next) {
  176. const projectId = req.params.project_id
  177. const userId = AuthenticationController.getLoggedInUserId(req)
  178. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  179. if (err != null) {
  180. return next(err)
  181. } else {
  182. return res.sendStatus(200)
  183. }
  184. })
  185. },
  186. expireDeletedProjectsAfterDuration(req, res) {
  187. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  188. if (err != null) {
  189. res.sendStatus(500)
  190. } else {
  191. res.sendStatus(200)
  192. }
  193. })
  194. },
  195. expireDeletedProject(req, res, next) {
  196. const { projectId } = req.params
  197. ProjectDeleter.expireDeletedProject(projectId, err => {
  198. if (err != null) {
  199. next(err)
  200. } else {
  201. res.sendStatus(200)
  202. }
  203. })
  204. },
  205. restoreProject(req, res) {
  206. const projectId = req.params.Project_id
  207. ProjectDeleter.restoreProject(projectId, err => {
  208. if (err != null) {
  209. res.sendStatus(500)
  210. } else {
  211. res.sendStatus(200)
  212. }
  213. })
  214. },
  215. cloneProject(req, res, next) {
  216. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  217. metrics.inc('cloned-project')
  218. const projectId = req.params.Project_id
  219. const { projectName } = req.body
  220. logger.log({ projectId, projectName }, 'cloning project')
  221. if (!AuthenticationController.isUserLoggedIn(req)) {
  222. return res.send({ redir: '/register' })
  223. }
  224. const currentUser = AuthenticationController.getSessionUser(req)
  225. const { first_name: firstName, last_name: lastName, email } = currentUser
  226. ProjectDuplicator.duplicate(
  227. currentUser,
  228. projectId,
  229. projectName,
  230. (err, project) => {
  231. if (err != null) {
  232. OError.tag(err, 'error cloning project', {
  233. projectId,
  234. userId: currentUser._id,
  235. })
  236. return next(err)
  237. }
  238. res.send({
  239. name: project.name,
  240. project_id: project._id,
  241. owner_ref: project.owner_ref,
  242. owner: {
  243. first_name: firstName,
  244. last_name: lastName,
  245. email,
  246. _id: currentUser._id,
  247. },
  248. })
  249. }
  250. )
  251. },
  252. newProject(req, res, next) {
  253. const currentUser = AuthenticationController.getSessionUser(req)
  254. const {
  255. first_name: firstName,
  256. last_name: lastName,
  257. email,
  258. _id: userId,
  259. } = currentUser
  260. const projectName =
  261. req.body.projectName != null ? req.body.projectName.trim() : undefined
  262. const { template } = req.body
  263. async.waterfall(
  264. [
  265. cb => {
  266. if (template === 'example') {
  267. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  268. } else {
  269. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  270. }
  271. },
  272. ],
  273. (err, project) => {
  274. if (err != null) {
  275. return next(err)
  276. }
  277. res.send({
  278. project_id: project._id,
  279. owner_ref: project.owner_ref,
  280. owner: {
  281. first_name: firstName,
  282. last_name: lastName,
  283. email,
  284. _id: userId,
  285. },
  286. })
  287. }
  288. )
  289. },
  290. renameProject(req, res, next) {
  291. const projectId = req.params.Project_id
  292. const newName = req.body.newProjectName
  293. EditorController.renameProject(projectId, newName, err => {
  294. if (err != null) {
  295. return next(err)
  296. }
  297. res.sendStatus(200)
  298. })
  299. },
  300. userProjectsJson(req, res, next) {
  301. const userId = AuthenticationController.getLoggedInUserId(req)
  302. ProjectGetter.findAllUsersProjects(
  303. userId,
  304. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  305. (err, projects) => {
  306. if (err != null) {
  307. return next(err)
  308. }
  309. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  310. projects = ProjectController._buildProjectList(projects, userId)
  311. .filter(p => !(p.archived || p.trashed))
  312. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  313. res.json({ projects })
  314. }
  315. )
  316. },
  317. projectEntitiesJson(req, res, next) {
  318. const projectId = req.params.Project_id
  319. ProjectGetter.getProject(projectId, (err, project) => {
  320. if (err != null) {
  321. return next(err)
  322. }
  323. ProjectEntityHandler.getAllEntitiesFromProject(
  324. project,
  325. (err, docs, files) => {
  326. if (err != null) {
  327. return next(err)
  328. }
  329. const entities = docs
  330. .concat(files)
  331. // Sort by path ascending
  332. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  333. .map(e => ({
  334. path: e.path,
  335. type: e.doc != null ? 'doc' : 'file',
  336. }))
  337. res.json({ project_id: projectId, entities })
  338. }
  339. )
  340. })
  341. },
  342. projectListPage(req, res, next) {
  343. const timer = new metrics.Timer('project-list')
  344. const userId = AuthenticationController.getLoggedInUserId(req)
  345. const currentUser = AuthenticationController.getSessionUser(req)
  346. 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 (AuthenticationController.isUserLoggedIn(req)) {
  566. sessionUser = AuthenticationController.getSessionUser(req)
  567. userId = AuthenticationController.getLoggedInUserId(req)
  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. },
  656. (err, results) => {
  657. if (err != null) {
  658. OError.tag(err, 'error getting details for project page')
  659. return next(err)
  660. }
  661. const { project } = results
  662. const { user } = results
  663. const { subscription } = results
  664. const { brandVariation } = results
  665. const anonRequestToken = TokenAccessHandler.getRequestToken(
  666. req,
  667. projectId
  668. )
  669. const { isTokenMember } = results
  670. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  671. sessionUser
  672. )
  673. AuthorizationManager.getPrivilegeLevelForProject(
  674. userId,
  675. projectId,
  676. anonRequestToken,
  677. (error, privilegeLevel) => {
  678. let allowedFreeTrial = true
  679. if (error != null) {
  680. return next(error)
  681. }
  682. if (
  683. privilegeLevel == null ||
  684. privilegeLevel === PrivilegeLevels.NONE
  685. ) {
  686. return res.sendStatus(401)
  687. }
  688. if (subscription != null) {
  689. allowedFreeTrial = false
  690. }
  691. let wsUrl = Settings.wsUrl
  692. let metricName = 'load-editor-ws'
  693. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  694. wsUrl = Settings.wsUrlBeta
  695. metricName += '-beta'
  696. } else if (
  697. Settings.wsUrlV2 &&
  698. Settings.wsUrlV2Percentage > 0 &&
  699. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  700. Settings.wsUrlV2Percentage
  701. ) {
  702. wsUrl = Settings.wsUrlV2
  703. metricName += '-v2'
  704. }
  705. if (req.query && req.query.ws === 'fallback') {
  706. // `?ws=fallback` will connect to the bare origin, and ignore
  707. // the custom wsUrl. Hence it must load the client side
  708. // javascript from there too.
  709. // Not resetting it here would possibly load a socket.io v2
  710. // client and connect to a v0 endpoint.
  711. wsUrl = undefined
  712. metricName += '-fallback'
  713. }
  714. metrics.inc(metricName)
  715. if (userId) {
  716. AnalyticsManager.recordEvent(userId, 'project-opened', {
  717. projectId: project._id,
  718. })
  719. }
  720. const logsUIVariant = getNewLogsUIVariantForUser(user)
  721. function shouldDisplayFeature(name, variantFlag) {
  722. if (req.query && req.query[name]) {
  723. return req.query[name] === 'true'
  724. } else {
  725. return variantFlag === true
  726. }
  727. }
  728. let trackPdfDownload = false
  729. let enablePdfCaching = false
  730. const render = () => {
  731. res.render('project/editor', {
  732. title: project.name,
  733. priority_title: true,
  734. bodyClasses: ['editor'],
  735. project_id: project._id,
  736. user: {
  737. id: userId,
  738. email: user.email,
  739. first_name: user.first_name,
  740. last_name: user.last_name,
  741. referal_id: user.referal_id,
  742. signUpDate: user.signUpDate,
  743. allowedFreeTrial: allowedFreeTrial,
  744. featureSwitches: user.featureSwitches,
  745. features: user.features,
  746. refProviders: _.mapValues(user.refProviders, Boolean),
  747. alphaProgram: user.alphaProgram,
  748. betaProgram: user.betaProgram,
  749. isAdmin: user.isAdmin,
  750. },
  751. userSettings: {
  752. mode: user.ace.mode,
  753. editorTheme: user.ace.theme,
  754. fontSize: user.ace.fontSize,
  755. autoComplete: user.ace.autoComplete,
  756. autoPairDelimiters: user.ace.autoPairDelimiters,
  757. pdfViewer: user.ace.pdfViewer,
  758. syntaxValidation: user.ace.syntaxValidation,
  759. fontFamily: user.ace.fontFamily || 'lucida',
  760. lineHeight: user.ace.lineHeight || 'normal',
  761. overallTheme: user.ace.overallTheme,
  762. },
  763. privilegeLevel,
  764. chatUrl: Settings.apis.chat.url,
  765. anonymous,
  766. anonymousAccessToken: anonymous ? anonRequestToken : null,
  767. isTokenMember,
  768. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  769. userId,
  770. privilegeLevel,
  771. isTokenMember
  772. ),
  773. languages: Settings.languages,
  774. editorThemes: THEME_LIST,
  775. maxDocLength: Settings.max_doc_length,
  776. useV2History:
  777. project.overleaf &&
  778. project.overleaf.history &&
  779. Boolean(project.overleaf.history.display),
  780. brandVariation,
  781. allowedImageNames,
  782. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  783. wsUrl,
  784. showSupport: Features.hasFeature('support'),
  785. showNewLogsUI: shouldDisplayFeature(
  786. 'new_logs_ui',
  787. logsUIVariant.newLogsUI
  788. ),
  789. logsUISubvariant: logsUIVariant.subvariant,
  790. showNewNavigationUI: shouldDisplayFeature(
  791. 'new_navigation_ui',
  792. user.alphaProgram
  793. ),
  794. showReactShareModal: shouldDisplayFeature(
  795. 'new_share_modal_ui',
  796. true
  797. ),
  798. showReactDropboxModal: shouldDisplayFeature(
  799. 'new_dropbox_modal_ui',
  800. user.betaProgram
  801. ),
  802. showReactGithubSync: shouldDisplayFeature(
  803. 'new_github_sync_ui',
  804. user.betaProgram || user.alphaProgram
  805. ),
  806. showNewBinaryFileUI: shouldDisplayFeature('new_binary_file'),
  807. showSymbolPalette: shouldDisplayFeature('symbol_palette'),
  808. trackPdfDownload,
  809. enablePdfCaching,
  810. })
  811. timer.done()
  812. }
  813. Promise.all([
  814. (async () => {
  815. if (Settings.enablePdfCaching) {
  816. if (user.alphaProgram) {
  817. trackPdfDownload = true
  818. } else if (user.betaProgram) {
  819. const testSegmentation = await SplitTestHandler.promises.getTestSegmentation(
  820. userId,
  821. 'track_pdf_download'
  822. )
  823. trackPdfDownload =
  824. testSegmentation.enabled &&
  825. testSegmentation.variant === 'enabled'
  826. }
  827. }
  828. })(),
  829. (async () => {
  830. if (Settings.enablePdfCaching) {
  831. if (user.alphaProgram) {
  832. enablePdfCaching = shouldDisplayFeature(
  833. 'enable_pdf_caching',
  834. true
  835. )
  836. } else if (user.betaProgram) {
  837. const testSegmentation = await SplitTestHandler.promises.getTestSegmentation(
  838. userId,
  839. 'enable_pdf_caching'
  840. )
  841. enablePdfCaching = shouldDisplayFeature(
  842. 'enable_pdf_caching',
  843. testSegmentation.enabled &&
  844. testSegmentation.variant === 'enabled'
  845. )
  846. } else {
  847. enablePdfCaching = shouldDisplayFeature(
  848. 'enable_pdf_caching',
  849. false
  850. )
  851. }
  852. }
  853. })(),
  854. ])
  855. .then(() => {
  856. render()
  857. })
  858. .catch(error => {
  859. logger.error({ err: error }, 'Failed to get test segmentation')
  860. render()
  861. })
  862. }
  863. )
  864. }
  865. )
  866. },
  867. _buildProjectList(allProjects, userId) {
  868. let project
  869. const {
  870. owned,
  871. readAndWrite,
  872. readOnly,
  873. tokenReadAndWrite,
  874. tokenReadOnly,
  875. } = allProjects
  876. const projects = []
  877. for (project of owned) {
  878. projects.push(
  879. ProjectController._buildProjectViewModel(
  880. project,
  881. 'owner',
  882. Sources.OWNER,
  883. userId
  884. )
  885. )
  886. }
  887. // Invite-access
  888. for (project of readAndWrite) {
  889. projects.push(
  890. ProjectController._buildProjectViewModel(
  891. project,
  892. 'readWrite',
  893. Sources.INVITE,
  894. userId
  895. )
  896. )
  897. }
  898. for (project of readOnly) {
  899. projects.push(
  900. ProjectController._buildProjectViewModel(
  901. project,
  902. 'readOnly',
  903. Sources.INVITE,
  904. userId
  905. )
  906. )
  907. }
  908. // Token-access
  909. // Only add these projects if they're not already present, this gives us cascading access
  910. // from 'owner' => 'token-read-only'
  911. for (project of tokenReadAndWrite) {
  912. if (
  913. projects.filter(p => p.id.toString() === project._id.toString())
  914. .length === 0
  915. ) {
  916. projects.push(
  917. ProjectController._buildProjectViewModel(
  918. project,
  919. 'readAndWrite',
  920. Sources.TOKEN,
  921. userId
  922. )
  923. )
  924. }
  925. }
  926. for (project of tokenReadOnly) {
  927. if (
  928. projects.filter(p => p.id.toString() === project._id.toString())
  929. .length === 0
  930. ) {
  931. projects.push(
  932. ProjectController._buildProjectViewModel(
  933. project,
  934. 'readOnly',
  935. Sources.TOKEN,
  936. userId
  937. )
  938. )
  939. }
  940. }
  941. return projects
  942. },
  943. _buildProjectViewModel(project, accessLevel, source, userId) {
  944. const archived = ProjectHelper.isArchived(project, userId)
  945. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  946. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  947. TokenAccessHandler.protectTokens(project, accessLevel)
  948. const model = {
  949. id: project._id,
  950. name: project.name,
  951. lastUpdated: project.lastUpdated,
  952. lastUpdatedBy: project.lastUpdatedBy,
  953. publicAccessLevel: project.publicAccesLevel,
  954. accessLevel,
  955. source,
  956. archived,
  957. trashed,
  958. owner_ref: project.owner_ref,
  959. isV1Project: false,
  960. }
  961. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  962. model.owner_ref = null
  963. model.lastUpdatedBy = null
  964. }
  965. return model
  966. },
  967. _injectProjectUsers(projects, callback) {
  968. const users = {}
  969. for (const project of projects) {
  970. if (project.owner_ref != null) {
  971. users[project.owner_ref.toString()] = true
  972. }
  973. if (project.lastUpdatedBy != null) {
  974. users[project.lastUpdatedBy.toString()] = true
  975. }
  976. }
  977. const userIds = Object.keys(users)
  978. async.eachSeries(
  979. userIds,
  980. (userId, cb) => {
  981. UserGetter.getUser(
  982. userId,
  983. { first_name: 1, last_name: 1, email: 1 },
  984. (error, user) => {
  985. if (error != null) {
  986. return cb(error)
  987. }
  988. users[userId] = user
  989. cb()
  990. }
  991. )
  992. },
  993. error => {
  994. if (error != null) {
  995. return callback(error)
  996. }
  997. for (const project of projects) {
  998. if (project.owner_ref != null) {
  999. project.owner = users[project.owner_ref.toString()]
  1000. }
  1001. if (project.lastUpdatedBy != null) {
  1002. project.lastUpdatedBy =
  1003. users[project.lastUpdatedBy.toString()] || null
  1004. }
  1005. }
  1006. callback(null, projects)
  1007. }
  1008. )
  1009. },
  1010. _buildPortalTemplatesList(affiliations) {
  1011. if (affiliations == null) {
  1012. affiliations = []
  1013. }
  1014. const portalTemplates = []
  1015. for (const aff of affiliations) {
  1016. if (
  1017. aff.portal &&
  1018. aff.portal.slug &&
  1019. aff.portal.templates_count &&
  1020. aff.portal.templates_count > 0
  1021. ) {
  1022. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1023. portalTemplates.push({
  1024. name: aff.institution.name,
  1025. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1026. })
  1027. }
  1028. }
  1029. return portalTemplates
  1030. },
  1031. }
  1032. var defaultSettingsForAnonymousUser = userId => ({
  1033. id: userId,
  1034. ace: {
  1035. mode: 'none',
  1036. theme: 'textmate',
  1037. fontSize: '12',
  1038. autoComplete: true,
  1039. spellCheckLanguage: '',
  1040. pdfViewer: '',
  1041. syntaxValidation: true,
  1042. },
  1043. subscription: {
  1044. freeTrial: {
  1045. allowed: true,
  1046. },
  1047. },
  1048. featureSwitches: {
  1049. github: false,
  1050. },
  1051. alphaProgram: false,
  1052. betaProgram: false,
  1053. })
  1054. var THEME_LIST = []
  1055. function generateThemeList() {
  1056. const files = fs.readdirSync(
  1057. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1058. )
  1059. const result = []
  1060. for (const file of files) {
  1061. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1062. const cleanName = file.slice(0, -3).slice(6)
  1063. result.push(THEME_LIST.push(cleanName))
  1064. } else {
  1065. result.push(undefined)
  1066. }
  1067. }
  1068. }
  1069. generateThemeList()
  1070. module.exports = ProjectController