ProjectController.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  1. const _ = require('lodash')
  2. const OError = require('@overleaf/o-error')
  3. const crypto = require('crypto')
  4. const async = require('async')
  5. const logger = require('@overleaf/logger')
  6. const { ObjectId } = require('mongodb')
  7. const ProjectDeleter = require('./ProjectDeleter')
  8. const ProjectDuplicator = require('./ProjectDuplicator')
  9. const ProjectCreationHandler = require('./ProjectCreationHandler')
  10. const EditorController = require('../Editor/EditorController')
  11. const ProjectHelper = require('./ProjectHelper')
  12. const metrics = require('@overleaf/metrics')
  13. const { User } = require('../../models/User')
  14. const TagsHandler = require('../Tags/TagsHandler')
  15. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  16. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  17. const LimitationsManager = require('../Subscription/LimitationsManager')
  18. const Settings = require('@overleaf/settings')
  19. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  20. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  21. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  22. const ProjectGetter = require('./ProjectGetter')
  23. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  24. const SessionManager = require('../Authentication/SessionManager')
  25. const Sources = require('../Authorization/Sources')
  26. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  27. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  28. const ProjectEntityHandler = require('./ProjectEntityHandler')
  29. const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
  30. const UserGetter = require('../User/UserGetter')
  31. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  32. const { V1ConnectionError } = require('../Errors/Errors')
  33. const Features = require('../../infrastructure/Features')
  34. const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
  35. const UserController = require('../User/UserController')
  36. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  37. const Modules = require('../../infrastructure/Modules')
  38. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  39. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  40. const SpellingHandler = require('../Spelling/SpellingHandler')
  41. const UserPrimaryEmailCheckHandler = require('../User/UserPrimaryEmailCheckHandler')
  42. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  43. if (!affiliation.institution) return false
  44. // institution.confirmed is for the domain being confirmed, not the email
  45. // Do not show SSO UI for unconfirmed domains
  46. if (!affiliation.institution.confirmed) return false
  47. // Could have multiple emails at the same institution, and if any are
  48. // linked to the institution then do not show notification for others
  49. if (
  50. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  51. ) {
  52. if (affiliation.institution.ssoEnabled) return true
  53. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  54. return false
  55. }
  56. return false
  57. }
  58. const ProjectController = {
  59. _isInPercentageRollout(rolloutName, objectId, percentage) {
  60. if (Settings.bypassPercentageRollouts === true) {
  61. return true
  62. }
  63. const data = `${rolloutName}:${objectId.toString()}`
  64. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  65. const counter = parseInt(md5hash.slice(26, 32), 16)
  66. return counter % 100 < percentage
  67. },
  68. updateProjectSettings(req, res, next) {
  69. const projectId = req.params.Project_id
  70. const jobs = []
  71. if (req.body.compiler != null) {
  72. jobs.push(callback =>
  73. EditorController.setCompiler(projectId, req.body.compiler, callback)
  74. )
  75. }
  76. if (req.body.imageName != null) {
  77. jobs.push(callback =>
  78. EditorController.setImageName(projectId, req.body.imageName, callback)
  79. )
  80. }
  81. if (req.body.name != null) {
  82. jobs.push(callback =>
  83. EditorController.renameProject(projectId, req.body.name, callback)
  84. )
  85. }
  86. if (req.body.spellCheckLanguage != null) {
  87. jobs.push(callback =>
  88. EditorController.setSpellCheckLanguage(
  89. projectId,
  90. req.body.spellCheckLanguage,
  91. callback
  92. )
  93. )
  94. }
  95. if (req.body.rootDocId != null) {
  96. jobs.push(callback =>
  97. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  98. )
  99. }
  100. async.series(jobs, error => {
  101. if (error != null) {
  102. return next(error)
  103. }
  104. res.sendStatus(204)
  105. })
  106. },
  107. updateProjectAdminSettings(req, res, next) {
  108. const projectId = req.params.Project_id
  109. const jobs = []
  110. if (req.body.publicAccessLevel != null) {
  111. jobs.push(callback =>
  112. EditorController.setPublicAccessLevel(
  113. projectId,
  114. req.body.publicAccessLevel,
  115. callback
  116. )
  117. )
  118. }
  119. async.series(jobs, error => {
  120. if (error != null) {
  121. return next(error)
  122. }
  123. res.sendStatus(204)
  124. })
  125. },
  126. deleteProject(req, res) {
  127. const projectId = req.params.Project_id
  128. const user = SessionManager.getSessionUser(req.session)
  129. const cb = err => {
  130. if (err != null) {
  131. res.sendStatus(500)
  132. } else {
  133. res.sendStatus(200)
  134. }
  135. }
  136. ProjectDeleter.deleteProject(
  137. projectId,
  138. { deleterUser: user, ipAddress: req.ip },
  139. cb
  140. )
  141. },
  142. archiveProject(req, res, next) {
  143. const projectId = req.params.Project_id
  144. const userId = SessionManager.getLoggedInUserId(req.session)
  145. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  146. if (err != null) {
  147. return next(err)
  148. } else {
  149. return res.sendStatus(200)
  150. }
  151. })
  152. },
  153. unarchiveProject(req, res, next) {
  154. const projectId = req.params.Project_id
  155. const userId = SessionManager.getLoggedInUserId(req.session)
  156. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  157. if (err != null) {
  158. return next(err)
  159. } else {
  160. return res.sendStatus(200)
  161. }
  162. })
  163. },
  164. trashProject(req, res, next) {
  165. const projectId = req.params.project_id
  166. const userId = SessionManager.getLoggedInUserId(req.session)
  167. ProjectDeleter.trashProject(projectId, userId, function (err) {
  168. if (err != null) {
  169. return next(err)
  170. } else {
  171. return res.sendStatus(200)
  172. }
  173. })
  174. },
  175. untrashProject(req, res, next) {
  176. const projectId = req.params.project_id
  177. const userId = SessionManager.getLoggedInUserId(req.session)
  178. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  179. if (err != null) {
  180. return next(err)
  181. } else {
  182. return res.sendStatus(200)
  183. }
  184. })
  185. },
  186. expireDeletedProjectsAfterDuration(req, res) {
  187. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  188. if (err != null) {
  189. res.sendStatus(500)
  190. } else {
  191. res.sendStatus(200)
  192. }
  193. })
  194. },
  195. expireDeletedProject(req, res, next) {
  196. const { projectId } = req.params
  197. ProjectDeleter.expireDeletedProject(projectId, err => {
  198. if (err != null) {
  199. next(err)
  200. } else {
  201. res.sendStatus(200)
  202. }
  203. })
  204. },
  205. restoreProject(req, res) {
  206. const projectId = req.params.Project_id
  207. ProjectDeleter.restoreProject(projectId, err => {
  208. if (err != null) {
  209. res.sendStatus(500)
  210. } else {
  211. res.sendStatus(200)
  212. }
  213. })
  214. },
  215. cloneProject(req, res, next) {
  216. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  217. metrics.inc('cloned-project')
  218. const projectId = req.params.Project_id
  219. const { projectName } = req.body
  220. logger.log({ projectId, projectName }, 'cloning project')
  221. if (!SessionManager.isUserLoggedIn(req.session)) {
  222. return res.json({ redir: '/register' })
  223. }
  224. const currentUser = SessionManager.getSessionUser(req.session)
  225. const { first_name: firstName, last_name: lastName, email } = currentUser
  226. ProjectDuplicator.duplicate(
  227. currentUser,
  228. projectId,
  229. projectName,
  230. (err, project) => {
  231. if (err != null) {
  232. OError.tag(err, 'error cloning project', {
  233. projectId,
  234. userId: currentUser._id,
  235. })
  236. return next(err)
  237. }
  238. res.json({
  239. name: project.name,
  240. project_id: project._id,
  241. owner_ref: project.owner_ref,
  242. owner: {
  243. first_name: firstName,
  244. last_name: lastName,
  245. email,
  246. _id: currentUser._id,
  247. },
  248. })
  249. }
  250. )
  251. },
  252. newProject(req, res, next) {
  253. const currentUser = SessionManager.getSessionUser(req.session)
  254. const {
  255. first_name: firstName,
  256. last_name: lastName,
  257. email,
  258. _id: userId,
  259. } = currentUser
  260. const projectName =
  261. req.body.projectName != null ? req.body.projectName.trim() : undefined
  262. const { template } = req.body
  263. async.waterfall(
  264. [
  265. cb => {
  266. if (template === 'example') {
  267. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  268. } else {
  269. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  270. }
  271. },
  272. ],
  273. (err, project) => {
  274. if (err != null) {
  275. return next(err)
  276. }
  277. res.json({
  278. project_id: project._id,
  279. owner_ref: project.owner_ref,
  280. owner: {
  281. first_name: firstName,
  282. last_name: lastName,
  283. email,
  284. _id: userId,
  285. },
  286. })
  287. }
  288. )
  289. },
  290. renameProject(req, res, next) {
  291. const projectId = req.params.Project_id
  292. const newName = req.body.newProjectName
  293. EditorController.renameProject(projectId, newName, err => {
  294. if (err != null) {
  295. return next(err)
  296. }
  297. res.sendStatus(200)
  298. })
  299. },
  300. userProjectsJson(req, res, next) {
  301. const userId = SessionManager.getLoggedInUserId(req.session)
  302. ProjectGetter.findAllUsersProjects(
  303. userId,
  304. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  305. (err, projects) => {
  306. if (err != null) {
  307. return next(err)
  308. }
  309. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  310. projects = ProjectController._buildProjectList(projects, userId)
  311. .filter(p => !(p.archived || p.trashed))
  312. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  313. res.json({ projects })
  314. }
  315. )
  316. },
  317. projectEntitiesJson(req, res, next) {
  318. const projectId = req.params.Project_id
  319. ProjectGetter.getProject(projectId, (err, project) => {
  320. if (err != null) {
  321. return next(err)
  322. }
  323. const { docs, files } =
  324. ProjectEntityHandler.getAllEntitiesFromProject(project)
  325. const entities = docs
  326. .concat(files)
  327. // Sort by path ascending
  328. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  329. .map(e => ({
  330. path: e.path,
  331. type: e.doc != null ? 'doc' : 'file',
  332. }))
  333. res.json({ project_id: projectId, entities })
  334. })
  335. },
  336. projectListPage(req, res, next) {
  337. const timer = new metrics.Timer('project-list')
  338. const userId = SessionManager.getLoggedInUserId(req.session)
  339. const currentUser = SessionManager.getSessionUser(req.session)
  340. async.parallel(
  341. {
  342. tags(cb) {
  343. TagsHandler.getAllTags(userId, cb)
  344. },
  345. notifications(cb) {
  346. NotificationsHandler.getUserNotifications(userId, cb)
  347. },
  348. projects(cb) {
  349. ProjectGetter.findAllUsersProjects(
  350. userId,
  351. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  352. cb
  353. )
  354. },
  355. hasSubscription(cb) {
  356. LimitationsManager.hasPaidSubscription(
  357. currentUser,
  358. (error, hasPaidSubscription) => {
  359. if (error != null && error instanceof V1ConnectionError) {
  360. return cb(null, true)
  361. }
  362. cb(error, hasPaidSubscription)
  363. }
  364. )
  365. },
  366. user(cb) {
  367. User.findById(
  368. userId,
  369. 'email emails featureSwitches overleaf awareOfV2 features lastLoginIp lastPrimaryEmailCheck signUpDate',
  370. cb
  371. )
  372. },
  373. userEmailsData(cb) {
  374. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  375. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  376. if (error && error instanceof V1ConnectionError) {
  377. return cb(null, result)
  378. }
  379. if (!Features.hasFeature('affiliations')) {
  380. result.list = fullEmails
  381. return cb(null, result)
  382. }
  383. Modules.hooks.fire(
  384. 'allInReconfirmNotificationPeriodsForUser',
  385. fullEmails,
  386. (error, results) => {
  387. if (error != null) {
  388. return cb(error)
  389. }
  390. // Module.hooks.fire accepts multiple methods
  391. // and does async.series
  392. const allInReconfirmNotificationPeriods =
  393. (results && results[0]) || []
  394. return cb(null, {
  395. list: fullEmails,
  396. allInReconfirmNotificationPeriods,
  397. })
  398. }
  399. )
  400. })
  401. },
  402. primaryEmailCheckActive(cb) {
  403. SplitTestHandler.getAssignment(
  404. req,
  405. 'primary-email-check',
  406. (err, assignment) => {
  407. if (err) {
  408. logger.warn(
  409. { err },
  410. 'failed to get "primary-email-check" split test assignment'
  411. )
  412. cb(null, false)
  413. } else {
  414. cb(null, assignment.variant === 'active')
  415. }
  416. }
  417. )
  418. },
  419. },
  420. (err, results) => {
  421. if (err != null) {
  422. OError.tag(err, 'error getting data for project list page')
  423. return next(err)
  424. }
  425. const { notifications, user, userEmailsData, primaryEmailCheckActive } =
  426. results
  427. if (
  428. user &&
  429. primaryEmailCheckActive &&
  430. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)
  431. ) {
  432. return res.redirect('/user/emails/primary-email-check')
  433. }
  434. const userEmails = userEmailsData.list || []
  435. const userAffiliations = userEmails
  436. .filter(emailData => !!emailData.affiliation)
  437. .map(emailData => {
  438. const result = emailData.affiliation
  439. result.email = emailData.email
  440. return result
  441. })
  442. const { allInReconfirmNotificationPeriods } = userEmailsData
  443. // Handle case of deleted user
  444. if (user == null) {
  445. UserController.logout(req, res, next)
  446. return
  447. }
  448. const tags = results.tags
  449. const notificationsInstitution = []
  450. for (const notification of notifications) {
  451. notification.html = req.i18n.translate(
  452. notification.templateKey,
  453. notification.messageOpts
  454. )
  455. }
  456. // Institution SSO Notifications
  457. let reconfirmedViaSAML
  458. if (Features.hasFeature('saml')) {
  459. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  460. const samlSession = req.session.saml
  461. // Notification: SSO Available
  462. const linkedInstitutionIds = []
  463. user.emails.forEach(email => {
  464. if (email.samlProviderId) {
  465. linkedInstitutionIds.push(email.samlProviderId)
  466. }
  467. })
  468. if (Array.isArray(userAffiliations)) {
  469. userAffiliations.forEach(affiliation => {
  470. if (
  471. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  472. ) {
  473. notificationsInstitution.push({
  474. email: affiliation.email,
  475. institutionId: affiliation.institution.id,
  476. institutionName: affiliation.institution.name,
  477. templateKey: 'notification_institution_sso_available',
  478. })
  479. }
  480. })
  481. }
  482. if (samlSession) {
  483. // Notification: After SSO Linked
  484. if (samlSession.linked) {
  485. notificationsInstitution.push({
  486. email: samlSession.institutionEmail,
  487. institutionName: samlSession.linked.universityName,
  488. templateKey: 'notification_institution_sso_linked',
  489. })
  490. }
  491. // Notification: After SSO Linked or Logging in
  492. // The requested email does not match primary email returned from
  493. // the institution
  494. if (
  495. samlSession.requestedEmail &&
  496. samlSession.emailNonCanonical &&
  497. !samlSession.error
  498. ) {
  499. notificationsInstitution.push({
  500. institutionEmail: samlSession.emailNonCanonical,
  501. requestedEmail: samlSession.requestedEmail,
  502. templateKey: 'notification_institution_sso_non_canonical',
  503. })
  504. }
  505. // Notification: Tried to register, but account already existed
  506. // registerIntercept is set before the institution callback.
  507. // institutionEmail is set after institution callback.
  508. // Check for both in case SSO flow was abandoned
  509. if (
  510. samlSession.registerIntercept &&
  511. samlSession.institutionEmail &&
  512. !samlSession.error
  513. ) {
  514. notificationsInstitution.push({
  515. email: samlSession.institutionEmail,
  516. templateKey: 'notification_institution_sso_already_registered',
  517. })
  518. }
  519. // Notification: When there is a session error
  520. if (samlSession.error) {
  521. notificationsInstitution.push({
  522. templateKey: 'notification_institution_sso_error',
  523. error: samlSession.error,
  524. })
  525. }
  526. }
  527. delete req.session.saml
  528. }
  529. const portalTemplates =
  530. ProjectController._buildPortalTemplatesList(userAffiliations)
  531. const projects = ProjectController._buildProjectList(
  532. results.projects,
  533. userId
  534. )
  535. // in v2 add notifications for matching university IPs
  536. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  537. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  538. req.ip,
  539. () => {}
  540. )
  541. }
  542. ProjectController._injectProjectUsers(projects, (error, projects) => {
  543. if (error != null) {
  544. return next(error)
  545. }
  546. const viewModel = {
  547. title: 'your_projects',
  548. priority_title: true,
  549. projects,
  550. tags,
  551. notifications: notifications || [],
  552. notificationsInstitution,
  553. allInReconfirmNotificationPeriods,
  554. portalTemplates,
  555. user,
  556. userAffiliations,
  557. userEmails,
  558. hasSubscription: results.hasSubscription,
  559. reconfirmedViaSAML,
  560. zipFileSizeLimit: Settings.maxUploadSize,
  561. isOverleaf: !!Settings.overleaf,
  562. metadata: { viewport: false },
  563. }
  564. const paidUser =
  565. (user.features != null ? user.features.github : undefined) &&
  566. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  567. const freeUserProportion = 0.1
  568. const sampleFreeUser =
  569. parseInt(user._id.toString().slice(-2), 16) <
  570. freeUserProportion * 255
  571. const showFrontWidget = paidUser || sampleFreeUser
  572. if (showFrontWidget) {
  573. viewModel.frontChatWidgetRoomId =
  574. Settings.overleaf != null
  575. ? Settings.overleaf.front_chat_widget_room_id
  576. : undefined
  577. }
  578. // null test targeting logged in users
  579. SplitTestHandler.promises.getAssignment(req, 'null-test-dashboard')
  580. res.render('project/list', viewModel)
  581. timer.done()
  582. })
  583. }
  584. )
  585. },
  586. loadEditor(req, res, next) {
  587. const timer = new metrics.Timer('load-editor')
  588. if (!Settings.editorIsOpen) {
  589. return res.render('general/closed', { title: 'updating_site' })
  590. }
  591. let anonymous, userId, sessionUser
  592. if (SessionManager.isUserLoggedIn(req.session)) {
  593. sessionUser = SessionManager.getSessionUser(req.session)
  594. userId = SessionManager.getLoggedInUserId(req.session)
  595. anonymous = false
  596. } else {
  597. sessionUser = null
  598. anonymous = true
  599. userId = null
  600. }
  601. const projectId = req.params.Project_id
  602. async.auto(
  603. {
  604. project(cb) {
  605. ProjectGetter.getProject(
  606. projectId,
  607. {
  608. name: 1,
  609. lastUpdated: 1,
  610. track_changes: 1,
  611. owner_ref: 1,
  612. brandVariationId: 1,
  613. overleaf: 1,
  614. tokens: 1,
  615. },
  616. (err, project) => {
  617. if (err != null) {
  618. return cb(err)
  619. }
  620. cb(null, project)
  621. }
  622. )
  623. },
  624. user(cb) {
  625. if (userId == null) {
  626. cb(null, defaultSettingsForAnonymousUser(userId))
  627. } else {
  628. User.updateOne(
  629. { _id: ObjectId(userId) },
  630. { $set: { lastActive: new Date() } },
  631. {},
  632. () => {}
  633. )
  634. User.findById(
  635. userId,
  636. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace',
  637. (err, user) => {
  638. // Handle case of deleted user
  639. if (user == null) {
  640. UserController.logout(req, res, next)
  641. return
  642. }
  643. if (err) {
  644. return cb(err)
  645. }
  646. logger.log({ projectId, userId }, 'got user')
  647. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  648. return cb(null, user)
  649. }
  650. ProjectController._refreshFeatures(req, user, cb)
  651. }
  652. )
  653. }
  654. },
  655. learnedWords(cb) {
  656. if (!userId) {
  657. return cb(null, [])
  658. }
  659. SpellingHandler.getUserDictionary(userId, cb)
  660. },
  661. subscription(cb) {
  662. if (userId == null) {
  663. return cb()
  664. }
  665. SubscriptionLocator.getUsersSubscription(userId, cb)
  666. },
  667. activate(cb) {
  668. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  669. },
  670. markAsOpened(cb) {
  671. // don't need to wait for this to complete
  672. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  673. cb()
  674. },
  675. isTokenMember(cb) {
  676. if (userId == null) {
  677. return cb()
  678. }
  679. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  680. },
  681. brandVariation: [
  682. 'project',
  683. (cb, results) => {
  684. if (
  685. (results.project != null
  686. ? results.project.brandVariationId
  687. : undefined) == null
  688. ) {
  689. return cb()
  690. }
  691. BrandVariationsHandler.getBrandVariationById(
  692. results.project.brandVariationId,
  693. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  694. )
  695. },
  696. ],
  697. flushToTpds: cb => {
  698. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  699. },
  700. sharingModalSplitTest(cb) {
  701. SplitTestHandler.assignInLocalsContext(
  702. req,
  703. res,
  704. 'project-share-modal-paywall',
  705. {},
  706. () => {
  707. // do not fail editor load if assignment fails
  708. cb()
  709. }
  710. )
  711. },
  712. sharingModalNullTest(cb) {
  713. // null test targeting logged in users, for front-end side
  714. SplitTestHandler.assignInLocalsContext(
  715. req,
  716. res,
  717. 'null-test-share-modal',
  718. {},
  719. () => {
  720. // do not fail editor load if assignment fails
  721. cb()
  722. }
  723. )
  724. },
  725. newPdfPreviewAssignment(cb) {
  726. SplitTestHandler.getAssignment(
  727. req,
  728. 'react-pdf-preview-rollout',
  729. {},
  730. (error, assignment) => {
  731. if (error) {
  732. // do not fail editor load if assignment fails
  733. cb(null, { variant: 'default' })
  734. } else {
  735. cb(null, assignment)
  736. }
  737. }
  738. )
  739. },
  740. newSourceEditorAssignment(cb) {
  741. SplitTestHandler.getAssignment(
  742. req,
  743. 'source-editor',
  744. {},
  745. (error, assignment) => {
  746. // do not fail editor load if assignment fails
  747. if (error) {
  748. cb(null)
  749. } else {
  750. cb(null, assignment)
  751. }
  752. }
  753. )
  754. },
  755. pdfDetachAssignment(cb) {
  756. SplitTestHandler.getAssignment(
  757. req,
  758. 'pdf-detach',
  759. {},
  760. (error, assignment) => {
  761. // do not fail editor load if assignment fails
  762. if (error) {
  763. cb(null)
  764. } else {
  765. cb(null, assignment)
  766. }
  767. }
  768. )
  769. },
  770. logsUIAssignment(cb) {
  771. SplitTestHandler.getAssignment(
  772. req,
  773. 'logs-ui',
  774. {},
  775. (error, assignment) => {
  776. // do not fail editor load if assignment fails
  777. if (error) {
  778. cb(null, { variant: 'default' })
  779. } else {
  780. cb(null, assignment)
  781. }
  782. }
  783. )
  784. },
  785. },
  786. (
  787. err,
  788. {
  789. project,
  790. user,
  791. learnedWords,
  792. subscription,
  793. isTokenMember,
  794. brandVariation,
  795. newPdfPreviewAssignment,
  796. newSourceEditorAssignment,
  797. pdfDetachAssignment,
  798. logsUIAssignment,
  799. }
  800. ) => {
  801. if (err != null) {
  802. OError.tag(err, 'error getting details for project page')
  803. return next(err)
  804. }
  805. const anonRequestToken = TokenAccessHandler.getRequestToken(
  806. req,
  807. projectId
  808. )
  809. const allowedImageNames =
  810. ProjectHelper.getAllowedImagesForUser(sessionUser)
  811. AuthorizationManager.getPrivilegeLevelForProject(
  812. userId,
  813. projectId,
  814. anonRequestToken,
  815. (error, privilegeLevel) => {
  816. let allowedFreeTrial = true
  817. if (error != null) {
  818. return next(error)
  819. }
  820. if (
  821. privilegeLevel == null ||
  822. privilegeLevel === PrivilegeLevels.NONE
  823. ) {
  824. return res.sendStatus(401)
  825. }
  826. if (subscription != null) {
  827. allowedFreeTrial = false
  828. }
  829. let wsUrl = Settings.wsUrl
  830. let metricName = 'load-editor-ws'
  831. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  832. wsUrl = Settings.wsUrlBeta
  833. metricName += '-beta'
  834. } else if (
  835. Settings.wsUrlV2 &&
  836. Settings.wsUrlV2Percentage > 0 &&
  837. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  838. Settings.wsUrlV2Percentage
  839. ) {
  840. wsUrl = Settings.wsUrlV2
  841. metricName += '-v2'
  842. }
  843. if (req.query && req.query.ws === 'fallback') {
  844. // `?ws=fallback` will connect to the bare origin, and ignore
  845. // the custom wsUrl. Hence it must load the client side
  846. // javascript from there too.
  847. // Not resetting it here would possibly load a socket.io v2
  848. // client and connect to a v0 endpoint.
  849. wsUrl = undefined
  850. metricName += '-fallback'
  851. }
  852. metrics.inc(metricName)
  853. if (userId) {
  854. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  855. projectId: project._id,
  856. })
  857. }
  858. function shouldDisplayFeature(name, variantFlag) {
  859. if (req.query && req.query[name]) {
  860. return req.query[name] === 'true'
  861. } else {
  862. return variantFlag === true
  863. }
  864. }
  865. function partOfPdfCachingRollout(flag) {
  866. if (!Settings.enablePdfCaching) {
  867. // The feature is disabled globally.
  868. return false
  869. }
  870. // Let the user opt-in only.
  871. // The flag will opt-out of both caching and metrics collection,
  872. // as if this editing session never happened.
  873. return shouldDisplayFeature('enable_pdf_caching', false)
  874. }
  875. let showNewPdfPreview = shouldDisplayFeature(
  876. 'new_pdf_preview',
  877. newPdfPreviewAssignment.variant === 'react-pdf-preview'
  878. )
  879. const showPdfDetach = shouldDisplayFeature(
  880. 'pdf_detach',
  881. pdfDetachAssignment.variant === 'enabled'
  882. )
  883. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  884. let detachRole = null
  885. if (showPdfDetach) {
  886. showNewPdfPreview = true
  887. detachRole = req.params.detachRole
  888. }
  889. const showNewSourceEditor =
  890. (newSourceEditorAssignment &&
  891. newSourceEditorAssignment.variant === 'codemirror') ||
  892. shouldDisplayFeature('new_source_editor', false) // also allow override via ?new_source_editor=true
  893. res.render('project/editor', {
  894. title: project.name,
  895. priority_title: true,
  896. bodyClasses: ['editor'],
  897. project_id: project._id,
  898. user: {
  899. id: userId,
  900. email: user.email,
  901. first_name: user.first_name,
  902. last_name: user.last_name,
  903. referal_id: user.referal_id,
  904. signUpDate: user.signUpDate,
  905. allowedFreeTrial: allowedFreeTrial,
  906. featureSwitches: user.featureSwitches,
  907. features: user.features,
  908. refProviders: _.mapValues(user.refProviders, Boolean),
  909. alphaProgram: user.alphaProgram,
  910. betaProgram: user.betaProgram,
  911. isAdmin: user.isAdmin,
  912. },
  913. userSettings: {
  914. mode: user.ace.mode,
  915. editorTheme: user.ace.theme,
  916. fontSize: user.ace.fontSize,
  917. autoComplete: user.ace.autoComplete,
  918. autoPairDelimiters: user.ace.autoPairDelimiters,
  919. pdfViewer: user.ace.pdfViewer,
  920. syntaxValidation: user.ace.syntaxValidation,
  921. fontFamily: user.ace.fontFamily || 'lucida',
  922. lineHeight: user.ace.lineHeight || 'normal',
  923. overallTheme: user.ace.overallTheme,
  924. },
  925. privilegeLevel,
  926. anonymous,
  927. anonymousAccessToken: anonymous ? anonRequestToken : null,
  928. isTokenMember,
  929. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  930. userId,
  931. privilegeLevel,
  932. isTokenMember
  933. ),
  934. languages: Settings.languages,
  935. learnedWords,
  936. editorThemes: THEME_LIST,
  937. maxDocLength: Settings.max_doc_length,
  938. useV2History:
  939. project.overleaf &&
  940. project.overleaf.history &&
  941. Boolean(project.overleaf.history.display),
  942. brandVariation,
  943. allowedImageNames,
  944. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  945. wsUrl,
  946. showSupport: Features.hasFeature('support'),
  947. logsUIVariant: logsUIAssignment.variant,
  948. showPdfDetach,
  949. debugPdfDetach,
  950. showNewPdfPreview,
  951. showNewSourceEditor,
  952. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  953. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  954. resetServiceWorker:
  955. Boolean(Settings.resetServiceWorker) &&
  956. !shouldDisplayFeature('enable_pdf_caching', false),
  957. detachRole,
  958. metadata: { viewport: false },
  959. })
  960. timer.done()
  961. }
  962. )
  963. }
  964. )
  965. },
  966. _refreshFeatures(req, user, callback) {
  967. // If the feature refresh has failed in this session, don't retry
  968. // it - require the user to log in again.
  969. if (req.session.feature_refresh_failed) {
  970. metrics.inc('features-refresh', 1, {
  971. path: 'load-editor',
  972. status: 'skipped',
  973. })
  974. return callback(null, user)
  975. }
  976. // If the refresh takes too long then return the current
  977. // features. Note that the user.features property may still be
  978. // updated in the background after the callback is called.
  979. callback = _.once(callback)
  980. const refreshTimeoutHandler = setTimeout(() => {
  981. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  982. metrics.inc('features-refresh', 1, {
  983. path: 'load-editor',
  984. status: 'timeout',
  985. })
  986. callback(null, user)
  987. }, 5000)
  988. // try to refresh user features now
  989. const timer = new metrics.Timer('features-refresh-on-load-editor')
  990. FeaturesUpdater.refreshFeatures(
  991. user._id,
  992. 'load-editor',
  993. (err, features) => {
  994. clearTimeout(refreshTimeoutHandler)
  995. timer.done()
  996. if (err) {
  997. // keep a record to prevent unneceary retries and leave
  998. // the original features unmodified if the refresh failed
  999. req.session.feature_refresh_failed = {
  1000. reason: 'error',
  1001. at: new Date(),
  1002. }
  1003. metrics.inc('features-refresh', 1, {
  1004. path: 'load-editor',
  1005. status: 'error',
  1006. })
  1007. } else {
  1008. user.features = features
  1009. metrics.inc('features-refresh', 1, {
  1010. path: 'load-editor',
  1011. status: 'success',
  1012. })
  1013. }
  1014. return callback(null, user)
  1015. }
  1016. )
  1017. },
  1018. _buildProjectList(allProjects, userId) {
  1019. let project
  1020. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  1021. allProjects
  1022. const projects = []
  1023. for (project of owned) {
  1024. projects.push(
  1025. ProjectController._buildProjectViewModel(
  1026. project,
  1027. 'owner',
  1028. Sources.OWNER,
  1029. userId
  1030. )
  1031. )
  1032. }
  1033. // Invite-access
  1034. for (project of readAndWrite) {
  1035. projects.push(
  1036. ProjectController._buildProjectViewModel(
  1037. project,
  1038. 'readWrite',
  1039. Sources.INVITE,
  1040. userId
  1041. )
  1042. )
  1043. }
  1044. for (project of readOnly) {
  1045. projects.push(
  1046. ProjectController._buildProjectViewModel(
  1047. project,
  1048. 'readOnly',
  1049. Sources.INVITE,
  1050. userId
  1051. )
  1052. )
  1053. }
  1054. // Token-access
  1055. // Only add these projects if they're not already present, this gives us cascading access
  1056. // from 'owner' => 'token-read-only'
  1057. for (project of tokenReadAndWrite) {
  1058. if (
  1059. projects.filter(p => p.id.toString() === project._id.toString())
  1060. .length === 0
  1061. ) {
  1062. projects.push(
  1063. ProjectController._buildProjectViewModel(
  1064. project,
  1065. 'readAndWrite',
  1066. Sources.TOKEN,
  1067. userId
  1068. )
  1069. )
  1070. }
  1071. }
  1072. for (project of tokenReadOnly) {
  1073. if (
  1074. projects.filter(p => p.id.toString() === project._id.toString())
  1075. .length === 0
  1076. ) {
  1077. projects.push(
  1078. ProjectController._buildProjectViewModel(
  1079. project,
  1080. 'readOnly',
  1081. Sources.TOKEN,
  1082. userId
  1083. )
  1084. )
  1085. }
  1086. }
  1087. return projects
  1088. },
  1089. _buildProjectViewModel(project, accessLevel, source, userId) {
  1090. const archived = ProjectHelper.isArchived(project, userId)
  1091. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1092. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1093. TokenAccessHandler.protectTokens(project, accessLevel)
  1094. const model = {
  1095. id: project._id,
  1096. name: project.name,
  1097. lastUpdated: project.lastUpdated,
  1098. lastUpdatedBy: project.lastUpdatedBy,
  1099. publicAccessLevel: project.publicAccesLevel,
  1100. accessLevel,
  1101. source,
  1102. archived,
  1103. trashed,
  1104. owner_ref: project.owner_ref,
  1105. isV1Project: false,
  1106. }
  1107. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1108. model.owner_ref = null
  1109. model.lastUpdatedBy = null
  1110. }
  1111. return model
  1112. },
  1113. _injectProjectUsers(projects, callback) {
  1114. const users = {}
  1115. for (const project of projects) {
  1116. if (project.owner_ref != null) {
  1117. users[project.owner_ref.toString()] = true
  1118. }
  1119. if (project.lastUpdatedBy != null) {
  1120. users[project.lastUpdatedBy.toString()] = true
  1121. }
  1122. }
  1123. const userIds = Object.keys(users)
  1124. async.eachSeries(
  1125. userIds,
  1126. (userId, cb) => {
  1127. UserGetter.getUser(
  1128. userId,
  1129. { first_name: 1, last_name: 1, email: 1 },
  1130. (error, user) => {
  1131. if (error != null) {
  1132. return cb(error)
  1133. }
  1134. users[userId] = user
  1135. cb()
  1136. }
  1137. )
  1138. },
  1139. error => {
  1140. if (error != null) {
  1141. return callback(error)
  1142. }
  1143. for (const project of projects) {
  1144. if (project.owner_ref != null) {
  1145. project.owner = users[project.owner_ref.toString()]
  1146. }
  1147. if (project.lastUpdatedBy != null) {
  1148. project.lastUpdatedBy =
  1149. users[project.lastUpdatedBy.toString()] || null
  1150. }
  1151. }
  1152. callback(null, projects)
  1153. }
  1154. )
  1155. },
  1156. _buildPortalTemplatesList(affiliations) {
  1157. if (affiliations == null) {
  1158. affiliations = []
  1159. }
  1160. const portalTemplates = []
  1161. for (const aff of affiliations) {
  1162. if (
  1163. aff.portal &&
  1164. aff.portal.slug &&
  1165. aff.portal.templates_count &&
  1166. aff.portal.templates_count > 0
  1167. ) {
  1168. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1169. portalTemplates.push({
  1170. name: aff.institution.name,
  1171. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1172. })
  1173. }
  1174. }
  1175. return portalTemplates
  1176. },
  1177. }
  1178. const defaultSettingsForAnonymousUser = userId => ({
  1179. id: userId,
  1180. ace: {
  1181. mode: 'none',
  1182. theme: 'textmate',
  1183. fontSize: '12',
  1184. autoComplete: true,
  1185. spellCheckLanguage: '',
  1186. pdfViewer: '',
  1187. syntaxValidation: true,
  1188. },
  1189. subscription: {
  1190. freeTrial: {
  1191. allowed: true,
  1192. },
  1193. },
  1194. featureSwitches: {
  1195. github: false,
  1196. },
  1197. alphaProgram: false,
  1198. betaProgram: false,
  1199. })
  1200. const THEME_LIST = [
  1201. 'ambiance',
  1202. 'chaos',
  1203. 'chrome',
  1204. 'clouds',
  1205. 'clouds_midnight',
  1206. 'cobalt',
  1207. 'crimson_editor',
  1208. 'dawn',
  1209. 'dracula',
  1210. 'dreamweaver',
  1211. 'eclipse',
  1212. 'github',
  1213. 'gob',
  1214. 'gruvbox',
  1215. 'idle_fingers',
  1216. 'iplastic',
  1217. 'katzenmilch',
  1218. 'kr_theme',
  1219. 'kuroir',
  1220. 'merbivore',
  1221. 'merbivore_soft',
  1222. 'mono_industrial',
  1223. 'monokai',
  1224. 'nord_dark',
  1225. 'overleaf',
  1226. 'pastel_on_dark',
  1227. 'solarized_dark',
  1228. 'solarized_light',
  1229. 'sqlserver',
  1230. 'terminal',
  1231. 'textmate',
  1232. 'tomorrow',
  1233. 'tomorrow_night',
  1234. 'tomorrow_night_blue',
  1235. 'tomorrow_night_bright',
  1236. 'tomorrow_night_eighties',
  1237. 'twilight',
  1238. 'vibrant_ink',
  1239. 'xcode',
  1240. ]
  1241. module.exports = ProjectController