ProjectController.js 38 KB

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