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