ProjectController.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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 { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
  43. const InstitutionsFeatures = require('../Institutions/InstitutionsFeatures')
  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.debug({ 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. 'email emails featureSwitches overleaf awareOfV2 features lastLoginIp lastPrimaryEmailCheck signUpDate',
  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. primaryEmailCheckActive(cb) {
  405. SplitTestHandler.getAssignment(
  406. req,
  407. res,
  408. 'primary-email-check',
  409. (err, assignment) => {
  410. if (err) {
  411. logger.warn(
  412. { err },
  413. 'failed to get "primary-email-check" split test assignment'
  414. )
  415. cb(null, false)
  416. } else {
  417. cb(null, assignment.variant === 'active')
  418. }
  419. }
  420. )
  421. },
  422. },
  423. (err, results) => {
  424. if (err != null) {
  425. OError.tag(err, 'error getting data for project list page')
  426. return next(err)
  427. }
  428. const { notifications, user, userEmailsData, primaryEmailCheckActive } =
  429. results
  430. if (
  431. user &&
  432. primaryEmailCheckActive &&
  433. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)
  434. ) {
  435. return res.redirect('/user/emails/primary-email-check')
  436. }
  437. const userEmails = userEmailsData.list || []
  438. const userAffiliations = userEmails
  439. .filter(emailData => !!emailData.affiliation)
  440. .map(emailData => {
  441. const result = emailData.affiliation
  442. result.email = emailData.email
  443. return result
  444. })
  445. const { allInReconfirmNotificationPeriods } = userEmailsData
  446. // Handle case of deleted user
  447. if (user == null) {
  448. UserController.logout(req, res, next)
  449. return
  450. }
  451. const tags = results.tags
  452. const notificationsInstitution = []
  453. for (const notification of notifications) {
  454. notification.html = req.i18n.translate(
  455. notification.templateKey,
  456. notification.messageOpts
  457. )
  458. }
  459. // Institution SSO Notifications
  460. let reconfirmedViaSAML
  461. if (Features.hasFeature('saml')) {
  462. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  463. const samlSession = req.session.saml
  464. // Notification: SSO Available
  465. const linkedInstitutionIds = []
  466. user.emails.forEach(email => {
  467. if (email.samlProviderId) {
  468. linkedInstitutionIds.push(email.samlProviderId)
  469. }
  470. })
  471. if (Array.isArray(userAffiliations)) {
  472. userAffiliations.forEach(affiliation => {
  473. if (
  474. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  475. ) {
  476. notificationsInstitution.push({
  477. email: affiliation.email,
  478. institutionId: affiliation.institution.id,
  479. institutionName: affiliation.institution.name,
  480. templateKey: 'notification_institution_sso_available',
  481. })
  482. }
  483. })
  484. }
  485. if (samlSession) {
  486. // Notification: After SSO Linked
  487. if (samlSession.linked) {
  488. notificationsInstitution.push({
  489. email: samlSession.institutionEmail,
  490. institutionName: samlSession.linked.universityName,
  491. templateKey: 'notification_institution_sso_linked',
  492. })
  493. }
  494. // Notification: After SSO Linked or Logging in
  495. // The requested email does not match primary email returned from
  496. // the institution
  497. if (
  498. samlSession.requestedEmail &&
  499. samlSession.emailNonCanonical &&
  500. !samlSession.error
  501. ) {
  502. notificationsInstitution.push({
  503. institutionEmail: samlSession.emailNonCanonical,
  504. requestedEmail: samlSession.requestedEmail,
  505. templateKey: 'notification_institution_sso_non_canonical',
  506. })
  507. }
  508. // Notification: Tried to register, but account already existed
  509. // registerIntercept is set before the institution callback.
  510. // institutionEmail is set after institution callback.
  511. // Check for both in case SSO flow was abandoned
  512. if (
  513. samlSession.registerIntercept &&
  514. samlSession.institutionEmail &&
  515. !samlSession.error
  516. ) {
  517. notificationsInstitution.push({
  518. email: samlSession.institutionEmail,
  519. templateKey: 'notification_institution_sso_already_registered',
  520. })
  521. }
  522. // Notification: When there is a session error
  523. if (samlSession.error) {
  524. notificationsInstitution.push({
  525. templateKey: 'notification_institution_sso_error',
  526. error: samlSession.error,
  527. })
  528. }
  529. }
  530. delete req.session.saml
  531. }
  532. const portalTemplates =
  533. ProjectController._buildPortalTemplatesList(userAffiliations)
  534. const projects = ProjectController._buildProjectList(
  535. results.projects,
  536. userId
  537. )
  538. // in v2 add notifications for matching university IPs
  539. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  540. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  541. req.ip,
  542. () => {}
  543. )
  544. }
  545. // Persistent upgrade prompts
  546. const showToolbarUpgradePrompt =
  547. !results.hasSubscription &&
  548. !userEmails.some(e => e.emailHasInstitutionLicence)
  549. ProjectController._injectProjectUsers(projects, (error, projects) => {
  550. if (error != null) {
  551. return next(error)
  552. }
  553. const viewModel = {
  554. title: 'your_projects',
  555. priority_title: true,
  556. projects,
  557. tags,
  558. notifications: notifications || [],
  559. notificationsInstitution,
  560. allInReconfirmNotificationPeriods,
  561. portalTemplates,
  562. user,
  563. userAffiliations,
  564. userEmails,
  565. hasSubscription: results.hasSubscription,
  566. reconfirmedViaSAML,
  567. zipFileSizeLimit: Settings.maxUploadSize,
  568. isOverleaf: !!Settings.overleaf,
  569. metadata: { viewport: false },
  570. showThinFooter: true, // don't show the fat footer on the projects dashboard, as there's a fixed space available
  571. showToolbarUpgradePrompt,
  572. }
  573. const paidUser =
  574. (user.features != null ? user.features.github : undefined) &&
  575. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  576. const freeUserProportion = 0.1
  577. const sampleFreeUser =
  578. parseInt(user._id.toString().slice(-2), 16) <
  579. freeUserProportion * 255
  580. const showFrontWidget = paidUser || sampleFreeUser
  581. if (showFrontWidget) {
  582. viewModel.frontChatWidgetRoomId =
  583. Settings.overleaf != null
  584. ? Settings.overleaf.front_chat_widget_room_id
  585. : undefined
  586. }
  587. // null test targeting logged in users
  588. SplitTestHandler.promises.getAssignment(
  589. req,
  590. res,
  591. 'null-test-dashboard'
  592. )
  593. res.render('project/list', viewModel)
  594. timer.done()
  595. })
  596. }
  597. )
  598. },
  599. loadEditor(req, res, next) {
  600. const timer = new metrics.Timer('load-editor')
  601. if (!Settings.editorIsOpen) {
  602. return res.render('general/closed', { title: 'updating_site' })
  603. }
  604. let anonymous, userId, sessionUser
  605. if (SessionManager.isUserLoggedIn(req.session)) {
  606. sessionUser = SessionManager.getSessionUser(req.session)
  607. userId = SessionManager.getLoggedInUserId(req.session)
  608. anonymous = false
  609. } else {
  610. sessionUser = null
  611. anonymous = true
  612. userId = null
  613. }
  614. const projectId = req.params.Project_id
  615. async.auto(
  616. {
  617. project(cb) {
  618. ProjectGetter.getProject(
  619. projectId,
  620. {
  621. name: 1,
  622. lastUpdated: 1,
  623. track_changes: 1,
  624. owner_ref: 1,
  625. brandVariationId: 1,
  626. overleaf: 1,
  627. tokens: 1,
  628. },
  629. (err, project) => {
  630. if (err != null) {
  631. return cb(err)
  632. }
  633. cb(null, project)
  634. }
  635. )
  636. },
  637. user(cb) {
  638. if (userId == null) {
  639. cb(null, defaultSettingsForAnonymousUser(userId))
  640. } else {
  641. User.updateOne(
  642. { _id: ObjectId(userId) },
  643. { $set: { lastActive: new Date() } },
  644. {},
  645. () => {}
  646. )
  647. User.findById(
  648. userId,
  649. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace',
  650. (err, user) => {
  651. // Handle case of deleted user
  652. if (user == null) {
  653. UserController.logout(req, res, next)
  654. return
  655. }
  656. if (err) {
  657. return cb(err)
  658. }
  659. logger.debug({ projectId, userId }, 'got user')
  660. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  661. return cb(null, user)
  662. }
  663. ProjectController._refreshFeatures(req, user, cb)
  664. }
  665. )
  666. }
  667. },
  668. userHasInstitutionLicence(cb) {
  669. if (!userId) {
  670. return cb(null, false)
  671. }
  672. InstitutionsFeatures.hasLicence(userId, (error, hasLicence) => {
  673. if (error) {
  674. // Don't fail if we can't get affiliation licences
  675. return cb(null, false)
  676. }
  677. cb(null, hasLicence)
  678. })
  679. },
  680. learnedWords(cb) {
  681. if (!userId) {
  682. return cb(null, [])
  683. }
  684. SpellingHandler.getUserDictionary(userId, cb)
  685. },
  686. subscription(cb) {
  687. if (userId == null) {
  688. return cb()
  689. }
  690. SubscriptionLocator.getUsersSubscription(userId, cb)
  691. },
  692. userIsMemberOfGroupSubscription(cb) {
  693. if (sessionUser == null) {
  694. return cb(null, false)
  695. }
  696. LimitationsManager.userIsMemberOfGroupSubscription(
  697. sessionUser,
  698. (error, isMember) => {
  699. cb(error, isMember)
  700. }
  701. )
  702. },
  703. activate(cb) {
  704. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  705. },
  706. markAsOpened(cb) {
  707. // don't need to wait for this to complete
  708. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  709. cb()
  710. },
  711. isTokenMember(cb) {
  712. if (userId == null) {
  713. return cb()
  714. }
  715. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  716. },
  717. brandVariation: [
  718. 'project',
  719. (cb, results) => {
  720. if (
  721. (results.project != null
  722. ? results.project.brandVariationId
  723. : undefined) == null
  724. ) {
  725. return cb()
  726. }
  727. BrandVariationsHandler.getBrandVariationById(
  728. results.project.brandVariationId,
  729. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  730. )
  731. },
  732. ],
  733. flushToTpds: cb => {
  734. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  735. },
  736. sharingModalSplitTest(cb) {
  737. SplitTestHandler.getAssignment(
  738. req,
  739. res,
  740. 'project-share-modal-paywall',
  741. {},
  742. () => {
  743. // do not fail editor load if assignment fails
  744. cb()
  745. }
  746. )
  747. },
  748. sharingModalNullTest(cb) {
  749. // null test targeting logged in users, for front-end side
  750. SplitTestHandler.getAssignment(
  751. req,
  752. res,
  753. 'null-test-share-modal',
  754. {},
  755. () => {
  756. // do not fail editor load if assignment fails
  757. cb()
  758. }
  759. )
  760. },
  761. newSourceEditorAssignment(cb) {
  762. SplitTestHandler.getAssignment(
  763. req,
  764. res,
  765. 'source-editor',
  766. {},
  767. (error, assignment) => {
  768. // do not fail editor load if assignment fails
  769. if (error) {
  770. cb(null)
  771. } else {
  772. cb(null, assignment)
  773. }
  774. }
  775. )
  776. },
  777. pdfDetachAssignment(cb) {
  778. SplitTestHandler.getAssignment(
  779. req,
  780. res,
  781. 'pdf-detach',
  782. {},
  783. (error, assignment) => {
  784. // do not fail editor load if assignment fails
  785. if (error) {
  786. cb(null)
  787. } else {
  788. cb(null, assignment)
  789. }
  790. }
  791. )
  792. },
  793. pdfjsAssignment(cb) {
  794. SplitTestHandler.getAssignment(
  795. req,
  796. res,
  797. 'pdfjs',
  798. {},
  799. (error, assignment) => {
  800. // do not fail editor load if assignment fails
  801. if (error) {
  802. cb(null, { variant: 'default' })
  803. } else {
  804. cb(null, assignment)
  805. }
  806. }
  807. )
  808. },
  809. dictionaryEditorAssignment(cb) {
  810. SplitTestHandler.getAssignment(
  811. req,
  812. res,
  813. 'dictionary-editor',
  814. {},
  815. (error, assignment) => {
  816. // do not fail editor load if assignment fails
  817. if (error) {
  818. cb(null, { variant: 'default' })
  819. } else {
  820. cb(null, assignment)
  821. }
  822. }
  823. )
  824. },
  825. },
  826. (
  827. err,
  828. {
  829. project,
  830. user,
  831. userHasInstitutionLicence,
  832. learnedWords,
  833. subscription,
  834. userIsMemberOfGroupSubscription,
  835. isTokenMember,
  836. brandVariation,
  837. newSourceEditorAssignment,
  838. pdfDetachAssignment,
  839. pdfjsAssignment,
  840. dictionaryEditorAssignment,
  841. }
  842. ) => {
  843. if (err != null) {
  844. OError.tag(err, 'error getting details for project page')
  845. return next(err)
  846. }
  847. const anonRequestToken = TokenAccessHandler.getRequestToken(
  848. req,
  849. projectId
  850. )
  851. const allowedImageNames =
  852. ProjectHelper.getAllowedImagesForUser(sessionUser)
  853. AuthorizationManager.getPrivilegeLevelForProject(
  854. userId,
  855. projectId,
  856. anonRequestToken,
  857. (error, privilegeLevel) => {
  858. let allowedFreeTrial = true
  859. if (error != null) {
  860. return next(error)
  861. }
  862. if (
  863. privilegeLevel == null ||
  864. privilegeLevel === PrivilegeLevels.NONE
  865. ) {
  866. return res.sendStatus(401)
  867. }
  868. if (subscription != null) {
  869. allowedFreeTrial = false
  870. }
  871. let wsUrl = Settings.wsUrl
  872. let metricName = 'load-editor-ws'
  873. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  874. wsUrl = Settings.wsUrlBeta
  875. metricName += '-beta'
  876. } else if (
  877. Settings.wsUrlV2 &&
  878. Settings.wsUrlV2Percentage > 0 &&
  879. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  880. Settings.wsUrlV2Percentage
  881. ) {
  882. wsUrl = Settings.wsUrlV2
  883. metricName += '-v2'
  884. }
  885. if (req.query && req.query.ws === 'fallback') {
  886. // `?ws=fallback` will connect to the bare origin, and ignore
  887. // the custom wsUrl. Hence it must load the client side
  888. // javascript from there too.
  889. // Not resetting it here would possibly load a socket.io v2
  890. // client and connect to a v0 endpoint.
  891. wsUrl = undefined
  892. metricName += '-fallback'
  893. }
  894. metrics.inc(metricName)
  895. if (userId) {
  896. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  897. projectId: project._id,
  898. })
  899. }
  900. function shouldDisplayFeature(name, variantFlag) {
  901. if (req.query && req.query[name]) {
  902. return req.query[name] === 'true'
  903. } else {
  904. return variantFlag === true
  905. }
  906. }
  907. function partOfPdfCachingRollout(flag) {
  908. if (!Settings.enablePdfCaching) {
  909. // The feature is disabled globally.
  910. return false
  911. }
  912. // Let the user opt-in only.
  913. // The flag will opt-out of both caching and metrics collection,
  914. // as if this editing session never happened.
  915. return shouldDisplayFeature('enable_pdf_caching', false)
  916. }
  917. const showPdfDetach = shouldDisplayFeature(
  918. 'pdf_detach',
  919. pdfDetachAssignment.variant === 'enabled'
  920. )
  921. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  922. let detachRole = null
  923. if (showPdfDetach) {
  924. detachRole = req.params.detachRole
  925. }
  926. const showNewSourceEditorOption =
  927. (newSourceEditorAssignment &&
  928. newSourceEditorAssignment.variant === 'codemirror') ||
  929. shouldDisplayFeature('new_source_editor', false) // also allow override via ?new_source_editor=true
  930. const showSymbolPalette =
  931. !Features.hasFeature('saas') ||
  932. (user.features && user.features.symbolPalette)
  933. const dictionaryEditorEnabled = shouldDisplayFeature(
  934. 'dictionary-editor',
  935. dictionaryEditorAssignment.variant === 'enabled'
  936. )
  937. // Persistent upgrade prompts
  938. const showHeaderUpgradePrompt =
  939. userId &&
  940. !subscription &&
  941. !userIsMemberOfGroupSubscription &&
  942. !userHasInstitutionLicence
  943. const template =
  944. detachRole === 'detached'
  945. ? 'project/editor_detached'
  946. : 'project/editor'
  947. res.render(template, {
  948. title: project.name,
  949. priority_title: true,
  950. bodyClasses: ['editor'],
  951. project_id: project._id,
  952. projectName: project.name,
  953. user: {
  954. id: userId,
  955. email: user.email,
  956. first_name: user.first_name,
  957. last_name: user.last_name,
  958. referal_id: user.referal_id,
  959. signUpDate: user.signUpDate,
  960. allowedFreeTrial,
  961. featureSwitches: user.featureSwitches,
  962. features: user.features,
  963. refProviders: _.mapValues(user.refProviders, Boolean),
  964. alphaProgram: user.alphaProgram,
  965. betaProgram: user.betaProgram,
  966. isAdmin: hasAdminAccess(user),
  967. },
  968. userSettings: {
  969. mode: user.ace.mode,
  970. editorTheme: user.ace.theme,
  971. fontSize: user.ace.fontSize,
  972. autoComplete: user.ace.autoComplete,
  973. autoPairDelimiters: user.ace.autoPairDelimiters,
  974. pdfViewer: user.ace.pdfViewer,
  975. syntaxValidation: user.ace.syntaxValidation,
  976. fontFamily: user.ace.fontFamily || 'lucida',
  977. lineHeight: user.ace.lineHeight || 'normal',
  978. overallTheme: user.ace.overallTheme,
  979. },
  980. privilegeLevel,
  981. anonymous,
  982. anonymousAccessToken: anonymous ? anonRequestToken : null,
  983. isTokenMember,
  984. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  985. userId,
  986. privilegeLevel,
  987. isTokenMember
  988. ),
  989. languages: Settings.languages,
  990. learnedWords,
  991. editorThemes: THEME_LIST,
  992. maxDocLength: Settings.max_doc_length,
  993. useV2History:
  994. project.overleaf &&
  995. project.overleaf.history &&
  996. Boolean(project.overleaf.history.display),
  997. brandVariation,
  998. allowedImageNames,
  999. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  1000. wsUrl,
  1001. showSupport: Features.hasFeature('support'),
  1002. pdfjsVariant: pdfjsAssignment.variant,
  1003. dictionaryEditorEnabled,
  1004. showPdfDetach,
  1005. debugPdfDetach,
  1006. showNewSourceEditorOption,
  1007. showSymbolPalette,
  1008. trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
  1009. enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
  1010. resetServiceWorker:
  1011. Boolean(Settings.resetServiceWorker) &&
  1012. !shouldDisplayFeature('enable_pdf_caching', false),
  1013. detachRole,
  1014. metadata: { viewport: false },
  1015. showHeaderUpgradePrompt,
  1016. })
  1017. timer.done()
  1018. }
  1019. )
  1020. }
  1021. )
  1022. },
  1023. _refreshFeatures(req, user, callback) {
  1024. // If the feature refresh has failed in this session, don't retry
  1025. // it - require the user to log in again.
  1026. if (req.session.feature_refresh_failed) {
  1027. metrics.inc('features-refresh', 1, {
  1028. path: 'load-editor',
  1029. status: 'skipped',
  1030. })
  1031. return callback(null, user)
  1032. }
  1033. // If the refresh takes too long then return the current
  1034. // features. Note that the user.features property may still be
  1035. // updated in the background after the callback is called.
  1036. callback = _.once(callback)
  1037. const refreshTimeoutHandler = setTimeout(() => {
  1038. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  1039. metrics.inc('features-refresh', 1, {
  1040. path: 'load-editor',
  1041. status: 'timeout',
  1042. })
  1043. callback(null, user)
  1044. }, 5000)
  1045. // try to refresh user features now
  1046. const timer = new metrics.Timer('features-refresh-on-load-editor')
  1047. FeaturesUpdater.refreshFeatures(
  1048. user._id,
  1049. 'load-editor',
  1050. (err, features) => {
  1051. clearTimeout(refreshTimeoutHandler)
  1052. timer.done()
  1053. if (err) {
  1054. // keep a record to prevent unneceary retries and leave
  1055. // the original features unmodified if the refresh failed
  1056. req.session.feature_refresh_failed = {
  1057. reason: 'error',
  1058. at: new Date(),
  1059. }
  1060. metrics.inc('features-refresh', 1, {
  1061. path: 'load-editor',
  1062. status: 'error',
  1063. })
  1064. } else {
  1065. user.features = features
  1066. metrics.inc('features-refresh', 1, {
  1067. path: 'load-editor',
  1068. status: 'success',
  1069. })
  1070. }
  1071. return callback(null, user)
  1072. }
  1073. )
  1074. },
  1075. _buildProjectList(allProjects, userId) {
  1076. let project
  1077. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  1078. allProjects
  1079. const projects = []
  1080. for (project of owned) {
  1081. projects.push(
  1082. ProjectController._buildProjectViewModel(
  1083. project,
  1084. 'owner',
  1085. Sources.OWNER,
  1086. userId
  1087. )
  1088. )
  1089. }
  1090. // Invite-access
  1091. for (project of readAndWrite) {
  1092. projects.push(
  1093. ProjectController._buildProjectViewModel(
  1094. project,
  1095. 'readWrite',
  1096. Sources.INVITE,
  1097. userId
  1098. )
  1099. )
  1100. }
  1101. for (project of readOnly) {
  1102. projects.push(
  1103. ProjectController._buildProjectViewModel(
  1104. project,
  1105. 'readOnly',
  1106. Sources.INVITE,
  1107. userId
  1108. )
  1109. )
  1110. }
  1111. // Token-access
  1112. // Only add these projects if they're not already present, this gives us cascading access
  1113. // from 'owner' => 'token-read-only'
  1114. for (project of tokenReadAndWrite) {
  1115. if (
  1116. projects.filter(p => p.id.toString() === project._id.toString())
  1117. .length === 0
  1118. ) {
  1119. projects.push(
  1120. ProjectController._buildProjectViewModel(
  1121. project,
  1122. 'readAndWrite',
  1123. Sources.TOKEN,
  1124. userId
  1125. )
  1126. )
  1127. }
  1128. }
  1129. for (project of tokenReadOnly) {
  1130. if (
  1131. projects.filter(p => p.id.toString() === project._id.toString())
  1132. .length === 0
  1133. ) {
  1134. projects.push(
  1135. ProjectController._buildProjectViewModel(
  1136. project,
  1137. 'readOnly',
  1138. Sources.TOKEN,
  1139. userId
  1140. )
  1141. )
  1142. }
  1143. }
  1144. return projects
  1145. },
  1146. _buildProjectViewModel(project, accessLevel, source, userId) {
  1147. const archived = ProjectHelper.isArchived(project, userId)
  1148. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1149. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1150. TokenAccessHandler.protectTokens(project, accessLevel)
  1151. const model = {
  1152. id: project._id,
  1153. name: project.name,
  1154. lastUpdated: project.lastUpdated,
  1155. lastUpdatedBy: project.lastUpdatedBy,
  1156. publicAccessLevel: project.publicAccesLevel,
  1157. accessLevel,
  1158. source,
  1159. archived,
  1160. trashed,
  1161. owner_ref: project.owner_ref,
  1162. isV1Project: false,
  1163. }
  1164. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1165. model.owner_ref = null
  1166. model.lastUpdatedBy = null
  1167. }
  1168. return model
  1169. },
  1170. _injectProjectUsers(projects, callback) {
  1171. const users = {}
  1172. for (const project of projects) {
  1173. if (project.owner_ref != null) {
  1174. users[project.owner_ref.toString()] = true
  1175. }
  1176. if (project.lastUpdatedBy != null) {
  1177. users[project.lastUpdatedBy.toString()] = true
  1178. }
  1179. }
  1180. const userIds = Object.keys(users)
  1181. async.eachSeries(
  1182. userIds,
  1183. (userId, cb) => {
  1184. UserGetter.getUser(
  1185. userId,
  1186. { first_name: 1, last_name: 1, email: 1 },
  1187. (error, user) => {
  1188. if (error != null) {
  1189. return cb(error)
  1190. }
  1191. users[userId] = user
  1192. cb()
  1193. }
  1194. )
  1195. },
  1196. error => {
  1197. if (error != null) {
  1198. return callback(error)
  1199. }
  1200. for (const project of projects) {
  1201. if (project.owner_ref != null) {
  1202. project.owner = users[project.owner_ref.toString()]
  1203. }
  1204. if (project.lastUpdatedBy != null) {
  1205. project.lastUpdatedBy =
  1206. users[project.lastUpdatedBy.toString()] || null
  1207. }
  1208. }
  1209. callback(null, projects)
  1210. }
  1211. )
  1212. },
  1213. _buildPortalTemplatesList(affiliations) {
  1214. if (affiliations == null) {
  1215. affiliations = []
  1216. }
  1217. const portalTemplates = []
  1218. for (const aff of affiliations) {
  1219. if (
  1220. aff.portal &&
  1221. aff.portal.slug &&
  1222. aff.portal.templates_count &&
  1223. aff.portal.templates_count > 0
  1224. ) {
  1225. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1226. portalTemplates.push({
  1227. name: aff.institution.name,
  1228. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1229. })
  1230. }
  1231. }
  1232. return portalTemplates
  1233. },
  1234. }
  1235. const defaultSettingsForAnonymousUser = userId => ({
  1236. id: userId,
  1237. ace: {
  1238. mode: 'none',
  1239. theme: 'textmate',
  1240. fontSize: '12',
  1241. autoComplete: true,
  1242. spellCheckLanguage: '',
  1243. pdfViewer: '',
  1244. syntaxValidation: true,
  1245. },
  1246. subscription: {
  1247. freeTrial: {
  1248. allowed: true,
  1249. },
  1250. },
  1251. featureSwitches: {
  1252. github: false,
  1253. },
  1254. alphaProgram: false,
  1255. betaProgram: false,
  1256. })
  1257. const THEME_LIST = [
  1258. 'ambiance',
  1259. 'chaos',
  1260. 'chrome',
  1261. 'clouds',
  1262. 'clouds_midnight',
  1263. 'cobalt',
  1264. 'crimson_editor',
  1265. 'dawn',
  1266. 'dracula',
  1267. 'dreamweaver',
  1268. 'eclipse',
  1269. 'github',
  1270. 'gob',
  1271. 'gruvbox',
  1272. 'idle_fingers',
  1273. 'iplastic',
  1274. 'katzenmilch',
  1275. 'kr_theme',
  1276. 'kuroir',
  1277. 'merbivore',
  1278. 'merbivore_soft',
  1279. 'mono_industrial',
  1280. 'monokai',
  1281. 'nord_dark',
  1282. 'overleaf',
  1283. 'pastel_on_dark',
  1284. 'solarized_dark',
  1285. 'solarized_light',
  1286. 'sqlserver',
  1287. 'terminal',
  1288. 'textmate',
  1289. 'tomorrow',
  1290. 'tomorrow_night',
  1291. 'tomorrow_night_blue',
  1292. 'tomorrow_night_bright',
  1293. 'tomorrow_night_eighties',
  1294. 'twilight',
  1295. 'vibrant_ink',
  1296. 'xcode',
  1297. ]
  1298. module.exports = ProjectController