ProjectController.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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 SubscriptionViewModelBuilder = require('../Subscription/SubscriptionViewModelBuilder')
  45. const SurveyHandler = require('../Survey/SurveyHandler')
  46. const ProjectAuditLogHandler = require('./ProjectAuditLogHandler')
  47. const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
  48. const VISUAL_EDITOR_NAMING_SPLIT_TEST_MIN_SIGNUP_DATE = new Date('2023-04-17')
  49. /**
  50. * @typedef {import("./types").GetProjectsRequest} GetProjectsRequest
  51. * @typedef {import("./types").GetProjectsResponse} GetProjectsResponse
  52. * @typedef {import("./types").Project} Project
  53. */
  54. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  55. if (!affiliation.institution) return false
  56. // institution.confirmed is for the domain being confirmed, not the email
  57. // Do not show SSO UI for unconfirmed domains
  58. if (!affiliation.institution.confirmed) return false
  59. // Could have multiple emails at the same institution, and if any are
  60. // linked to the institution then do not show notification for others
  61. if (
  62. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  63. ) {
  64. if (affiliation.institution.ssoEnabled) return true
  65. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  66. return false
  67. }
  68. return false
  69. }
  70. const ProjectController = {
  71. _isInPercentageRollout(rolloutName, objectId, percentage) {
  72. if (Settings.bypassPercentageRollouts === true) {
  73. return true
  74. }
  75. const data = `${rolloutName}:${objectId.toString()}`
  76. const md5hash = crypto.createHash('md5').update(data).digest('hex')
  77. const counter = parseInt(md5hash.slice(26, 32), 16)
  78. return counter % 100 < percentage
  79. },
  80. updateProjectSettings(req, res, next) {
  81. const projectId = req.params.Project_id
  82. const jobs = []
  83. if (req.body.compiler != null) {
  84. jobs.push(callback =>
  85. EditorController.setCompiler(projectId, req.body.compiler, callback)
  86. )
  87. }
  88. if (req.body.imageName != null) {
  89. jobs.push(callback =>
  90. EditorController.setImageName(projectId, req.body.imageName, callback)
  91. )
  92. }
  93. if (req.body.name != null) {
  94. jobs.push(callback =>
  95. EditorController.renameProject(projectId, req.body.name, callback)
  96. )
  97. }
  98. if (req.body.spellCheckLanguage != null) {
  99. jobs.push(callback =>
  100. EditorController.setSpellCheckLanguage(
  101. projectId,
  102. req.body.spellCheckLanguage,
  103. callback
  104. )
  105. )
  106. }
  107. if (req.body.rootDocId != null) {
  108. jobs.push(callback =>
  109. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  110. )
  111. }
  112. async.series(jobs, error => {
  113. if (error != null) {
  114. return next(error)
  115. }
  116. res.sendStatus(204)
  117. })
  118. },
  119. updateProjectAdminSettings(req, res, next) {
  120. const projectId = req.params.Project_id
  121. const user = SessionManager.getSessionUser(req.session)
  122. const publicAccessLevel = req.body.publicAccessLevel
  123. const publicAccessLevels = [
  124. PublicAccessLevels.READ_ONLY,
  125. PublicAccessLevels.READ_AND_WRITE,
  126. PublicAccessLevels.PRIVATE,
  127. PublicAccessLevels.TOKEN_BASED,
  128. ]
  129. if (
  130. req.body.publicAccessLevel != null &&
  131. publicAccessLevels.includes(publicAccessLevel)
  132. ) {
  133. const jobs = []
  134. jobs.push(callback =>
  135. EditorController.setPublicAccessLevel(
  136. projectId,
  137. req.body.publicAccessLevel,
  138. callback
  139. )
  140. )
  141. jobs.push(callback =>
  142. ProjectAuditLogHandler.addEntry(
  143. projectId,
  144. 'toggle-access-level',
  145. user._id,
  146. { publicAccessLevel: req.body.publicAccessLevel, status: 'OK' },
  147. callback
  148. )
  149. )
  150. async.series(jobs, error => {
  151. if (error != null) {
  152. return next(error)
  153. }
  154. res.sendStatus(204)
  155. })
  156. } else {
  157. res.sendStatus(500)
  158. }
  159. },
  160. deleteProject(req, res) {
  161. const projectId = req.params.Project_id
  162. const user = SessionManager.getSessionUser(req.session)
  163. const cb = err => {
  164. if (err != null) {
  165. res.sendStatus(500)
  166. } else {
  167. res.sendStatus(200)
  168. }
  169. }
  170. ProjectDeleter.deleteProject(
  171. projectId,
  172. { deleterUser: user, ipAddress: req.ip },
  173. cb
  174. )
  175. },
  176. archiveProject(req, res, next) {
  177. const projectId = req.params.Project_id
  178. const userId = SessionManager.getLoggedInUserId(req.session)
  179. ProjectDeleter.archiveProject(projectId, userId, function (err) {
  180. if (err != null) {
  181. next(err)
  182. } else {
  183. res.sendStatus(200)
  184. }
  185. })
  186. },
  187. unarchiveProject(req, res, next) {
  188. const projectId = req.params.Project_id
  189. const userId = SessionManager.getLoggedInUserId(req.session)
  190. ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
  191. if (err != null) {
  192. next(err)
  193. } else {
  194. res.sendStatus(200)
  195. }
  196. })
  197. },
  198. trashProject(req, res, next) {
  199. const projectId = req.params.project_id
  200. const userId = SessionManager.getLoggedInUserId(req.session)
  201. ProjectDeleter.trashProject(projectId, userId, function (err) {
  202. if (err != null) {
  203. next(err)
  204. } else {
  205. res.sendStatus(200)
  206. }
  207. })
  208. },
  209. untrashProject(req, res, next) {
  210. const projectId = req.params.project_id
  211. const userId = SessionManager.getLoggedInUserId(req.session)
  212. ProjectDeleter.untrashProject(projectId, userId, function (err) {
  213. if (err != null) {
  214. next(err)
  215. } else {
  216. res.sendStatus(200)
  217. }
  218. })
  219. },
  220. expireDeletedProjectsAfterDuration(req, res) {
  221. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  222. if (err != null) {
  223. res.sendStatus(500)
  224. } else {
  225. res.sendStatus(200)
  226. }
  227. })
  228. },
  229. expireDeletedProject(req, res, next) {
  230. const { projectId } = req.params
  231. ProjectDeleter.expireDeletedProject(projectId, err => {
  232. if (err != null) {
  233. next(err)
  234. } else {
  235. res.sendStatus(200)
  236. }
  237. })
  238. },
  239. restoreProject(req, res) {
  240. const projectId = req.params.Project_id
  241. ProjectDeleter.restoreProject(projectId, err => {
  242. if (err != null) {
  243. res.sendStatus(500)
  244. } else {
  245. res.sendStatus(200)
  246. }
  247. })
  248. },
  249. cloneProject(req, res, next) {
  250. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  251. metrics.inc('cloned-project')
  252. const projectId = req.params.Project_id
  253. const { projectName } = req.body
  254. logger.debug({ projectId, projectName }, 'cloning project')
  255. if (!SessionManager.isUserLoggedIn(req.session)) {
  256. return res.json({ redir: '/register' })
  257. }
  258. const currentUser = SessionManager.getSessionUser(req.session)
  259. const { first_name: firstName, last_name: lastName, email } = currentUser
  260. ProjectDuplicator.duplicate(
  261. currentUser,
  262. projectId,
  263. projectName,
  264. (err, project) => {
  265. if (err != null) {
  266. OError.tag(err, 'error cloning project', {
  267. projectId,
  268. userId: currentUser._id,
  269. })
  270. return next(err)
  271. }
  272. res.json({
  273. name: project.name,
  274. lastUpdated: project.lastUpdated,
  275. project_id: project._id,
  276. owner_ref: project.owner_ref,
  277. owner: {
  278. first_name: firstName,
  279. last_name: lastName,
  280. email,
  281. _id: currentUser._id,
  282. },
  283. })
  284. }
  285. )
  286. },
  287. newProject(req, res, next) {
  288. const currentUser = SessionManager.getSessionUser(req.session)
  289. const {
  290. first_name: firstName,
  291. last_name: lastName,
  292. email,
  293. _id: userId,
  294. } = currentUser
  295. const projectName =
  296. req.body.projectName != null ? req.body.projectName.trim() : undefined
  297. const { template } = req.body
  298. async.waterfall(
  299. [
  300. cb => {
  301. if (template === 'example') {
  302. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  303. } else {
  304. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  305. }
  306. },
  307. ],
  308. (err, project) => {
  309. if (err != null) {
  310. return next(err)
  311. }
  312. res.json({
  313. project_id: project._id,
  314. owner_ref: project.owner_ref,
  315. owner: {
  316. first_name: firstName,
  317. last_name: lastName,
  318. email,
  319. _id: userId,
  320. },
  321. })
  322. }
  323. )
  324. },
  325. renameProject(req, res, next) {
  326. const projectId = req.params.Project_id
  327. const newName = req.body.newProjectName
  328. EditorController.renameProject(projectId, newName, err => {
  329. if (err != null) {
  330. return next(err)
  331. }
  332. res.sendStatus(200)
  333. })
  334. },
  335. userProjectsJson(req, res, next) {
  336. const userId = SessionManager.getLoggedInUserId(req.session)
  337. ProjectGetter.findAllUsersProjects(
  338. userId,
  339. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  340. (err, projects) => {
  341. if (err != null) {
  342. return next(err)
  343. }
  344. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  345. projects = ProjectController._buildProjectList(projects, userId)
  346. .filter(p => !(p.archived || p.trashed))
  347. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  348. res.json({ projects })
  349. }
  350. )
  351. },
  352. projectEntitiesJson(req, res, next) {
  353. const projectId = req.params.Project_id
  354. ProjectGetter.getProject(projectId, (err, project) => {
  355. if (err != null) {
  356. return next(err)
  357. }
  358. let docs, files
  359. try {
  360. ;({ docs, files } =
  361. ProjectEntityHandler.getAllEntitiesFromProject(project))
  362. } catch (err) {
  363. return next(err)
  364. }
  365. const entities = docs
  366. .concat(files)
  367. // Sort by path ascending
  368. .sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
  369. .map(e => ({
  370. path: e.path,
  371. type: e.doc != null ? 'doc' : 'file',
  372. }))
  373. res.json({ project_id: projectId, entities })
  374. })
  375. },
  376. projectListPage(req, res, next) {
  377. const timer = new metrics.Timer('project-list')
  378. const userId = SessionManager.getLoggedInUserId(req.session)
  379. const currentUser = SessionManager.getSessionUser(req.session)
  380. async.parallel(
  381. {
  382. tags(cb) {
  383. TagsHandler.getAllTags(userId, cb)
  384. },
  385. notifications(cb) {
  386. NotificationsHandler.getUserNotifications(userId, cb)
  387. },
  388. projects(cb) {
  389. ProjectGetter.findAllUsersProjects(
  390. userId,
  391. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  392. cb
  393. )
  394. },
  395. hasSubscription(cb) {
  396. LimitationsManager.hasPaidSubscription(
  397. currentUser,
  398. (error, hasPaidSubscription) => {
  399. if (error != null && error instanceof V1ConnectionError) {
  400. return cb(null, true)
  401. }
  402. cb(error, hasPaidSubscription)
  403. }
  404. )
  405. },
  406. user(cb) {
  407. User.findById(
  408. userId,
  409. 'email emails featureSwitches overleaf awareOfV2 features lastLoginIp lastPrimaryEmailCheck signUpDate',
  410. cb
  411. )
  412. },
  413. userEmailsData(cb) {
  414. const result = { list: [], allInReconfirmNotificationPeriods: [] }
  415. UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
  416. if (error && error instanceof V1ConnectionError) {
  417. return cb(null, result)
  418. }
  419. if (!Features.hasFeature('affiliations')) {
  420. result.list = fullEmails
  421. return cb(null, result)
  422. }
  423. Modules.hooks.fire(
  424. 'allInReconfirmNotificationPeriodsForUser',
  425. fullEmails,
  426. (error, results) => {
  427. if (error != null) {
  428. return cb(error)
  429. }
  430. // Module.hooks.fire accepts multiple methods
  431. // and does async.series
  432. const allInReconfirmNotificationPeriods =
  433. (results && results[0]) || []
  434. cb(null, {
  435. list: fullEmails,
  436. allInReconfirmNotificationPeriods,
  437. })
  438. }
  439. )
  440. })
  441. },
  442. usersBestSubscription(cb) {
  443. if (!Features.hasFeature('saas')) {
  444. return cb()
  445. }
  446. SubscriptionViewModelBuilder.getBestSubscription(
  447. { _id: userId },
  448. (err, subscription) => {
  449. if (err) {
  450. // do not fail loading the project list when fetching the best subscription fails
  451. logger.error(
  452. { userId, err },
  453. 'Could not get usersBestSubscription'
  454. )
  455. return cb(null, { type: 'error' })
  456. }
  457. cb(null, subscription)
  458. }
  459. )
  460. },
  461. userIsMemberOfGroupSubscription(cb) {
  462. LimitationsManager.userIsMemberOfGroupSubscription(
  463. currentUser,
  464. (error, isMember) => {
  465. if (error) {
  466. logger.error(
  467. { err: error },
  468. 'Failed to check whether user is a member of group subscription'
  469. )
  470. return cb(null, false)
  471. }
  472. cb(null, isMember)
  473. }
  474. )
  475. },
  476. survey(cb) {
  477. SurveyHandler.getSurvey(userId, (err, survey) => {
  478. if (err) {
  479. logger.warn({ err }, 'failed to get survey')
  480. // do not fail loading the project list if we fail to load the survey
  481. cb(null, null)
  482. } else {
  483. cb(null, survey)
  484. }
  485. })
  486. },
  487. },
  488. (err, results) => {
  489. if (err != null) {
  490. OError.tag(err, 'error getting data for project list page')
  491. return next(err)
  492. }
  493. const {
  494. notifications,
  495. user,
  496. userEmailsData,
  497. userIsMemberOfGroupSubscription,
  498. } = results
  499. if (
  500. user &&
  501. Features.hasFeature('saas') &&
  502. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)
  503. ) {
  504. return res.redirect('/user/emails/primary-email-check')
  505. }
  506. const userEmails = userEmailsData.list || []
  507. const userAffiliations = userEmails
  508. .filter(emailData => !!emailData.affiliation)
  509. .map(emailData => {
  510. const result = emailData.affiliation
  511. result.email = emailData.email
  512. return result
  513. })
  514. const { allInReconfirmNotificationPeriods } = userEmailsData
  515. // Handle case of deleted user
  516. if (user == null) {
  517. UserController.logout(req, res, next)
  518. return
  519. }
  520. const tags = results.tags
  521. const notificationsInstitution = []
  522. for (const notification of notifications) {
  523. notification.html = req.i18n.translate(
  524. notification.templateKey,
  525. notification.messageOpts
  526. )
  527. }
  528. // Institution SSO Notifications
  529. let reconfirmedViaSAML
  530. if (Features.hasFeature('saml')) {
  531. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  532. const samlSession = req.session.saml
  533. // Notification: SSO Available
  534. const linkedInstitutionIds = []
  535. user.emails.forEach(email => {
  536. if (email.samlProviderId) {
  537. linkedInstitutionIds.push(email.samlProviderId)
  538. }
  539. })
  540. if (Array.isArray(userAffiliations)) {
  541. userAffiliations.forEach(affiliation => {
  542. if (
  543. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  544. ) {
  545. notificationsInstitution.push({
  546. email: affiliation.email,
  547. institutionId: affiliation.institution.id,
  548. institutionName: affiliation.institution.name,
  549. templateKey: 'notification_institution_sso_available',
  550. })
  551. }
  552. })
  553. }
  554. if (samlSession) {
  555. // Notification: After SSO Linked
  556. if (samlSession.linked) {
  557. notificationsInstitution.push({
  558. email: samlSession.institutionEmail,
  559. institutionName: samlSession.linked.universityName,
  560. templateKey: 'notification_institution_sso_linked',
  561. })
  562. }
  563. // Notification: After SSO Linked or Logging in
  564. // The requested email does not match primary email returned from
  565. // the institution
  566. if (
  567. samlSession.requestedEmail &&
  568. samlSession.emailNonCanonical &&
  569. !samlSession.error
  570. ) {
  571. notificationsInstitution.push({
  572. institutionEmail: samlSession.emailNonCanonical,
  573. requestedEmail: samlSession.requestedEmail,
  574. templateKey: 'notification_institution_sso_non_canonical',
  575. })
  576. }
  577. // Notification: Tried to register, but account already existed
  578. // registerIntercept is set before the institution callback.
  579. // institutionEmail is set after institution callback.
  580. // Check for both in case SSO flow was abandoned
  581. if (
  582. samlSession.registerIntercept &&
  583. samlSession.institutionEmail &&
  584. !samlSession.error
  585. ) {
  586. notificationsInstitution.push({
  587. email: samlSession.institutionEmail,
  588. templateKey: 'notification_institution_sso_already_registered',
  589. })
  590. }
  591. // Notification: When there is a session error
  592. if (samlSession.error) {
  593. notificationsInstitution.push({
  594. templateKey: 'notification_institution_sso_error',
  595. error: samlSession.error,
  596. })
  597. }
  598. }
  599. delete req.session.saml
  600. }
  601. const portalTemplates =
  602. ProjectController._buildPortalTemplatesList(userAffiliations)
  603. const projects = ProjectController._buildProjectList(
  604. results.projects,
  605. userId
  606. )
  607. // in v2 add notifications for matching university IPs
  608. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  609. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  610. req.ip,
  611. () => {}
  612. )
  613. }
  614. const hasPaidAffiliation = userAffiliations.some(
  615. affiliation => affiliation.licence && affiliation.licence !== 'free'
  616. )
  617. const showGroupsAndEnterpriseBanner =
  618. Features.hasFeature('saas') &&
  619. !userIsMemberOfGroupSubscription &&
  620. !hasPaidAffiliation
  621. const groupsAndEnterpriseBannerVariant =
  622. showGroupsAndEnterpriseBanner &&
  623. _.sample(['did-you-know', 'on-premise', 'people', 'FOMO'])
  624. ProjectController._injectProjectUsers(projects, (error, projects) => {
  625. if (error != null) {
  626. return next(error)
  627. }
  628. const viewModel = {
  629. title: 'your_projects',
  630. priority_title: true,
  631. projects,
  632. tags,
  633. notifications: notifications || [],
  634. notificationsInstitution,
  635. allInReconfirmNotificationPeriods,
  636. portalTemplates,
  637. user,
  638. userAffiliations,
  639. userEmails,
  640. hasSubscription: results.hasSubscription,
  641. reconfirmedViaSAML,
  642. zipFileSizeLimit: Settings.maxUploadSize,
  643. isOverleaf: !!Settings.overleaf,
  644. metadata: { viewport: false },
  645. showThinFooter: true, // don't show the fat footer on the projects dashboard, as there's a fixed space available
  646. usersBestSubscription: results.usersBestSubscription,
  647. survey: results.survey,
  648. showGroupsAndEnterpriseBanner,
  649. groupsAndEnterpriseBannerVariant,
  650. }
  651. const paidUser =
  652. (user.features != null ? user.features.github : undefined) &&
  653. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  654. const freeUserProportion = 0.1
  655. const sampleFreeUser =
  656. parseInt(user._id.toString().slice(-2), 16) <
  657. freeUserProportion * 255
  658. const showFrontWidget = paidUser || sampleFreeUser
  659. if (showFrontWidget) {
  660. viewModel.frontChatWidgetRoomId =
  661. Settings.overleaf != null
  662. ? Settings.overleaf.front_chat_widget_room_id
  663. : undefined
  664. }
  665. // null test targeting logged in users
  666. SplitTestHandler.promises.getAssignment(
  667. req,
  668. res,
  669. 'null-test-dashboard'
  670. )
  671. res.render('project/list', viewModel)
  672. timer.done()
  673. })
  674. }
  675. )
  676. },
  677. loadEditor(req, res, next) {
  678. const timer = new metrics.Timer('load-editor')
  679. if (!Settings.editorIsOpen) {
  680. return res.render('general/closed', { title: 'updating_site' })
  681. }
  682. let anonymous, userId, sessionUser
  683. if (SessionManager.isUserLoggedIn(req.session)) {
  684. sessionUser = SessionManager.getSessionUser(req.session)
  685. userId = SessionManager.getLoggedInUserId(req.session)
  686. anonymous = false
  687. } else {
  688. sessionUser = null
  689. anonymous = true
  690. userId = null
  691. }
  692. const projectId = req.params.Project_id
  693. async.auto(
  694. {
  695. project(cb) {
  696. ProjectGetter.getProject(
  697. projectId,
  698. {
  699. name: 1,
  700. lastUpdated: 1,
  701. track_changes: 1,
  702. owner_ref: 1,
  703. brandVariationId: 1,
  704. overleaf: 1,
  705. tokens: 1,
  706. },
  707. (err, project) => {
  708. if (err != null) {
  709. return cb(err)
  710. }
  711. cb(null, project)
  712. }
  713. )
  714. },
  715. user(cb) {
  716. if (userId == null) {
  717. cb(null, defaultSettingsForAnonymousUser(userId))
  718. } else {
  719. User.updateOne(
  720. { _id: ObjectId(userId) },
  721. { $set: { lastActive: new Date() } },
  722. {},
  723. () => {}
  724. )
  725. User.findById(
  726. userId,
  727. 'email first_name last_name referal_id signUpDate featureSwitches features featuresEpoch refProviders alphaProgram betaProgram isAdmin ace labsProgram labsProgramGalileo',
  728. (err, user) => {
  729. // Handle case of deleted user
  730. if (user == null) {
  731. UserController.logout(req, res, next)
  732. return
  733. }
  734. if (err) {
  735. return cb(err)
  736. }
  737. logger.debug({ projectId, userId }, 'got user')
  738. if (FeaturesUpdater.featuresEpochIsCurrent(user)) {
  739. return cb(null, user)
  740. }
  741. ProjectController._refreshFeatures(req, user, cb)
  742. }
  743. )
  744. }
  745. },
  746. userHasInstitutionLicence(cb) {
  747. if (!userId) {
  748. return cb(null, false)
  749. }
  750. InstitutionsFeatures.hasLicence(userId, (error, hasLicence) => {
  751. if (error) {
  752. // Don't fail if we can't get affiliation licences
  753. return cb(null, false)
  754. }
  755. cb(null, hasLicence)
  756. })
  757. },
  758. learnedWords(cb) {
  759. if (!userId) {
  760. return cb(null, [])
  761. }
  762. SpellingHandler.getUserDictionary(userId, cb)
  763. },
  764. subscription(cb) {
  765. if (userId == null) {
  766. return cb()
  767. }
  768. SubscriptionLocator.getUsersSubscription(userId, cb)
  769. },
  770. userIsMemberOfGroupSubscription(cb) {
  771. if (sessionUser == null) {
  772. return cb(null, false)
  773. }
  774. LimitationsManager.userIsMemberOfGroupSubscription(
  775. sessionUser,
  776. (error, isMember) => {
  777. cb(error, isMember)
  778. }
  779. )
  780. },
  781. activate(cb) {
  782. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  783. },
  784. markAsOpened(cb) {
  785. // don't need to wait for this to complete
  786. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  787. cb()
  788. },
  789. isTokenMember(cb) {
  790. if (userId == null) {
  791. return cb()
  792. }
  793. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  794. },
  795. isInvitedMember(cb) {
  796. CollaboratorsGetter.isUserInvitedMemberOfProject(
  797. userId,
  798. projectId,
  799. cb
  800. )
  801. },
  802. brandVariation: [
  803. 'project',
  804. (results, cb) => {
  805. if (
  806. (results.project != null
  807. ? results.project.brandVariationId
  808. : undefined) == null
  809. ) {
  810. return cb()
  811. }
  812. BrandVariationsHandler.getBrandVariationById(
  813. results.project.brandVariationId,
  814. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  815. )
  816. },
  817. ],
  818. flushToTpds: cb => {
  819. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  820. },
  821. sharingModalSplitTest(cb) {
  822. SplitTestHandler.getAssignment(
  823. req,
  824. res,
  825. 'project-share-modal-paywall',
  826. {},
  827. () => {
  828. // do not fail editor load if assignment fails
  829. cb()
  830. }
  831. )
  832. },
  833. sharingModalNullTest(cb) {
  834. // null test targeting logged in users, for front-end side
  835. SplitTestHandler.getAssignment(
  836. req,
  837. res,
  838. 'null-test-share-modal',
  839. {},
  840. () => {
  841. // do not fail editor load if assignment fails
  842. cb()
  843. }
  844. )
  845. },
  846. participatingInVisualEditorNamingTest: [
  847. 'user',
  848. (results, cb) => {
  849. const isNewUser =
  850. results.user.signUpDate >=
  851. VISUAL_EDITOR_NAMING_SPLIT_TEST_MIN_SIGNUP_DATE
  852. cb(null, isNewUser)
  853. },
  854. ],
  855. visualEditorNameAssignment: [
  856. 'participatingInVisualEditorNamingTest',
  857. (results, cb) => {
  858. if (!results.participatingInVisualEditorNamingTest) {
  859. cb(null, { variant: 'default' })
  860. } else {
  861. SplitTestHandler.getAssignment(
  862. req,
  863. res,
  864. 'visual-editor-name',
  865. (error, assignment) => {
  866. if (error) {
  867. cb(null, { variant: 'default' })
  868. } else {
  869. cb(null, assignment)
  870. }
  871. }
  872. )
  873. }
  874. },
  875. ],
  876. legacySourceEditorAssignment: [
  877. 'participatingInVisualEditorNamingTest',
  878. 'visualEditorNameAssignment',
  879. (results, cb) => {
  880. // Hide Ace for people in the Rich Text naming test
  881. if (results.participatingInVisualEditorNamingTest) {
  882. cb(null, { variant: 'true' })
  883. } else {
  884. SplitTestHandler.getAssignment(
  885. req,
  886. res,
  887. 'source-editor-legacy',
  888. (error, assignment) => {
  889. // do not fail editor load if assignment fails
  890. if (error) {
  891. cb(null, { variant: 'default' })
  892. } else {
  893. cb(null, assignment)
  894. }
  895. }
  896. )
  897. }
  898. },
  899. ],
  900. pdfjsAssignment(cb) {
  901. SplitTestHandler.getAssignment(
  902. req,
  903. res,
  904. 'pdfjs-31',
  905. {},
  906. (error, assignment) => {
  907. // do not fail editor load if assignment fails
  908. if (error) {
  909. cb(null, { variant: 'default' })
  910. } else {
  911. cb(null, assignment)
  912. }
  913. }
  914. )
  915. },
  916. latexLogParserAssignment(cb) {
  917. SplitTestHandler.getAssignment(
  918. req,
  919. res,
  920. 'latex-log-parser',
  921. (error, assignment) => {
  922. // do not fail editor load if assignment fails
  923. if (error) {
  924. cb(null, { variant: 'default' })
  925. } else {
  926. cb(null, assignment)
  927. }
  928. }
  929. )
  930. },
  931. trackPdfDownloadAssignment(cb) {
  932. SplitTestHandler.getAssignment(req, res, 'track-pdf-download', () => {
  933. // We'll pick up the assignment from the res.locals assignment.
  934. cb()
  935. })
  936. },
  937. pdfCachingModeAssignment(cb) {
  938. SplitTestHandler.getAssignment(req, res, 'pdf-caching-mode', () => {
  939. // We'll pick up the assignment from the res.locals assignment.
  940. cb()
  941. })
  942. },
  943. pdfCachingPrefetchingAssignment(cb) {
  944. SplitTestHandler.getAssignment(
  945. req,
  946. res,
  947. 'pdf-caching-prefetching',
  948. () => {
  949. // We'll pick up the assignment from the res.locals assignment.
  950. cb()
  951. }
  952. )
  953. },
  954. pdfCachingPrefetchLargeAssignment(cb) {
  955. SplitTestHandler.getAssignment(
  956. req,
  957. res,
  958. 'pdf-caching-prefetch-large',
  959. () => {
  960. // We'll pick up the assignment from the res.locals assignment.
  961. cb()
  962. }
  963. )
  964. },
  965. pdfCachingCachedUrlLookupAssignment(cb) {
  966. SplitTestHandler.getAssignment(
  967. req,
  968. res,
  969. 'pdf-caching-cached-url-lookup',
  970. () => {
  971. // We'll pick up the assignment from the res.locals assignment.
  972. cb()
  973. }
  974. )
  975. },
  976. editorLeftMenuAssignment(cb) {
  977. SplitTestHandler.getAssignment(
  978. req,
  979. res,
  980. 'editor-left-menu',
  981. (error, assignment) => {
  982. // do not fail editor load if assignment fails
  983. if (error) {
  984. cb(null, { variant: 'default' })
  985. } else {
  986. cb(null, assignment)
  987. }
  988. }
  989. )
  990. },
  991. editorDocumentationButton(cb) {
  992. SplitTestHandler.getAssignment(
  993. req,
  994. res,
  995. 'documentation-on-editor',
  996. (error, assignment) => {
  997. // do not fail editor load if assignment fails
  998. if (error) {
  999. cb(null, { variant: 'default' })
  1000. } else {
  1001. cb(null, assignment)
  1002. }
  1003. }
  1004. )
  1005. },
  1006. richTextAssignment(cb) {
  1007. SplitTestHandler.getAssignment(
  1008. req,
  1009. res,
  1010. 'rich-text',
  1011. (error, assignment) => {
  1012. // do not fail editor load if assignment fails
  1013. if (error) {
  1014. cb(null, { variant: 'default' })
  1015. } else {
  1016. cb(null, assignment)
  1017. }
  1018. }
  1019. )
  1020. },
  1021. figureModalAssignment(cb) {
  1022. SplitTestHandler.getAssignment(req, res, 'figure-modal', () => {
  1023. // We'll pick up the assignment from the res.locals assignment.
  1024. cb()
  1025. })
  1026. },
  1027. onboardingVideoTourAssignment(cb) {
  1028. SplitTestHandler.getAssignment(
  1029. req,
  1030. res,
  1031. 'onboarding-video-tour',
  1032. (error, assignment) => {
  1033. // do not fail editor load if assignment fails
  1034. if (error) {
  1035. cb(null, { variant: 'default' })
  1036. } else {
  1037. cb(null, assignment)
  1038. }
  1039. }
  1040. )
  1041. },
  1042. historyViewAssignment(cb) {
  1043. SplitTestHandler.getAssignment(
  1044. req,
  1045. res,
  1046. 'history-view',
  1047. (error, assignment) => {
  1048. // do not fail editor load if assignment fails
  1049. if (error) {
  1050. cb(null, { variant: 'default' })
  1051. } else {
  1052. cb(null, assignment)
  1053. }
  1054. }
  1055. )
  1056. },
  1057. accessCheckForOldCompileDomainAssigment(cb) {
  1058. SplitTestHandler.getAssignment(
  1059. req,
  1060. res,
  1061. 'access-check-for-old-compile-domain',
  1062. () => {
  1063. // We'll pick up the assignment from the res.locals assignment.
  1064. cb()
  1065. }
  1066. )
  1067. },
  1068. forceNewDomainAssignment(cb) {
  1069. SplitTestHandler.getAssignment(
  1070. req,
  1071. res,
  1072. 'force-new-compile-domain',
  1073. () => {
  1074. // We'll pick up the assignment from the res.locals assignment.
  1075. cb()
  1076. }
  1077. )
  1078. },
  1079. userContentDomainAccessCheckAssigment(cb) {
  1080. SplitTestHandler.getAssignment(
  1081. req,
  1082. res,
  1083. 'user-content-domain-access-check',
  1084. () => {
  1085. // We'll pick up the assignment from the res.locals assignment.
  1086. cb()
  1087. }
  1088. )
  1089. },
  1090. userContentDomainAccessCheckDelayAssigment(cb) {
  1091. SplitTestHandler.getAssignment(
  1092. req,
  1093. res,
  1094. 'user-content-domain-access-check-delay',
  1095. () => {
  1096. // We'll pick up the assignment from the res.locals assignment.
  1097. cb()
  1098. }
  1099. )
  1100. },
  1101. userContentDomainAccessCheckMaxChecksAssigment(cb) {
  1102. SplitTestHandler.getAssignment(
  1103. req,
  1104. res,
  1105. 'user-content-domain-access-check-max-checks',
  1106. () => {
  1107. // We'll pick up the assignment from the res.locals assignment.
  1108. cb()
  1109. }
  1110. )
  1111. },
  1112. reportUserContentDomainAccessCheckErrorAssigment(cb) {
  1113. SplitTestHandler.getAssignment(
  1114. req,
  1115. res,
  1116. 'report-user-content-domain-access-check-error',
  1117. () => {
  1118. // We'll pick up the assignment from the res.locals assignment.
  1119. cb()
  1120. }
  1121. )
  1122. },
  1123. },
  1124. (
  1125. err,
  1126. {
  1127. project,
  1128. user,
  1129. userHasInstitutionLicence,
  1130. learnedWords,
  1131. subscription,
  1132. userIsMemberOfGroupSubscription,
  1133. isTokenMember,
  1134. isInvitedMember,
  1135. brandVariation,
  1136. visualEditorNameAssignment,
  1137. participatingInVisualEditorNamingTest,
  1138. legacySourceEditorAssignment,
  1139. pdfjsAssignment,
  1140. editorLeftMenuAssignment,
  1141. richTextAssignment,
  1142. onboardingVideoTourAssignment,
  1143. historyViewAssignment,
  1144. }
  1145. ) => {
  1146. if (err != null) {
  1147. OError.tag(err, 'error getting details for project page')
  1148. return next(err)
  1149. }
  1150. const anonRequestToken = TokenAccessHandler.getRequestToken(
  1151. req,
  1152. projectId
  1153. )
  1154. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  1155. AuthorizationManager.getPrivilegeLevelForProject(
  1156. userId,
  1157. projectId,
  1158. anonRequestToken,
  1159. (error, privilegeLevel) => {
  1160. let allowedFreeTrial = true
  1161. if (error != null) {
  1162. return next(error)
  1163. }
  1164. if (
  1165. privilegeLevel == null ||
  1166. privilegeLevel === PrivilegeLevels.NONE
  1167. ) {
  1168. return res.sendStatus(401)
  1169. }
  1170. if (subscription != null) {
  1171. allowedFreeTrial = false
  1172. }
  1173. let wsUrl = Settings.wsUrl
  1174. let metricName = 'load-editor-ws'
  1175. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  1176. wsUrl = Settings.wsUrlBeta
  1177. metricName += '-beta'
  1178. } else if (
  1179. Settings.wsUrlV2 &&
  1180. Settings.wsUrlV2Percentage > 0 &&
  1181. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  1182. Settings.wsUrlV2Percentage
  1183. ) {
  1184. wsUrl = Settings.wsUrlV2
  1185. metricName += '-v2'
  1186. }
  1187. if (req.query && req.query.ws === 'fallback') {
  1188. // `?ws=fallback` will connect to the bare origin, and ignore
  1189. // the custom wsUrl. Hence it must load the client side
  1190. // javascript from there too.
  1191. // Not resetting it here would possibly load a socket.io v2
  1192. // client and connect to a v0 endpoint.
  1193. wsUrl = undefined
  1194. metricName += '-fallback'
  1195. }
  1196. metrics.inc(metricName)
  1197. if (userId) {
  1198. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  1199. projectId: project._id,
  1200. })
  1201. }
  1202. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  1203. function shouldDisplayFeature(name, variantFlag) {
  1204. if (req.query && req.query[name]) {
  1205. return req.query[name] === 'true'
  1206. } else {
  1207. return variantFlag === true
  1208. }
  1209. }
  1210. const isAdminOrTemplateOwner =
  1211. hasAdminAccess(user) || Settings.templates?.user_id === userId
  1212. const showTemplatesServerPro =
  1213. Features.hasFeature('templates-server-pro') &&
  1214. isAdminOrTemplateOwner
  1215. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  1216. const detachRole = req.params.detachRole
  1217. const showLegacySourceEditor =
  1218. !Features.hasFeature('saas') ||
  1219. // Allow override via legacy_source_editor=true in query string
  1220. shouldDisplayFeature('legacy_source_editor') ||
  1221. // Hide Ace for beta users
  1222. (!user.betaProgram &&
  1223. legacySourceEditorAssignment.variant === 'default')
  1224. const editorLeftMenuReact =
  1225. editorLeftMenuAssignment?.variant === 'react'
  1226. const showSymbolPalette =
  1227. !Features.hasFeature('saas') ||
  1228. (user.features && user.features.symbolPalette)
  1229. // It would be nice if this could go in the Galileo module but
  1230. // nothing else does that
  1231. const galileoEnabled = req.query?.galileo || ''
  1232. const galileoFeatures =
  1233. req.query && 'galileoFeatures' in req.query
  1234. ? req.query.galileoFeatures.split(',').map(f => f.trim())
  1235. : ['all']
  1236. const galileoPromptWords = req.query?.galileoPromptWords || ''
  1237. // Persistent upgrade prompts
  1238. // in header & in share project modal
  1239. const showUpgradePrompt =
  1240. Features.hasFeature('saas') &&
  1241. userId &&
  1242. !subscription &&
  1243. !userIsMemberOfGroupSubscription &&
  1244. !userHasInstitutionLicence
  1245. const showOnboardingVideoTour =
  1246. Features.hasFeature('saas') &&
  1247. userId &&
  1248. onboardingVideoTourAssignment.variant === 'active' &&
  1249. req.session.justRegistered
  1250. const showPersonalAccessToken =
  1251. !Features.hasFeature('saas') ||
  1252. req.query?.personal_access_token === 'true'
  1253. const template =
  1254. detachRole === 'detached'
  1255. ? 'project/editor_detached'
  1256. : 'project/editor'
  1257. const isParticipatingInVisualEditorNamingTest =
  1258. Features.hasFeature('saas') &&
  1259. participatingInVisualEditorNamingTest
  1260. let richTextVariant
  1261. if (!Features.hasFeature('saas')) {
  1262. richTextVariant = 'cm6'
  1263. } else {
  1264. richTextVariant = richTextAssignment.variant
  1265. }
  1266. res.render(template, {
  1267. title: project.name,
  1268. priority_title: true,
  1269. bodyClasses: ['editor'],
  1270. project_id: project._id,
  1271. projectName: project.name,
  1272. editorLeftMenuReact,
  1273. user: {
  1274. id: userId,
  1275. email: user.email,
  1276. first_name: user.first_name,
  1277. last_name: user.last_name,
  1278. referal_id: user.referal_id,
  1279. signUpDate: user.signUpDate,
  1280. allowedFreeTrial,
  1281. featureSwitches: user.featureSwitches,
  1282. features: user.features,
  1283. refProviders: _.mapValues(user.refProviders, Boolean),
  1284. alphaProgram: user.alphaProgram,
  1285. betaProgram: user.betaProgram,
  1286. labsProgram: user.labsProgram,
  1287. labsProgramGalileo: user.labsProgramGalileo,
  1288. isAdmin: hasAdminAccess(user),
  1289. },
  1290. userSettings: {
  1291. mode: user.ace.mode,
  1292. editorTheme: user.ace.theme,
  1293. fontSize: user.ace.fontSize,
  1294. autoComplete: user.ace.autoComplete,
  1295. autoPairDelimiters: user.ace.autoPairDelimiters,
  1296. pdfViewer: user.ace.pdfViewer,
  1297. syntaxValidation: user.ace.syntaxValidation,
  1298. fontFamily: user.ace.fontFamily || 'lucida',
  1299. lineHeight: user.ace.lineHeight || 'normal',
  1300. overallTheme: user.ace.overallTheme,
  1301. },
  1302. privilegeLevel,
  1303. anonymous,
  1304. anonymousAccessToken: anonymous ? anonRequestToken : null,
  1305. isTokenMember,
  1306. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  1307. userId,
  1308. privilegeLevel,
  1309. isTokenMember,
  1310. isInvitedMember
  1311. ),
  1312. languages: Settings.languages,
  1313. learnedWords,
  1314. editorThemes: THEME_LIST,
  1315. legacyEditorThemes: LEGACY_THEME_LIST,
  1316. maxDocLength: Settings.max_doc_length,
  1317. useV2History:
  1318. project.overleaf &&
  1319. project.overleaf.history &&
  1320. Boolean(project.overleaf.history.display),
  1321. brandVariation,
  1322. allowedImageNames,
  1323. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  1324. wsUrl,
  1325. showSupport: Features.hasFeature('support'),
  1326. showTemplatesServerPro,
  1327. pdfjsVariant: pdfjsAssignment.variant,
  1328. debugPdfDetach,
  1329. isParticipatingInVisualEditorNamingTest,
  1330. visualEditorNameVariant: visualEditorNameAssignment.variant,
  1331. showLegacySourceEditor,
  1332. showSymbolPalette,
  1333. galileoEnabled,
  1334. galileoFeatures,
  1335. galileoPromptWords,
  1336. detachRole,
  1337. metadata: { viewport: false },
  1338. showUpgradePrompt,
  1339. fixedSizeDocument: true,
  1340. useOpenTelemetry: Settings.useOpenTelemetryClient,
  1341. showCM6SwitchAwaySurvey: Settings.showCM6SwitchAwaySurvey,
  1342. richTextVariant,
  1343. showOnboardingVideoTour,
  1344. historyViewReact: historyViewAssignment.variant === 'react',
  1345. showPersonalAccessToken,
  1346. })
  1347. timer.done()
  1348. }
  1349. )
  1350. }
  1351. )
  1352. },
  1353. _refreshFeatures(req, user, callback) {
  1354. // If the feature refresh has failed in this session, don't retry
  1355. // it - require the user to log in again.
  1356. if (req.session.feature_refresh_failed) {
  1357. metrics.inc('features-refresh', 1, {
  1358. path: 'load-editor',
  1359. status: 'skipped',
  1360. })
  1361. return callback(null, user)
  1362. }
  1363. // If the refresh takes too long then return the current
  1364. // features. Note that the user.features property may still be
  1365. // updated in the background after the callback is called.
  1366. callback = _.once(callback)
  1367. const refreshTimeoutHandler = setTimeout(() => {
  1368. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  1369. metrics.inc('features-refresh', 1, {
  1370. path: 'load-editor',
  1371. status: 'timeout',
  1372. })
  1373. callback(null, user)
  1374. }, 5000)
  1375. // try to refresh user features now
  1376. const timer = new metrics.Timer('features-refresh-on-load-editor')
  1377. FeaturesUpdater.refreshFeatures(
  1378. user._id,
  1379. 'load-editor',
  1380. (err, features) => {
  1381. clearTimeout(refreshTimeoutHandler)
  1382. timer.done()
  1383. if (err) {
  1384. // keep a record to prevent unneceary retries and leave
  1385. // the original features unmodified if the refresh failed
  1386. req.session.feature_refresh_failed = {
  1387. reason: 'error',
  1388. at: new Date(),
  1389. }
  1390. metrics.inc('features-refresh', 1, {
  1391. path: 'load-editor',
  1392. status: 'error',
  1393. })
  1394. } else {
  1395. user.features = features
  1396. metrics.inc('features-refresh', 1, {
  1397. path: 'load-editor',
  1398. status: 'success',
  1399. })
  1400. }
  1401. callback(null, user)
  1402. }
  1403. )
  1404. },
  1405. _buildProjectList(allProjects, userId) {
  1406. let project
  1407. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  1408. allProjects
  1409. const projects = []
  1410. for (project of owned) {
  1411. projects.push(
  1412. ProjectController._buildProjectViewModel(
  1413. project,
  1414. 'owner',
  1415. Sources.OWNER,
  1416. userId
  1417. )
  1418. )
  1419. }
  1420. // Invite-access
  1421. for (project of readAndWrite) {
  1422. projects.push(
  1423. ProjectController._buildProjectViewModel(
  1424. project,
  1425. 'readWrite',
  1426. Sources.INVITE,
  1427. userId
  1428. )
  1429. )
  1430. }
  1431. for (project of readOnly) {
  1432. projects.push(
  1433. ProjectController._buildProjectViewModel(
  1434. project,
  1435. 'readOnly',
  1436. Sources.INVITE,
  1437. userId
  1438. )
  1439. )
  1440. }
  1441. // Token-access
  1442. // Only add these projects if they're not already present, this gives us cascading access
  1443. // from 'owner' => 'token-read-only'
  1444. for (project of tokenReadAndWrite) {
  1445. if (
  1446. projects.filter(p => p.id.toString() === project._id.toString())
  1447. .length === 0
  1448. ) {
  1449. projects.push(
  1450. ProjectController._buildProjectViewModel(
  1451. project,
  1452. 'readAndWrite',
  1453. Sources.TOKEN,
  1454. userId
  1455. )
  1456. )
  1457. }
  1458. }
  1459. for (project of tokenReadOnly) {
  1460. if (
  1461. projects.filter(p => p.id.toString() === project._id.toString())
  1462. .length === 0
  1463. ) {
  1464. projects.push(
  1465. ProjectController._buildProjectViewModel(
  1466. project,
  1467. 'readOnly',
  1468. Sources.TOKEN,
  1469. userId
  1470. )
  1471. )
  1472. }
  1473. }
  1474. return projects
  1475. },
  1476. _buildProjectViewModel(project, accessLevel, source, userId) {
  1477. const archived = ProjectHelper.isArchived(project, userId)
  1478. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1479. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1480. TokenAccessHandler.protectTokens(project, accessLevel)
  1481. const model = {
  1482. id: project._id,
  1483. name: project.name,
  1484. lastUpdated: project.lastUpdated,
  1485. lastUpdatedBy: project.lastUpdatedBy,
  1486. publicAccessLevel: project.publicAccesLevel,
  1487. accessLevel,
  1488. source,
  1489. archived,
  1490. trashed,
  1491. owner_ref: project.owner_ref,
  1492. isV1Project: false,
  1493. }
  1494. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1495. model.owner_ref = null
  1496. model.lastUpdatedBy = null
  1497. }
  1498. return model
  1499. },
  1500. _injectProjectUsers(projects, callback) {
  1501. const users = {}
  1502. for (const project of projects) {
  1503. if (project.owner_ref != null) {
  1504. users[project.owner_ref.toString()] = true
  1505. }
  1506. if (project.lastUpdatedBy != null) {
  1507. users[project.lastUpdatedBy.toString()] = true
  1508. }
  1509. }
  1510. const userIds = Object.keys(users)
  1511. async.eachSeries(
  1512. userIds,
  1513. (userId, cb) => {
  1514. UserGetter.getUser(
  1515. userId,
  1516. { first_name: 1, last_name: 1, email: 1 },
  1517. (error, user) => {
  1518. if (error != null) {
  1519. return cb(error)
  1520. }
  1521. users[userId] = user
  1522. cb()
  1523. }
  1524. )
  1525. },
  1526. error => {
  1527. if (error != null) {
  1528. return callback(error)
  1529. }
  1530. for (const project of projects) {
  1531. if (project.owner_ref != null) {
  1532. project.owner = users[project.owner_ref.toString()]
  1533. }
  1534. if (project.lastUpdatedBy != null) {
  1535. project.lastUpdatedBy =
  1536. users[project.lastUpdatedBy.toString()] || null
  1537. }
  1538. }
  1539. callback(null, projects)
  1540. }
  1541. )
  1542. },
  1543. _buildPortalTemplatesList(affiliations) {
  1544. if (affiliations == null) {
  1545. affiliations = []
  1546. }
  1547. const portalTemplates = []
  1548. for (const aff of affiliations) {
  1549. if (
  1550. aff.portal &&
  1551. aff.portal.slug &&
  1552. aff.portal.templates_count &&
  1553. aff.portal.templates_count > 0
  1554. ) {
  1555. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1556. portalTemplates.push({
  1557. name: aff.institution.name,
  1558. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1559. })
  1560. }
  1561. }
  1562. return portalTemplates
  1563. },
  1564. }
  1565. const defaultSettingsForAnonymousUser = userId => ({
  1566. id: userId,
  1567. ace: {
  1568. mode: 'none',
  1569. theme: 'textmate',
  1570. fontSize: '12',
  1571. autoComplete: true,
  1572. spellCheckLanguage: '',
  1573. pdfViewer: '',
  1574. syntaxValidation: true,
  1575. },
  1576. subscription: {
  1577. freeTrial: {
  1578. allowed: true,
  1579. },
  1580. },
  1581. featureSwitches: {
  1582. github: false,
  1583. },
  1584. alphaProgram: false,
  1585. betaProgram: false,
  1586. })
  1587. const THEME_LIST = [
  1588. 'cobalt',
  1589. 'dracula',
  1590. 'eclipse',
  1591. 'monokai',
  1592. 'overleaf',
  1593. 'textmate',
  1594. ]
  1595. const LEGACY_THEME_LIST = [
  1596. 'ambiance',
  1597. 'chaos',
  1598. 'chrome',
  1599. 'clouds',
  1600. 'clouds_midnight',
  1601. 'crimson_editor',
  1602. 'dawn',
  1603. 'dreamweaver',
  1604. 'github',
  1605. 'gob',
  1606. 'gruvbox',
  1607. 'idle_fingers',
  1608. 'iplastic',
  1609. 'katzenmilch',
  1610. 'kr_theme',
  1611. 'kuroir',
  1612. 'merbivore',
  1613. 'merbivore_soft',
  1614. 'mono_industrial',
  1615. 'nord_dark',
  1616. 'pastel_on_dark',
  1617. 'solarized_dark',
  1618. 'solarized_light',
  1619. 'sqlserver',
  1620. 'terminal',
  1621. 'tomorrow',
  1622. 'tomorrow_night',
  1623. 'tomorrow_night_blue',
  1624. 'tomorrow_night_bright',
  1625. 'tomorrow_night_eighties',
  1626. 'twilight',
  1627. 'vibrant_ink',
  1628. 'xcode',
  1629. ]
  1630. module.exports = ProjectController