ProjectController.js 33 KB

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