ProjectController.js 33 KB

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