ProjectController.js 32 KB

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