ProjectController.js 33 KB

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