ProjectController.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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 { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
  41. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  42. if (!affiliation.institution) return false
  43. // institution.confirmed is for the domain being confirmed, not the email
  44. // Do not show SSO UI for unconfirmed domains
  45. if (!affiliation.institution.confirmed) return false
  46. // Could have multiple emails at the same institution, and if any are
  47. // linked to the institution then do not show notification for others
  48. if (
  49. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  50. ) {
  51. if (affiliation.institution.ssoEnabled) return true
  52. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  53. return false
  54. }
  55. return false
  56. }
  57. const ProjectController = {
  58. _isInPercentageRollout(rolloutName, objectId, percentage) {
  59. if (Settings.bypassPercentageRollouts === true) {
  60. return true
  61. }
  62. const data = `${rolloutName}:${objectId.toString()}`
  63. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  64. const counter = parseInt(md5hash.slice(26, 32), 16)
  65. return counter % 100 < percentage
  66. },
  67. updateProjectSettings(req, res, next) {
  68. const projectId = req.params.Project_id
  69. const jobs = []
  70. if (req.body.compiler != null) {
  71. jobs.push(callback =>
  72. EditorController.setCompiler(projectId, req.body.compiler, callback)
  73. )
  74. }
  75. if (req.body.imageName != null) {
  76. jobs.push(callback =>
  77. EditorController.setImageName(projectId, req.body.imageName, callback)
  78. )
  79. }
  80. if (req.body.name != null) {
  81. jobs.push(callback =>
  82. EditorController.renameProject(projectId, req.body.name, callback)
  83. )
  84. }
  85. if (req.body.spellCheckLanguage != null) {
  86. jobs.push(callback =>
  87. EditorController.setSpellCheckLanguage(
  88. projectId,
  89. req.body.spellCheckLanguage,
  90. callback
  91. )
  92. )
  93. }
  94. if (req.body.rootDocId != null) {
  95. jobs.push(callback =>
  96. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  97. )
  98. }
  99. async.series(jobs, error => {
  100. if (error != null) {
  101. return next(error)
  102. }
  103. res.sendStatus(204)
  104. })
  105. },
  106. updateProjectAdminSettings(req, res, next) {
  107. const projectId = req.params.Project_id
  108. const jobs = []
  109. if (req.body.publicAccessLevel != null) {
  110. jobs.push(callback =>
  111. EditorController.setPublicAccessLevel(
  112. projectId,
  113. req.body.publicAccessLevel,
  114. callback
  115. )
  116. )
  117. }
  118. async.series(jobs, error => {
  119. if (error != null) {
  120. return next(error)
  121. }
  122. res.sendStatus(204)
  123. })
  124. },
  125. deleteProject(req, res) {
  126. const projectId = req.params.Project_id
  127. const user = AuthenticationController.getSessionUser(req)
  128. const cb = err => {
  129. if (err != null) {
  130. res.sendStatus(500)
  131. } else {
  132. res.sendStatus(200)
  133. }
  134. }
  135. ProjectDeleter.deleteProject(
  136. projectId,
  137. { deleterUser: user, ipAddress: req.ip },
  138. cb
  139. )
  140. },
  141. archiveProject(req, res, next) {
  142. const projectId = req.params.Project_id
  143. const userId = AuthenticationController.getLoggedInUserId(req)
  144. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  145. if (err != null) {
  146. return next(err)
  147. } else {
  148. return res.sendStatus(200)
  149. }
  150. })
  151. },
  152. unarchiveProject(req, res, next) {
  153. const projectId = req.params.Project_id
  154. const userId = AuthenticationController.getLoggedInUserId(req)
  155. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  156. if (err != null) {
  157. return next(err)
  158. } else {
  159. return res.sendStatus(200)
  160. }
  161. })
  162. },
  163. trashProject(req, res, next) {
  164. const projectId = req.params.project_id
  165. const userId = AuthenticationController.getLoggedInUserId(req)
  166. ProjectDeleter.trashProject(projectId, userId, function (err) {
  167. if (err != null) {
  168. return next(err)
  169. } else {
  170. return res.sendStatus(200)
  171. }
  172. })
  173. },
  174. untrashProject(req, res, next) {
  175. const projectId = req.params.project_id
  176. const userId = AuthenticationController.getLoggedInUserId(req)
  177. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  178. if (err != null) {
  179. return next(err)
  180. } else {
  181. return res.sendStatus(200)
  182. }
  183. })
  184. },
  185. expireDeletedProjectsAfterDuration(req, res) {
  186. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  187. if (err != null) {
  188. res.sendStatus(500)
  189. } else {
  190. res.sendStatus(200)
  191. }
  192. })
  193. },
  194. expireDeletedProject(req, res, next) {
  195. const { projectId } = req.params
  196. ProjectDeleter.expireDeletedProject(projectId, err => {
  197. if (err != null) {
  198. next(err)
  199. } else {
  200. res.sendStatus(200)
  201. }
  202. })
  203. },
  204. restoreProject(req, res) {
  205. const projectId = req.params.Project_id
  206. ProjectDeleter.restoreProject(projectId, err => {
  207. if (err != null) {
  208. res.sendStatus(500)
  209. } else {
  210. res.sendStatus(200)
  211. }
  212. })
  213. },
  214. cloneProject(req, res, next) {
  215. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  216. metrics.inc('cloned-project')
  217. const projectId = req.params.Project_id
  218. const { projectName } = req.body
  219. logger.log({ projectId, projectName }, 'cloning project')
  220. if (!AuthenticationController.isUserLoggedIn(req)) {
  221. return res.send({ redir: '/register' })
  222. }
  223. const currentUser = AuthenticationController.getSessionUser(req)
  224. const { first_name: firstName, last_name: lastName, email } = currentUser
  225. ProjectDuplicator.duplicate(
  226. currentUser,
  227. projectId,
  228. projectName,
  229. (err, project) => {
  230. if (err != null) {
  231. OError.tag(err, 'error cloning project', {
  232. projectId,
  233. userId: currentUser._id,
  234. })
  235. return next(err)
  236. }
  237. res.send({
  238. name: project.name,
  239. project_id: project._id,
  240. owner_ref: project.owner_ref,
  241. owner: {
  242. first_name: firstName,
  243. last_name: lastName,
  244. email,
  245. _id: currentUser._id,
  246. },
  247. })
  248. }
  249. )
  250. },
  251. newProject(req, res, next) {
  252. const currentUser = AuthenticationController.getSessionUser(req)
  253. const {
  254. first_name: firstName,
  255. last_name: lastName,
  256. email,
  257. _id: userId,
  258. } = currentUser
  259. const projectName =
  260. req.body.projectName != null ? req.body.projectName.trim() : undefined
  261. const { template } = req.body
  262. async.waterfall(
  263. [
  264. cb => {
  265. if (template === 'example') {
  266. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  267. } else {
  268. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  269. }
  270. },
  271. ],
  272. (err, project) => {
  273. if (err != null) {
  274. return next(err)
  275. }
  276. res.send({
  277. project_id: project._id,
  278. owner_ref: project.owner_ref,
  279. owner: {
  280. first_name: firstName,
  281. last_name: lastName,
  282. email,
  283. _id: userId,
  284. },
  285. })
  286. }
  287. )
  288. },
  289. renameProject(req, res, next) {
  290. const projectId = req.params.Project_id
  291. const newName = req.body.newProjectName
  292. EditorController.renameProject(projectId, newName, err => {
  293. if (err != null) {
  294. return next(err)
  295. }
  296. res.sendStatus(200)
  297. })
  298. },
  299. userProjectsJson(req, res, next) {
  300. const userId = AuthenticationController.getLoggedInUserId(req)
  301. ProjectGetter.findAllUsersProjects(
  302. userId,
  303. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  304. (err, projects) => {
  305. if (err != null) {
  306. return next(err)
  307. }
  308. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  309. projects = ProjectController._buildProjectList(projects, userId)
  310. .filter(p => !(p.archived || p.trashed))
  311. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  312. res.json({ projects })
  313. }
  314. )
  315. },
  316. projectEntitiesJson(req, res, next) {
  317. const projectId = req.params.Project_id
  318. ProjectGetter.getProject(projectId, (err, project) => {
  319. if (err != null) {
  320. return next(err)
  321. }
  322. ProjectEntityHandler.getAllEntitiesFromProject(
  323. project,
  324. (err, docs, files) => {
  325. if (err != null) {
  326. return next(err)
  327. }
  328. const entities = docs
  329. .concat(files)
  330. // Sort by path ascending
  331. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  332. .map(e => ({
  333. path: e.path,
  334. type: e.doc != null ? 'doc' : 'file',
  335. }))
  336. res.json({ project_id: projectId, entities })
  337. }
  338. )
  339. })
  340. },
  341. projectListPage(req, res, next) {
  342. const timer = new metrics.Timer('project-list')
  343. const userId = AuthenticationController.getLoggedInUserId(req)
  344. const currentUser = AuthenticationController.getSessionUser(req)
  345. async.parallel(
  346. {
  347. tags(cb) {
  348. TagsHandler.getAllTags(userId, cb)
  349. },
  350. notifications(cb) {
  351. NotificationsHandler.getUserNotifications(userId, cb)
  352. },
  353. projects(cb) {
  354. ProjectGetter.findAllUsersProjects(
  355. userId,
  356. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  357. cb
  358. )
  359. },
  360. hasSubscription(cb) {
  361. LimitationsManager.hasPaidSubscription(
  362. currentUser,
  363. (error, hasPaidSubscription) => {
  364. if (error != null && error instanceof V1ConnectionError) {
  365. return cb(null, true)
  366. }
  367. cb(error, hasPaidSubscription)
  368. }
  369. )
  370. },
  371. user(cb) {
  372. User.findById(
  373. userId,
  374. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  375. cb
  376. )
  377. },
  378. userEmailsData(cb) {
  379. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  380. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  381. if (error && error instanceof V1ConnectionError) {
  382. return cb(null, result)
  383. }
  384. if (!Features.hasFeature('affiliations')) {
  385. result.list = fullEmails
  386. return cb(null, result)
  387. }
  388. Modules.hooks.fire(
  389. 'allInReconfirmNotificationPeriodsForUser',
  390. fullEmails,
  391. (error, results) => {
  392. // Module.hooks.fire accepts multiple methods
  393. // and does async.series
  394. const allInReconfirmNotificationPeriods =
  395. (results && results[0]) || []
  396. return cb(null, {
  397. list: fullEmails,
  398. allInReconfirmNotificationPeriods,
  399. })
  400. }
  401. )
  402. })
  403. },
  404. },
  405. (err, results) => {
  406. if (err != null) {
  407. OError.tag(err, 'error getting data for project list page')
  408. return next(err)
  409. }
  410. const { notifications, user, userEmailsData } = results
  411. const userEmails = userEmailsData.list || []
  412. const userAffiliations = userEmails
  413. .filter(emailData => !!emailData.affiliation)
  414. .map(emailData => {
  415. const result = emailData.affiliation
  416. result.email = emailData.email
  417. return result
  418. })
  419. const { allInReconfirmNotificationPeriods } = userEmailsData
  420. // Handle case of deleted user
  421. if (user == null) {
  422. UserController.logout(req, res, next)
  423. return
  424. }
  425. const tags = results.tags
  426. const notificationsInstitution = []
  427. for (const notification of notifications) {
  428. notification.html = req.i18n.translate(
  429. notification.templateKey,
  430. notification.messageOpts
  431. )
  432. }
  433. // Institution SSO Notifications
  434. let reconfirmedViaSAML
  435. if (Features.hasFeature('saml')) {
  436. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  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. reconfirmedViaSAML,
  535. zipFileSizeLimit: Settings.maxUploadSize,
  536. }
  537. if (
  538. Settings.algolia &&
  539. Settings.algolia.app_id &&
  540. Settings.algolia.read_only_api_key
  541. ) {
  542. viewModel.showUserDetailsArea = true
  543. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  544. viewModel.algolia_app_id = Settings.algolia.app_id
  545. } else {
  546. viewModel.showUserDetailsArea = false
  547. }
  548. const paidUser =
  549. (user.features != null ? user.features.github : undefined) &&
  550. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  551. const freeUserProportion = 0.1
  552. const sampleFreeUser =
  553. parseInt(user._id.toString().slice(-2), 16) <
  554. freeUserProportion * 255
  555. const showFrontWidget = paidUser || sampleFreeUser
  556. if (showFrontWidget) {
  557. viewModel.frontChatWidgetRoomId =
  558. Settings.overleaf != null
  559. ? Settings.overleaf.front_chat_widget_room_id
  560. : undefined
  561. }
  562. res.render('project/list', viewModel)
  563. timer.done()
  564. })
  565. }
  566. )
  567. },
  568. loadEditor(req, res, next) {
  569. const timer = new metrics.Timer('load-editor')
  570. if (!Settings.editorIsOpen) {
  571. return res.render('general/closed', { title: 'updating_site' })
  572. }
  573. let anonymous, userId, sessionUser
  574. if (AuthenticationController.isUserLoggedIn(req)) {
  575. sessionUser = AuthenticationController.getSessionUser(req)
  576. userId = AuthenticationController.getLoggedInUserId(req)
  577. anonymous = false
  578. } else {
  579. sessionUser = null
  580. anonymous = true
  581. userId = null
  582. }
  583. const projectId = req.params.Project_id
  584. async.auto(
  585. {
  586. project(cb) {
  587. ProjectGetter.getProject(
  588. projectId,
  589. {
  590. name: 1,
  591. lastUpdated: 1,
  592. track_changes: 1,
  593. owner_ref: 1,
  594. brandVariationId: 1,
  595. overleaf: 1,
  596. tokens: 1,
  597. },
  598. (err, project) => {
  599. if (err != null) {
  600. return cb(err)
  601. }
  602. cb(null, project)
  603. }
  604. )
  605. },
  606. user(cb) {
  607. if (userId == null) {
  608. cb(null, defaultSettingsForAnonymousUser(userId))
  609. } else {
  610. User.findById(
  611. userId,
  612. 'email first_name last_name referal_id signUpDate featureSwitches features refProviders alphaProgram betaProgram isAdmin ace',
  613. (err, user) => {
  614. // Handle case of deleted user
  615. if (user == null) {
  616. UserController.logout(req, res, next)
  617. return
  618. }
  619. logger.log({ projectId, userId }, 'got user')
  620. cb(err, user)
  621. }
  622. )
  623. }
  624. },
  625. subscription(cb) {
  626. if (userId == null) {
  627. return cb()
  628. }
  629. SubscriptionLocator.getUsersSubscription(userId, cb)
  630. },
  631. activate(cb) {
  632. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  633. },
  634. markAsOpened(cb) {
  635. // don't need to wait for this to complete
  636. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  637. cb()
  638. },
  639. isTokenMember(cb) {
  640. if (userId == null) {
  641. return cb()
  642. }
  643. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  644. },
  645. brandVariation: [
  646. 'project',
  647. (cb, results) => {
  648. if (
  649. (results.project != null
  650. ? results.project.brandVariationId
  651. : undefined) == null
  652. ) {
  653. return cb()
  654. }
  655. BrandVariationsHandler.getBrandVariationById(
  656. results.project.brandVariationId,
  657. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  658. )
  659. },
  660. ],
  661. flushToTpds: cb => {
  662. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  663. },
  664. },
  665. (err, results) => {
  666. if (err != null) {
  667. OError.tag(err, 'error getting details for project page')
  668. return next(err)
  669. }
  670. const { project } = results
  671. const { user } = results
  672. const { subscription } = results
  673. const { brandVariation } = results
  674. const anonRequestToken = TokenAccessHandler.getRequestToken(
  675. req,
  676. projectId
  677. )
  678. const { isTokenMember } = results
  679. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  680. sessionUser
  681. )
  682. AuthorizationManager.getPrivilegeLevelForProject(
  683. userId,
  684. projectId,
  685. anonRequestToken,
  686. (error, privilegeLevel) => {
  687. let allowedFreeTrial = true
  688. if (error != null) {
  689. return next(error)
  690. }
  691. if (
  692. privilegeLevel == null ||
  693. privilegeLevel === PrivilegeLevels.NONE
  694. ) {
  695. return res.sendStatus(401)
  696. }
  697. if (subscription != null) {
  698. allowedFreeTrial = false
  699. }
  700. let wsUrl = Settings.wsUrl
  701. let metricName = 'load-editor-ws'
  702. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  703. wsUrl = Settings.wsUrlBeta
  704. metricName += '-beta'
  705. } else if (
  706. Settings.wsUrlV2 &&
  707. Settings.wsUrlV2Percentage > 0 &&
  708. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  709. Settings.wsUrlV2Percentage
  710. ) {
  711. wsUrl = Settings.wsUrlV2
  712. metricName += '-v2'
  713. }
  714. if (req.query && req.query.ws === 'fallback') {
  715. // `?ws=fallback` will connect to the bare origin, and ignore
  716. // the custom wsUrl. Hence it must load the client side
  717. // javascript from there too.
  718. // Not resetting it here would possibly load a socket.io v2
  719. // client and connect to a v0 endpoint.
  720. wsUrl = undefined
  721. metricName += '-fallback'
  722. }
  723. metrics.inc(metricName)
  724. if (userId) {
  725. AnalyticsManager.recordEvent(userId, 'project-opened', {
  726. projectId: project._id,
  727. })
  728. }
  729. const logsUIVariant = getNewLogsUIVariantForUser(user)
  730. function shouldDisplayFeature(name, variantFlag) {
  731. if (req.query && req.query[name]) {
  732. return req.query[name] === 'true'
  733. } else {
  734. return variantFlag === true
  735. }
  736. }
  737. res.render('project/editor', {
  738. title: project.name,
  739. priority_title: true,
  740. bodyClasses: ['editor'],
  741. project_id: project._id,
  742. user: {
  743. id: userId,
  744. email: user.email,
  745. first_name: user.first_name,
  746. last_name: user.last_name,
  747. referal_id: user.referal_id,
  748. signUpDate: user.signUpDate,
  749. allowedFreeTrial: allowedFreeTrial,
  750. featureSwitches: user.featureSwitches,
  751. features: user.features,
  752. refProviders: _.mapValues(user.refProviders, Boolean),
  753. alphaProgram: user.alphaProgram,
  754. betaProgram: user.betaProgram,
  755. isAdmin: user.isAdmin,
  756. },
  757. userSettings: {
  758. mode: user.ace.mode,
  759. editorTheme: user.ace.theme,
  760. fontSize: user.ace.fontSize,
  761. autoComplete: user.ace.autoComplete,
  762. autoPairDelimiters: user.ace.autoPairDelimiters,
  763. pdfViewer: user.ace.pdfViewer,
  764. syntaxValidation: user.ace.syntaxValidation,
  765. fontFamily: user.ace.fontFamily || 'lucida',
  766. lineHeight: user.ace.lineHeight || 'normal',
  767. overallTheme: user.ace.overallTheme,
  768. },
  769. privilegeLevel,
  770. chatUrl: Settings.apis.chat.url,
  771. anonymous,
  772. anonymousAccessToken: anonymous ? anonRequestToken : null,
  773. isTokenMember,
  774. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  775. userId,
  776. privilegeLevel,
  777. isTokenMember
  778. ),
  779. languages: Settings.languages,
  780. editorThemes: THEME_LIST,
  781. maxDocLength: Settings.max_doc_length,
  782. useV2History:
  783. project.overleaf &&
  784. project.overleaf.history &&
  785. Boolean(project.overleaf.history.display),
  786. brandVariation,
  787. allowedImageNames,
  788. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  789. wsUrl,
  790. showSupport: Features.hasFeature('support'),
  791. showNewLogsUI: shouldDisplayFeature(
  792. 'new_logs_ui',
  793. logsUIVariant.newLogsUI
  794. ),
  795. logsUISubvariant: logsUIVariant.subvariant,
  796. showNewNavigationUI: shouldDisplayFeature(
  797. 'new_navigation_ui',
  798. user.alphaProgram
  799. ),
  800. showReactShareModal: shouldDisplayFeature(
  801. 'new_share_modal_ui',
  802. true
  803. ),
  804. showReactDropboxModal: shouldDisplayFeature(
  805. 'new_dropbox_modal_ui',
  806. false
  807. ),
  808. showReactGithubSync: shouldDisplayFeature(
  809. 'new_github_sync_ui',
  810. user.alphaProgram
  811. ),
  812. showNewBinaryFileUI: shouldDisplayFeature('new_binary_file'),
  813. showSymbolPalette: shouldDisplayFeature('symbol_palette'),
  814. enablePdfCaching:
  815. Settings.enablePdfCaching &&
  816. shouldDisplayFeature('enable_pdf_caching', user.alphaProgram),
  817. })
  818. timer.done()
  819. }
  820. )
  821. }
  822. )
  823. },
  824. _buildProjectList(allProjects, userId) {
  825. let project
  826. const {
  827. owned,
  828. readAndWrite,
  829. readOnly,
  830. tokenReadAndWrite,
  831. tokenReadOnly,
  832. } = allProjects
  833. const projects = []
  834. for (project of owned) {
  835. projects.push(
  836. ProjectController._buildProjectViewModel(
  837. project,
  838. 'owner',
  839. Sources.OWNER,
  840. userId
  841. )
  842. )
  843. }
  844. // Invite-access
  845. for (project of readAndWrite) {
  846. projects.push(
  847. ProjectController._buildProjectViewModel(
  848. project,
  849. 'readWrite',
  850. Sources.INVITE,
  851. userId
  852. )
  853. )
  854. }
  855. for (project of readOnly) {
  856. projects.push(
  857. ProjectController._buildProjectViewModel(
  858. project,
  859. 'readOnly',
  860. Sources.INVITE,
  861. userId
  862. )
  863. )
  864. }
  865. // Token-access
  866. // Only add these projects if they're not already present, this gives us cascading access
  867. // from 'owner' => 'token-read-only'
  868. for (project of tokenReadAndWrite) {
  869. if (
  870. projects.filter(p => p.id.toString() === project._id.toString())
  871. .length === 0
  872. ) {
  873. projects.push(
  874. ProjectController._buildProjectViewModel(
  875. project,
  876. 'readAndWrite',
  877. Sources.TOKEN,
  878. userId
  879. )
  880. )
  881. }
  882. }
  883. for (project of tokenReadOnly) {
  884. if (
  885. projects.filter(p => p.id.toString() === project._id.toString())
  886. .length === 0
  887. ) {
  888. projects.push(
  889. ProjectController._buildProjectViewModel(
  890. project,
  891. 'readOnly',
  892. Sources.TOKEN,
  893. userId
  894. )
  895. )
  896. }
  897. }
  898. return projects
  899. },
  900. _buildProjectViewModel(project, accessLevel, source, userId) {
  901. const archived = ProjectHelper.isArchived(project, userId)
  902. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  903. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  904. TokenAccessHandler.protectTokens(project, accessLevel)
  905. const model = {
  906. id: project._id,
  907. name: project.name,
  908. lastUpdated: project.lastUpdated,
  909. lastUpdatedBy: project.lastUpdatedBy,
  910. publicAccessLevel: project.publicAccesLevel,
  911. accessLevel,
  912. source,
  913. archived,
  914. trashed,
  915. owner_ref: project.owner_ref,
  916. isV1Project: false,
  917. }
  918. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  919. model.owner_ref = null
  920. model.lastUpdatedBy = null
  921. }
  922. return model
  923. },
  924. _injectProjectUsers(projects, callback) {
  925. const users = {}
  926. for (const project of projects) {
  927. if (project.owner_ref != null) {
  928. users[project.owner_ref.toString()] = true
  929. }
  930. if (project.lastUpdatedBy != null) {
  931. users[project.lastUpdatedBy.toString()] = true
  932. }
  933. }
  934. const userIds = Object.keys(users)
  935. async.eachSeries(
  936. userIds,
  937. (userId, cb) => {
  938. UserGetter.getUser(
  939. userId,
  940. { first_name: 1, last_name: 1, email: 1 },
  941. (error, user) => {
  942. if (error != null) {
  943. return cb(error)
  944. }
  945. users[userId] = user
  946. cb()
  947. }
  948. )
  949. },
  950. error => {
  951. if (error != null) {
  952. return callback(error)
  953. }
  954. for (const project of projects) {
  955. if (project.owner_ref != null) {
  956. project.owner = users[project.owner_ref.toString()]
  957. }
  958. if (project.lastUpdatedBy != null) {
  959. project.lastUpdatedBy =
  960. users[project.lastUpdatedBy.toString()] || null
  961. }
  962. }
  963. callback(null, projects)
  964. }
  965. )
  966. },
  967. _buildPortalTemplatesList(affiliations) {
  968. if (affiliations == null) {
  969. affiliations = []
  970. }
  971. const portalTemplates = []
  972. for (const aff of affiliations) {
  973. if (
  974. aff.portal &&
  975. aff.portal.slug &&
  976. aff.portal.templates_count &&
  977. aff.portal.templates_count > 0
  978. ) {
  979. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  980. portalTemplates.push({
  981. name: aff.institution.name,
  982. url: Settings.siteUrl + portalPath + aff.portal.slug,
  983. })
  984. }
  985. }
  986. return portalTemplates
  987. },
  988. }
  989. var defaultSettingsForAnonymousUser = userId => ({
  990. id: userId,
  991. ace: {
  992. mode: 'none',
  993. theme: 'textmate',
  994. fontSize: '12',
  995. autoComplete: true,
  996. spellCheckLanguage: '',
  997. pdfViewer: '',
  998. syntaxValidation: true,
  999. },
  1000. subscription: {
  1001. freeTrial: {
  1002. allowed: true,
  1003. },
  1004. },
  1005. featureSwitches: {
  1006. github: false,
  1007. },
  1008. alphaProgram: false,
  1009. betaProgram: false,
  1010. })
  1011. var THEME_LIST = []
  1012. function generateThemeList() {
  1013. const files = fs.readdirSync(
  1014. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1015. )
  1016. const result = []
  1017. for (const file of files) {
  1018. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1019. const cleanName = file.slice(0, -3).slice(6)
  1020. result.push(THEME_LIST.push(cleanName))
  1021. } else {
  1022. result.push(undefined)
  1023. }
  1024. }
  1025. }
  1026. generateThemeList()
  1027. module.exports = ProjectController