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.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. const wantsOldFileTreeUI =
  683. req.query && req.query.new_file_tree_ui === 'false'
  684. const wantsOldShareModalUI =
  685. req.query && req.query.new_share_modal_ui === 'false'
  686. const wantsOldAddFilesModalUI =
  687. req.query && req.query.new_add_files_modal_ui === 'false'
  688. const wantsOldGithubSyncUI =
  689. req.query && req.query.new_github_sync_ui === 'false'
  690. AuthorizationManager.getPrivilegeLevelForProject(
  691. userId,
  692. projectId,
  693. anonRequestToken,
  694. (error, privilegeLevel) => {
  695. let allowedFreeTrial = true
  696. if (error != null) {
  697. return next(error)
  698. }
  699. if (
  700. privilegeLevel == null ||
  701. privilegeLevel === PrivilegeLevels.NONE
  702. ) {
  703. return res.sendStatus(401)
  704. }
  705. if (subscription != null) {
  706. allowedFreeTrial = false
  707. }
  708. let wsUrl = Settings.wsUrl
  709. let metricName = 'load-editor-ws'
  710. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  711. wsUrl = Settings.wsUrlBeta
  712. metricName += '-beta'
  713. } else if (
  714. Settings.wsUrlV2 &&
  715. Settings.wsUrlV2Percentage > 0 &&
  716. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  717. Settings.wsUrlV2Percentage
  718. ) {
  719. wsUrl = Settings.wsUrlV2
  720. metricName += '-v2'
  721. }
  722. if (req.query && req.query.ws === 'fallback') {
  723. // `?ws=fallback` will connect to the bare origin, and ignore
  724. // the custom wsUrl. Hence it must load the client side
  725. // javascript from there too.
  726. // Not resetting it here would possibly load a socket.io v2
  727. // client and connect to a v0 endpoint.
  728. wsUrl = undefined
  729. metricName += '-fallback'
  730. }
  731. metrics.inc(metricName)
  732. if (userId) {
  733. AnalyticsManager.recordEvent(userId, 'project-opened', {
  734. projectId: project._id
  735. })
  736. }
  737. const logsUIVariant = getNewLogsUIVariantForUser(user)
  738. const userShouldSeeNewLogsUI = logsUIVariant.newLogsUI
  739. const wantsOldLogsUI =
  740. req.query && req.query.new_logs_ui === 'false'
  741. res.render('project/editor', {
  742. title: project.name,
  743. priority_title: true,
  744. bodyClasses: ['editor'],
  745. project_id: project._id,
  746. user: {
  747. id: userId,
  748. email: user.email,
  749. first_name: user.first_name,
  750. last_name: user.last_name,
  751. referal_id: user.referal_id,
  752. signUpDate: user.signUpDate,
  753. allowedFreeTrial: allowedFreeTrial,
  754. featureSwitches: user.featureSwitches,
  755. features: user.features,
  756. refProviders: _.mapValues(user.refProviders, Boolean),
  757. alphaProgram: user.alphaProgram,
  758. betaProgram: user.betaProgram,
  759. isAdmin: user.isAdmin
  760. },
  761. userSettings: {
  762. mode: user.ace.mode,
  763. editorTheme: user.ace.theme,
  764. fontSize: user.ace.fontSize,
  765. autoComplete: user.ace.autoComplete,
  766. autoPairDelimiters: user.ace.autoPairDelimiters,
  767. pdfViewer: user.ace.pdfViewer,
  768. syntaxValidation: user.ace.syntaxValidation,
  769. fontFamily: user.ace.fontFamily || 'lucida',
  770. lineHeight: user.ace.lineHeight || 'normal',
  771. overallTheme: user.ace.overallTheme
  772. },
  773. privilegeLevel,
  774. chatUrl: Settings.apis.chat.url,
  775. anonymous,
  776. anonymousAccessToken: anonymous ? anonRequestToken : null,
  777. isTokenMember,
  778. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  779. userId,
  780. privilegeLevel,
  781. isTokenMember
  782. ),
  783. languages: Settings.languages,
  784. editorThemes: THEME_LIST,
  785. maxDocLength: Settings.max_doc_length,
  786. useV2History:
  787. project.overleaf &&
  788. project.overleaf.history &&
  789. Boolean(project.overleaf.history.display),
  790. brandVariation,
  791. allowedImageNames,
  792. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  793. wsUrl,
  794. showSupport: Features.hasFeature('support'),
  795. showNewLogsUI: userShouldSeeNewLogsUI && !wantsOldLogsUI,
  796. logsUISubvariant: logsUIVariant.subvariant,
  797. showNewNavigationUI:
  798. req.query && req.query.new_navigation_ui === 'true',
  799. showReactFileTree: !wantsOldFileTreeUI,
  800. showReactShareModal: !wantsOldShareModalUI,
  801. showReactAddFilesModal: !wantsOldAddFilesModalUI,
  802. showReactGithubSync: !wantsOldGithubSyncUI && user.alphaProgram,
  803. showNewBinaryFileUI:
  804. req.query && req.query.new_binary_file === 'true'
  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