ProjectController.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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('@overleaf/logger')
  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('@overleaf/settings')
  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 SessionManager = require('../Authentication/SessionManager')
  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 SplitTestV2Handler = require('../SplitTests/SplitTestV2Handler')
  41. const { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
  42. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  43. const SpellingHandler = require('../Spelling/SpellingHandler')
  44. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  45. if (!affiliation.institution) return false
  46. // institution.confirmed is for the domain being confirmed, not the email
  47. // Do not show SSO UI for unconfirmed domains
  48. if (!affiliation.institution.confirmed) return false
  49. // Could have multiple emails at the same institution, and if any are
  50. // linked to the institution then do not show notification for others
  51. if (
  52. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  53. ) {
  54. if (affiliation.institution.ssoEnabled) return true
  55. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  56. return false
  57. }
  58. return false
  59. }
  60. const ProjectController = {
  61. _isInPercentageRollout(rolloutName, objectId, percentage) {
  62. if (Settings.bypassPercentageRollouts === true) {
  63. return true
  64. }
  65. const data = `${rolloutName}:${objectId.toString()}`
  66. const md5hash = crypto.createHash('md5').update(data).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 = SessionManager.getSessionUser(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 = SessionManager.getLoggedInUserId(req.session)
  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 (!SessionManager.isUserLoggedIn(req.session)) {
  224. return res.json({ redir: '/register' })
  225. }
  226. const currentUser = SessionManager.getSessionUser(req.session)
  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.json({
  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 = SessionManager.getSessionUser(req.session)
  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.json({
  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 = SessionManager.getLoggedInUserId(req.session)
  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. const { docs, files } =
  326. ProjectEntityHandler.getAllEntitiesFromProject(project)
  327. const entities = docs
  328. .concat(files)
  329. // Sort by path ascending
  330. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  331. .map(e => ({
  332. path: e.path,
  333. type: e.doc != null ? 'doc' : 'file',
  334. }))
  335. res.json({ project_id: projectId, entities })
  336. })
  337. },
  338. projectListPage(req, res, next) {
  339. const timer = new metrics.Timer('project-list')
  340. const userId = SessionManager.getLoggedInUserId(req.session)
  341. const currentUser = SessionManager.getSessionUser(req.session)
  342. async.parallel(
  343. {
  344. tags(cb) {
  345. TagsHandler.getAllTags(userId, cb)
  346. },
  347. notifications(cb) {
  348. NotificationsHandler.getUserNotifications(userId, cb)
  349. },
  350. projects(cb) {
  351. ProjectGetter.findAllUsersProjects(
  352. userId,
  353. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  354. cb
  355. )
  356. },
  357. hasSubscription(cb) {
  358. LimitationsManager.hasPaidSubscription(
  359. currentUser,
  360. (error, hasPaidSubscription) => {
  361. if (error != null && error instanceof V1ConnectionError) {
  362. return cb(null, true)
  363. }
  364. cb(error, hasPaidSubscription)
  365. }
  366. )
  367. },
  368. user(cb) {
  369. User.findById(
  370. userId,
  371. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  372. cb
  373. )
  374. },
  375. userEmailsData(cb) {
  376. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  377. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  378. if (error && error instanceof V1ConnectionError) {
  379. return cb(null, result)
  380. }
  381. if (!Features.hasFeature('affiliations')) {
  382. result.list = fullEmails
  383. return cb(null, result)
  384. }
  385. Modules.hooks.fire(
  386. 'allInReconfirmNotificationPeriodsForUser',
  387. fullEmails,
  388. (error, results) => {
  389. if (error != null) {
  390. return cb(error)
  391. }
  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 =
  507. ProjectController._buildPortalTemplatesList(userAffiliations)
  508. const projects = ProjectController._buildProjectList(
  509. results.projects,
  510. userId
  511. )
  512. // in v2 add notifications for matching university IPs
  513. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  514. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  515. req.ip,
  516. () => {}
  517. )
  518. }
  519. ProjectController._injectProjectUsers(projects, (error, projects) => {
  520. if (error != null) {
  521. return next(error)
  522. }
  523. const viewModel = {
  524. title: 'your_projects',
  525. priority_title: true,
  526. projects,
  527. tags,
  528. notifications: notifications || [],
  529. notificationsInstitution,
  530. allInReconfirmNotificationPeriods,
  531. portalTemplates,
  532. user,
  533. userAffiliations,
  534. userEmails,
  535. hasSubscription: results.hasSubscription,
  536. reconfirmedViaSAML,
  537. zipFileSizeLimit: Settings.maxUploadSize,
  538. isOverleaf: !!Settings.overleaf,
  539. metadata: { viewport: false },
  540. }
  541. const paidUser =
  542. (user.features != null ? user.features.github : undefined) &&
  543. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  544. const freeUserProportion = 0.1
  545. const sampleFreeUser =
  546. parseInt(user._id.toString().slice(-2), 16) <
  547. freeUserProportion * 255
  548. const showFrontWidget = paidUser || sampleFreeUser
  549. if (showFrontWidget) {
  550. viewModel.frontChatWidgetRoomId =
  551. Settings.overleaf != null
  552. ? Settings.overleaf.front_chat_widget_room_id
  553. : undefined
  554. }
  555. // null test targeting logged in users
  556. SplitTestV2Handler.promises.getAssignmentForSession(
  557. req.session,
  558. 'null-test-dashboard'
  559. )
  560. res.render('project/list', viewModel)
  561. timer.done()
  562. })
  563. }
  564. )
  565. },
  566. loadEditor(req, res, next) {
  567. const timer = new metrics.Timer('load-editor')
  568. if (!Settings.editorIsOpen) {
  569. return res.render('general/closed', { title: 'updating_site' })
  570. }
  571. let anonymous, userId, sessionUser
  572. if (SessionManager.isUserLoggedIn(req.session)) {
  573. sessionUser = SessionManager.getSessionUser(req.session)
  574. userId = SessionManager.getLoggedInUserId(req.session)
  575. anonymous = false
  576. } else {
  577. sessionUser = null
  578. anonymous = true
  579. userId = null
  580. }
  581. const projectId = req.params.Project_id
  582. async.auto(
  583. {
  584. project(cb) {
  585. ProjectGetter.getProject(
  586. projectId,
  587. {
  588. name: 1,
  589. lastUpdated: 1,
  590. track_changes: 1,
  591. owner_ref: 1,
  592. brandVariationId: 1,
  593. overleaf: 1,
  594. tokens: 1,
  595. },
  596. (err, project) => {
  597. if (err != null) {
  598. return cb(err)
  599. }
  600. cb(null, project)
  601. }
  602. )
  603. },
  604. user(cb) {
  605. if (userId == null) {
  606. cb(null, defaultSettingsForAnonymousUser(userId))
  607. } else {
  608. User.updateOne(
  609. { _id: ObjectId(userId) },
  610. { $set: { lastActive: new Date() } },
  611. {},
  612. () => {}
  613. )
  614. User.findById(
  615. userId,
  616. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace',
  617. (err, user) => {
  618. // Handle case of deleted user
  619. if (user == null) {
  620. UserController.logout(req, res, next)
  621. return
  622. }
  623. if (err) {
  624. return cb(err)
  625. }
  626. logger.log({ projectId, userId }, 'got user')
  627. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  628. return cb(null, user)
  629. }
  630. ProjectController._refreshFeatures(req, user, cb)
  631. }
  632. )
  633. }
  634. },
  635. learnedWords(cb) {
  636. if (!userId) {
  637. return cb(null, [])
  638. }
  639. SpellingHandler.getUserDictionary(userId, cb)
  640. },
  641. subscription(cb) {
  642. if (userId == null) {
  643. return cb()
  644. }
  645. SubscriptionLocator.getUsersSubscription(userId, cb)
  646. },
  647. activate(cb) {
  648. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  649. },
  650. markAsOpened(cb) {
  651. // don't need to wait for this to complete
  652. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  653. cb()
  654. },
  655. isTokenMember(cb) {
  656. if (userId == null) {
  657. return cb()
  658. }
  659. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  660. },
  661. brandVariation: [
  662. 'project',
  663. (cb, results) => {
  664. if (
  665. (results.project != null
  666. ? results.project.brandVariationId
  667. : undefined) == null
  668. ) {
  669. return cb()
  670. }
  671. BrandVariationsHandler.getBrandVariationById(
  672. results.project.brandVariationId,
  673. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  674. )
  675. },
  676. ],
  677. flushToTpds: cb => {
  678. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  679. },
  680. sharingModalSplitTest(cb) {
  681. SplitTestV2Handler.assignInLocalsContextForSession(
  682. res,
  683. req.session,
  684. 'project-share-modal-paywall',
  685. {},
  686. () => {
  687. // do not fail editor load if assignment fails
  688. cb()
  689. }
  690. )
  691. },
  692. sharingModalNullTest(cb) {
  693. // null test targeting logged in users, for front-end side
  694. SplitTestV2Handler.assignInLocalsContextForSession(
  695. res,
  696. req.session,
  697. 'null-test-share-modal',
  698. {},
  699. () => {
  700. // do not fail editor load if assignment fails
  701. cb()
  702. }
  703. )
  704. },
  705. newPdfPreviewAssignment(cb) {
  706. SplitTestV2Handler.getAssignmentForSession(
  707. req.session,
  708. 'react-pdf-preview-rollout',
  709. {},
  710. (error, assignment) => {
  711. if (error) {
  712. // do not fail editor load if assignment fails
  713. cb(null, { variant: 'default' })
  714. } else {
  715. cb(null, assignment)
  716. }
  717. }
  718. )
  719. },
  720. },
  721. (
  722. err,
  723. {
  724. project,
  725. user,
  726. learnedWords,
  727. subscription,
  728. isTokenMember,
  729. brandVariation,
  730. newPdfPreviewAssignment,
  731. }
  732. ) => {
  733. if (err != null) {
  734. OError.tag(err, 'error getting details for project page')
  735. return next(err)
  736. }
  737. const anonRequestToken = TokenAccessHandler.getRequestToken(
  738. req,
  739. projectId
  740. )
  741. const allowedImageNames =
  742. ProjectHelper.getAllowedImagesForUser(sessionUser)
  743. AuthorizationManager.getPrivilegeLevelForProject(
  744. userId,
  745. projectId,
  746. anonRequestToken,
  747. (error, privilegeLevel) => {
  748. let allowedFreeTrial = true
  749. if (error != null) {
  750. return next(error)
  751. }
  752. if (
  753. privilegeLevel == null ||
  754. privilegeLevel === PrivilegeLevels.NONE
  755. ) {
  756. return res.sendStatus(401)
  757. }
  758. if (subscription != null) {
  759. allowedFreeTrial = false
  760. }
  761. let wsUrl = Settings.wsUrl
  762. let metricName = 'load-editor-ws'
  763. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  764. wsUrl = Settings.wsUrlBeta
  765. metricName += '-beta'
  766. } else if (
  767. Settings.wsUrlV2 &&
  768. Settings.wsUrlV2Percentage > 0 &&
  769. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  770. Settings.wsUrlV2Percentage
  771. ) {
  772. wsUrl = Settings.wsUrlV2
  773. metricName += '-v2'
  774. }
  775. if (req.query && req.query.ws === 'fallback') {
  776. // `?ws=fallback` will connect to the bare origin, and ignore
  777. // the custom wsUrl. Hence it must load the client side
  778. // javascript from there too.
  779. // Not resetting it here would possibly load a socket.io v2
  780. // client and connect to a v0 endpoint.
  781. wsUrl = undefined
  782. metricName += '-fallback'
  783. }
  784. metrics.inc(metricName)
  785. if (userId) {
  786. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  787. projectId: project._id,
  788. })
  789. }
  790. const logsUIVariant = getNewLogsUIVariantForUser(user)
  791. function shouldDisplayFeature(name, variantFlag) {
  792. if (req.query && req.query[name]) {
  793. return req.query[name] === 'true'
  794. } else {
  795. return variantFlag === true
  796. }
  797. }
  798. function partOfPdfCachingRollout(flag) {
  799. if (!Settings.enablePdfCaching) {
  800. // The feature is disabled globally.
  801. return false
  802. }
  803. // Let the user opt-in only.
  804. // The flag will opt-out of both caching and metrics collection,
  805. // as if this editing session never happened.
  806. return shouldDisplayFeature('enable_pdf_caching', false)
  807. }
  808. let showNewPdfPreview = shouldDisplayFeature(
  809. 'new_pdf_preview',
  810. newPdfPreviewAssignment.variant === 'react-pdf-preview'
  811. )
  812. const showPdfDetach = shouldDisplayFeature(
  813. 'pdf_detach',
  814. user.alphaProgram
  815. )
  816. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  817. let detachRole = null
  818. if (showPdfDetach) {
  819. showNewPdfPreview = true
  820. detachRole = req.params.detachRole
  821. }
  822. res.render('project/editor', {
  823. title: project.name,
  824. priority_title: true,
  825. bodyClasses: ['editor'],
  826. project_id: project._id,
  827. user: {
  828. id: userId,
  829. email: user.email,
  830. first_name: user.first_name,
  831. last_name: user.last_name,
  832. referal_id: user.referal_id,
  833. signUpDate: user.signUpDate,
  834. allowedFreeTrial: allowedFreeTrial,
  835. featureSwitches: user.featureSwitches,
  836. features: user.features,
  837. refProviders: _.mapValues(user.refProviders, Boolean),
  838. alphaProgram: user.alphaProgram,
  839. betaProgram: user.betaProgram,
  840. isAdmin: user.isAdmin,
  841. },
  842. userSettings: {
  843. mode: user.ace.mode,
  844. editorTheme: user.ace.theme,
  845. fontSize: user.ace.fontSize,
  846. autoComplete: user.ace.autoComplete,
  847. autoPairDelimiters: user.ace.autoPairDelimiters,
  848. pdfViewer: user.ace.pdfViewer,
  849. syntaxValidation: user.ace.syntaxValidation,
  850. fontFamily: user.ace.fontFamily || 'lucida',
  851. lineHeight: user.ace.lineHeight || 'normal',
  852. overallTheme: user.ace.overallTheme,
  853. },
  854. privilegeLevel,
  855. anonymous,
  856. anonymousAccessToken: anonymous ? anonRequestToken : null,
  857. isTokenMember,
  858. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  859. userId,
  860. privilegeLevel,
  861. isTokenMember
  862. ),
  863. languages: Settings.languages,
  864. learnedWords,
  865. editorThemes: THEME_LIST,
  866. maxDocLength: Settings.max_doc_length,
  867. useV2History:
  868. project.overleaf &&
  869. project.overleaf.history &&
  870. Boolean(project.overleaf.history.display),
  871. brandVariation,
  872. allowedImageNames,
  873. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  874. wsUrl,
  875. showSupport: Features.hasFeature('support'),
  876. showNewLogsUI: shouldDisplayFeature(
  877. 'new_logs_ui',
  878. logsUIVariant.newLogsUI
  879. ),
  880. logsUISubvariant: logsUIVariant.subvariant,
  881. showPdfDetach,
  882. debugPdfDetach,
  883. showNewPdfPreview,
  884. showNewSourceEditor: shouldDisplayFeature(
  885. 'new_source_editor',
  886. false
  887. ),
  888. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  889. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  890. resetServiceWorker:
  891. Boolean(Settings.resetServiceWorker) &&
  892. !shouldDisplayFeature('enable_pdf_caching', false),
  893. detachRole,
  894. metadata: { viewport: false },
  895. })
  896. timer.done()
  897. }
  898. )
  899. }
  900. )
  901. },
  902. _refreshFeatures(req, user, callback) {
  903. // If the feature refresh has failed in this session, don't retry
  904. // it - require the user to log in again.
  905. if (req.session.feature_refresh_failed) {
  906. metrics.inc('features-refresh', 1, {
  907. path: 'load-editor',
  908. status: 'skipped',
  909. })
  910. return callback(null, user)
  911. }
  912. // If the refresh takes too long then return the current
  913. // features. Note that the user.features property may still be
  914. // updated in the background after the callback is called.
  915. callback = _.once(callback)
  916. const refreshTimeoutHandler = setTimeout(() => {
  917. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  918. metrics.inc('features-refresh', 1, {
  919. path: 'load-editor',
  920. status: 'timeout',
  921. })
  922. callback(null, user)
  923. }, 5000)
  924. // try to refresh user features now
  925. const timer = new metrics.Timer('features-refresh-on-load-editor')
  926. FeaturesUpdater.refreshFeatures(
  927. user._id,
  928. 'load-editor',
  929. (err, features) => {
  930. clearTimeout(refreshTimeoutHandler)
  931. timer.done()
  932. if (err) {
  933. // keep a record to prevent unneceary retries and leave
  934. // the original features unmodified if the refresh failed
  935. req.session.feature_refresh_failed = {
  936. reason: 'error',
  937. at: new Date(),
  938. }
  939. metrics.inc('features-refresh', 1, {
  940. path: 'load-editor',
  941. status: 'error',
  942. })
  943. } else {
  944. user.features = features
  945. metrics.inc('features-refresh', 1, {
  946. path: 'load-editor',
  947. status: 'success',
  948. })
  949. }
  950. return callback(null, user)
  951. }
  952. )
  953. },
  954. _buildProjectList(allProjects, userId) {
  955. let project
  956. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  957. allProjects
  958. const projects = []
  959. for (project of owned) {
  960. projects.push(
  961. ProjectController._buildProjectViewModel(
  962. project,
  963. 'owner',
  964. Sources.OWNER,
  965. userId
  966. )
  967. )
  968. }
  969. // Invite-access
  970. for (project of readAndWrite) {
  971. projects.push(
  972. ProjectController._buildProjectViewModel(
  973. project,
  974. 'readWrite',
  975. Sources.INVITE,
  976. userId
  977. )
  978. )
  979. }
  980. for (project of readOnly) {
  981. projects.push(
  982. ProjectController._buildProjectViewModel(
  983. project,
  984. 'readOnly',
  985. Sources.INVITE,
  986. userId
  987. )
  988. )
  989. }
  990. // Token-access
  991. // Only add these projects if they're not already present, this gives us cascading access
  992. // from 'owner' => 'token-read-only'
  993. for (project of tokenReadAndWrite) {
  994. if (
  995. projects.filter(p => p.id.toString() === project._id.toString())
  996. .length === 0
  997. ) {
  998. projects.push(
  999. ProjectController._buildProjectViewModel(
  1000. project,
  1001. 'readAndWrite',
  1002. Sources.TOKEN,
  1003. userId
  1004. )
  1005. )
  1006. }
  1007. }
  1008. for (project of tokenReadOnly) {
  1009. if (
  1010. projects.filter(p => p.id.toString() === project._id.toString())
  1011. .length === 0
  1012. ) {
  1013. projects.push(
  1014. ProjectController._buildProjectViewModel(
  1015. project,
  1016. 'readOnly',
  1017. Sources.TOKEN,
  1018. userId
  1019. )
  1020. )
  1021. }
  1022. }
  1023. return projects
  1024. },
  1025. _buildProjectViewModel(project, accessLevel, source, userId) {
  1026. const archived = ProjectHelper.isArchived(project, userId)
  1027. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1028. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1029. TokenAccessHandler.protectTokens(project, accessLevel)
  1030. const model = {
  1031. id: project._id,
  1032. name: project.name,
  1033. lastUpdated: project.lastUpdated,
  1034. lastUpdatedBy: project.lastUpdatedBy,
  1035. publicAccessLevel: project.publicAccesLevel,
  1036. accessLevel,
  1037. source,
  1038. archived,
  1039. trashed,
  1040. owner_ref: project.owner_ref,
  1041. isV1Project: false,
  1042. }
  1043. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1044. model.owner_ref = null
  1045. model.lastUpdatedBy = null
  1046. }
  1047. return model
  1048. },
  1049. _injectProjectUsers(projects, callback) {
  1050. const users = {}
  1051. for (const project of projects) {
  1052. if (project.owner_ref != null) {
  1053. users[project.owner_ref.toString()] = true
  1054. }
  1055. if (project.lastUpdatedBy != null) {
  1056. users[project.lastUpdatedBy.toString()] = true
  1057. }
  1058. }
  1059. const userIds = Object.keys(users)
  1060. async.eachSeries(
  1061. userIds,
  1062. (userId, cb) => {
  1063. UserGetter.getUser(
  1064. userId,
  1065. { first_name: 1, last_name: 1, email: 1 },
  1066. (error, user) => {
  1067. if (error != null) {
  1068. return cb(error)
  1069. }
  1070. users[userId] = user
  1071. cb()
  1072. }
  1073. )
  1074. },
  1075. error => {
  1076. if (error != null) {
  1077. return callback(error)
  1078. }
  1079. for (const project of projects) {
  1080. if (project.owner_ref != null) {
  1081. project.owner = users[project.owner_ref.toString()]
  1082. }
  1083. if (project.lastUpdatedBy != null) {
  1084. project.lastUpdatedBy =
  1085. users[project.lastUpdatedBy.toString()] || null
  1086. }
  1087. }
  1088. callback(null, projects)
  1089. }
  1090. )
  1091. },
  1092. _buildPortalTemplatesList(affiliations) {
  1093. if (affiliations == null) {
  1094. affiliations = []
  1095. }
  1096. const portalTemplates = []
  1097. for (const aff of affiliations) {
  1098. if (
  1099. aff.portal &&
  1100. aff.portal.slug &&
  1101. aff.portal.templates_count &&
  1102. aff.portal.templates_count > 0
  1103. ) {
  1104. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1105. portalTemplates.push({
  1106. name: aff.institution.name,
  1107. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1108. })
  1109. }
  1110. }
  1111. return portalTemplates
  1112. },
  1113. }
  1114. const defaultSettingsForAnonymousUser = userId => ({
  1115. id: userId,
  1116. ace: {
  1117. mode: 'none',
  1118. theme: 'textmate',
  1119. fontSize: '12',
  1120. autoComplete: true,
  1121. spellCheckLanguage: '',
  1122. pdfViewer: '',
  1123. syntaxValidation: true,
  1124. },
  1125. subscription: {
  1126. freeTrial: {
  1127. allowed: true,
  1128. },
  1129. },
  1130. featureSwitches: {
  1131. github: false,
  1132. },
  1133. alphaProgram: false,
  1134. betaProgram: false,
  1135. })
  1136. const THEME_LIST = []
  1137. function generateThemeList() {
  1138. const files = fs.readdirSync(
  1139. Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
  1140. )
  1141. const result = []
  1142. for (const file of files) {
  1143. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1144. const cleanName = file.slice(0, -3).slice(6)
  1145. result.push(THEME_LIST.push(cleanName))
  1146. } else {
  1147. result.push(undefined)
  1148. }
  1149. }
  1150. }
  1151. generateThemeList()
  1152. module.exports = ProjectController