ProjectController.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  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. onboardingVideoTourAssignment(cb) {
  1022. SplitTestHandler.getAssignment(
  1023. req,
  1024. res,
  1025. 'onboarding-video-tour',
  1026. (error, assignment) => {
  1027. // do not fail editor load if assignment fails
  1028. if (error) {
  1029. cb(null, { variant: 'default' })
  1030. } else {
  1031. cb(null, assignment)
  1032. }
  1033. }
  1034. )
  1035. },
  1036. historyViewAssignment(cb) {
  1037. SplitTestHandler.getAssignment(
  1038. req,
  1039. res,
  1040. 'history-view',
  1041. (error, assignment) => {
  1042. // do not fail editor load if assignment fails
  1043. if (error) {
  1044. cb(null, { variant: 'default' })
  1045. } else {
  1046. cb(null, assignment)
  1047. }
  1048. }
  1049. )
  1050. },
  1051. accessCheckForOldCompileDomainAssigment(cb) {
  1052. SplitTestHandler.getAssignment(
  1053. req,
  1054. res,
  1055. 'access-check-for-old-compile-domain',
  1056. () => {
  1057. // We'll pick up the assignment from the res.locals assignment.
  1058. cb()
  1059. }
  1060. )
  1061. },
  1062. forceNewDomainAssignment(cb) {
  1063. SplitTestHandler.getAssignment(
  1064. req,
  1065. res,
  1066. 'force-new-compile-domain',
  1067. () => {
  1068. // We'll pick up the assignment from the res.locals assignment.
  1069. cb()
  1070. }
  1071. )
  1072. },
  1073. userContentDomainAccessCheckAssigment(cb) {
  1074. SplitTestHandler.getAssignment(
  1075. req,
  1076. res,
  1077. 'user-content-domain-access-check',
  1078. () => {
  1079. // We'll pick up the assignment from the res.locals assignment.
  1080. cb()
  1081. }
  1082. )
  1083. },
  1084. userContentDomainAccessCheckDelayAssigment(cb) {
  1085. SplitTestHandler.getAssignment(
  1086. req,
  1087. res,
  1088. 'user-content-domain-access-check-delay',
  1089. () => {
  1090. // We'll pick up the assignment from the res.locals assignment.
  1091. cb()
  1092. }
  1093. )
  1094. },
  1095. userContentDomainAccessCheckMaxChecksAssigment(cb) {
  1096. SplitTestHandler.getAssignment(
  1097. req,
  1098. res,
  1099. 'user-content-domain-access-check-max-checks',
  1100. () => {
  1101. // We'll pick up the assignment from the res.locals assignment.
  1102. cb()
  1103. }
  1104. )
  1105. },
  1106. reportUserContentDomainAccessCheckErrorAssigment(cb) {
  1107. SplitTestHandler.getAssignment(
  1108. req,
  1109. res,
  1110. 'report-user-content-domain-access-check-error',
  1111. () => {
  1112. // We'll pick up the assignment from the res.locals assignment.
  1113. cb()
  1114. }
  1115. )
  1116. },
  1117. },
  1118. (
  1119. err,
  1120. {
  1121. project,
  1122. user,
  1123. userHasInstitutionLicence,
  1124. learnedWords,
  1125. subscription,
  1126. userIsMemberOfGroupSubscription,
  1127. isTokenMember,
  1128. isInvitedMember,
  1129. brandVariation,
  1130. visualEditorNameAssignment,
  1131. participatingInVisualEditorNamingTest,
  1132. legacySourceEditorAssignment,
  1133. pdfjsAssignment,
  1134. editorLeftMenuAssignment,
  1135. richTextAssignment,
  1136. onboardingVideoTourAssignment,
  1137. historyViewAssignment,
  1138. }
  1139. ) => {
  1140. if (err != null) {
  1141. OError.tag(err, 'error getting details for project page')
  1142. return next(err)
  1143. }
  1144. const anonRequestToken = TokenAccessHandler.getRequestToken(
  1145. req,
  1146. projectId
  1147. )
  1148. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(user)
  1149. AuthorizationManager.getPrivilegeLevelForProject(
  1150. userId,
  1151. projectId,
  1152. anonRequestToken,
  1153. (error, privilegeLevel) => {
  1154. let allowedFreeTrial = true
  1155. if (error != null) {
  1156. return next(error)
  1157. }
  1158. if (
  1159. privilegeLevel == null ||
  1160. privilegeLevel === PrivilegeLevels.NONE
  1161. ) {
  1162. return res.sendStatus(401)
  1163. }
  1164. if (subscription != null) {
  1165. allowedFreeTrial = false
  1166. }
  1167. let wsUrl = Settings.wsUrl
  1168. let metricName = 'load-editor-ws'
  1169. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  1170. wsUrl = Settings.wsUrlBeta
  1171. metricName += '-beta'
  1172. } else if (
  1173. Settings.wsUrlV2 &&
  1174. Settings.wsUrlV2Percentage > 0 &&
  1175. (ObjectId(projectId).getTimestamp() / 1000) % 100 <
  1176. Settings.wsUrlV2Percentage
  1177. ) {
  1178. wsUrl = Settings.wsUrlV2
  1179. metricName += '-v2'
  1180. }
  1181. if (req.query && req.query.ws === 'fallback') {
  1182. // `?ws=fallback` will connect to the bare origin, and ignore
  1183. // the custom wsUrl. Hence it must load the client side
  1184. // javascript from there too.
  1185. // Not resetting it here would possibly load a socket.io v2
  1186. // client and connect to a v0 endpoint.
  1187. wsUrl = undefined
  1188. metricName += '-fallback'
  1189. }
  1190. metrics.inc(metricName)
  1191. if (userId) {
  1192. AnalyticsManager.recordEventForUser(userId, 'project-opened', {
  1193. projectId: project._id,
  1194. })
  1195. }
  1196. // should not be used in place of split tests query param overrides (?my-split-test-name=my-variant)
  1197. function shouldDisplayFeature(name, variantFlag) {
  1198. if (req.query && req.query[name]) {
  1199. return req.query[name] === 'true'
  1200. } else {
  1201. return variantFlag === true
  1202. }
  1203. }
  1204. const isAdminOrTemplateOwner =
  1205. hasAdminAccess(user) || Settings.templates?.user_id === userId
  1206. const showTemplatesServerPro =
  1207. Features.hasFeature('templates-server-pro') &&
  1208. isAdminOrTemplateOwner
  1209. const debugPdfDetach = shouldDisplayFeature('debug_pdf_detach')
  1210. const detachRole = req.params.detachRole
  1211. const showLegacySourceEditor =
  1212. !Features.hasFeature('saas') ||
  1213. // Allow override via legacy_source_editor=true in query string
  1214. shouldDisplayFeature('legacy_source_editor') ||
  1215. // Hide Ace for beta users
  1216. (!user.betaProgram &&
  1217. legacySourceEditorAssignment.variant === 'default')
  1218. const editorLeftMenuReact =
  1219. editorLeftMenuAssignment?.variant === 'react'
  1220. const showSymbolPalette =
  1221. !Features.hasFeature('saas') ||
  1222. (user.features && user.features.symbolPalette)
  1223. // It would be nice if this could go in the Galileo module but
  1224. // nothing else does that
  1225. const galileoEnabled = req.query?.galileo || ''
  1226. const galileoFeatures =
  1227. req.query && 'galileoFeatures' in req.query
  1228. ? req.query.galileoFeatures.split(',').map(f => f.trim())
  1229. : ['all']
  1230. const galileoPromptWords = req.query?.galileoPromptWords || ''
  1231. // Persistent upgrade prompts
  1232. // in header & in share project modal
  1233. const showUpgradePrompt =
  1234. Features.hasFeature('saas') &&
  1235. userId &&
  1236. !subscription &&
  1237. !userIsMemberOfGroupSubscription &&
  1238. !userHasInstitutionLicence
  1239. const showOnboardingVideoTour =
  1240. Features.hasFeature('saas') &&
  1241. userId &&
  1242. onboardingVideoTourAssignment.variant === 'active' &&
  1243. req.session.justRegistered
  1244. const showPersonalAccessToken =
  1245. !Features.hasFeature('saas') ||
  1246. req.query?.personal_access_token === 'true'
  1247. const template =
  1248. detachRole === 'detached'
  1249. ? 'project/editor_detached'
  1250. : 'project/editor'
  1251. const isParticipatingInVisualEditorNamingTest =
  1252. Features.hasFeature('saas') &&
  1253. participatingInVisualEditorNamingTest
  1254. res.render(template, {
  1255. title: project.name,
  1256. priority_title: true,
  1257. bodyClasses: ['editor'],
  1258. project_id: project._id,
  1259. projectName: project.name,
  1260. editorLeftMenuReact,
  1261. user: {
  1262. id: userId,
  1263. email: user.email,
  1264. first_name: user.first_name,
  1265. last_name: user.last_name,
  1266. referal_id: user.referal_id,
  1267. signUpDate: user.signUpDate,
  1268. allowedFreeTrial,
  1269. featureSwitches: user.featureSwitches,
  1270. features: user.features,
  1271. refProviders: _.mapValues(user.refProviders, Boolean),
  1272. alphaProgram: user.alphaProgram,
  1273. betaProgram: user.betaProgram,
  1274. labsProgram: user.labsProgram,
  1275. labsProgramGalileo: user.labsProgramGalileo,
  1276. isAdmin: hasAdminAccess(user),
  1277. },
  1278. userSettings: {
  1279. mode: user.ace.mode,
  1280. editorTheme: user.ace.theme,
  1281. fontSize: user.ace.fontSize,
  1282. autoComplete: user.ace.autoComplete,
  1283. autoPairDelimiters: user.ace.autoPairDelimiters,
  1284. pdfViewer: user.ace.pdfViewer,
  1285. syntaxValidation: user.ace.syntaxValidation,
  1286. fontFamily: user.ace.fontFamily || 'lucida',
  1287. lineHeight: user.ace.lineHeight || 'normal',
  1288. overallTheme: user.ace.overallTheme,
  1289. },
  1290. privilegeLevel,
  1291. anonymous,
  1292. anonymousAccessToken: anonymous ? anonRequestToken : null,
  1293. isTokenMember,
  1294. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  1295. userId,
  1296. privilegeLevel,
  1297. isTokenMember,
  1298. isInvitedMember
  1299. ),
  1300. languages: Settings.languages,
  1301. learnedWords,
  1302. editorThemes: THEME_LIST,
  1303. legacyEditorThemes: LEGACY_THEME_LIST,
  1304. maxDocLength: Settings.max_doc_length,
  1305. useV2History:
  1306. project.overleaf &&
  1307. project.overleaf.history &&
  1308. Boolean(project.overleaf.history.display),
  1309. brandVariation,
  1310. allowedImageNames,
  1311. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  1312. wsUrl,
  1313. showSupport: Features.hasFeature('support'),
  1314. showTemplatesServerPro,
  1315. pdfjsVariant: pdfjsAssignment.variant,
  1316. debugPdfDetach,
  1317. isParticipatingInVisualEditorNamingTest,
  1318. visualEditorNameVariant: visualEditorNameAssignment.variant,
  1319. showLegacySourceEditor,
  1320. showSymbolPalette,
  1321. galileoEnabled,
  1322. galileoFeatures,
  1323. galileoPromptWords,
  1324. detachRole,
  1325. metadata: { viewport: false },
  1326. showUpgradePrompt,
  1327. fixedSizeDocument: true,
  1328. useOpenTelemetry: Settings.useOpenTelemetryClient,
  1329. showCM6SwitchAwaySurvey: Settings.showCM6SwitchAwaySurvey,
  1330. richTextVariant: richTextAssignment.variant,
  1331. showOnboardingVideoTour,
  1332. historyViewReact: historyViewAssignment.variant === 'react',
  1333. showPersonalAccessToken,
  1334. })
  1335. timer.done()
  1336. }
  1337. )
  1338. }
  1339. )
  1340. },
  1341. _refreshFeatures(req, user, callback) {
  1342. // If the feature refresh has failed in this session, don't retry
  1343. // it - require the user to log in again.
  1344. if (req.session.feature_refresh_failed) {
  1345. metrics.inc('features-refresh', 1, {
  1346. path: 'load-editor',
  1347. status: 'skipped',
  1348. })
  1349. return callback(null, user)
  1350. }
  1351. // If the refresh takes too long then return the current
  1352. // features. Note that the user.features property may still be
  1353. // updated in the background after the callback is called.
  1354. callback = _.once(callback)
  1355. const refreshTimeoutHandler = setTimeout(() => {
  1356. req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  1357. metrics.inc('features-refresh', 1, {
  1358. path: 'load-editor',
  1359. status: 'timeout',
  1360. })
  1361. callback(null, user)
  1362. }, 5000)
  1363. // try to refresh user features now
  1364. const timer = new metrics.Timer('features-refresh-on-load-editor')
  1365. FeaturesUpdater.refreshFeatures(
  1366. user._id,
  1367. 'load-editor',
  1368. (err, features) => {
  1369. clearTimeout(refreshTimeoutHandler)
  1370. timer.done()
  1371. if (err) {
  1372. // keep a record to prevent unneceary retries and leave
  1373. // the original features unmodified if the refresh failed
  1374. req.session.feature_refresh_failed = {
  1375. reason: 'error',
  1376. at: new Date(),
  1377. }
  1378. metrics.inc('features-refresh', 1, {
  1379. path: 'load-editor',
  1380. status: 'error',
  1381. })
  1382. } else {
  1383. user.features = features
  1384. metrics.inc('features-refresh', 1, {
  1385. path: 'load-editor',
  1386. status: 'success',
  1387. })
  1388. }
  1389. callback(null, user)
  1390. }
  1391. )
  1392. },
  1393. _buildProjectList(allProjects, userId) {
  1394. let project
  1395. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  1396. allProjects
  1397. const projects = []
  1398. for (project of owned) {
  1399. projects.push(
  1400. ProjectController._buildProjectViewModel(
  1401. project,
  1402. 'owner',
  1403. Sources.OWNER,
  1404. userId
  1405. )
  1406. )
  1407. }
  1408. // Invite-access
  1409. for (project of readAndWrite) {
  1410. projects.push(
  1411. ProjectController._buildProjectViewModel(
  1412. project,
  1413. 'readWrite',
  1414. Sources.INVITE,
  1415. userId
  1416. )
  1417. )
  1418. }
  1419. for (project of readOnly) {
  1420. projects.push(
  1421. ProjectController._buildProjectViewModel(
  1422. project,
  1423. 'readOnly',
  1424. Sources.INVITE,
  1425. userId
  1426. )
  1427. )
  1428. }
  1429. // Token-access
  1430. // Only add these projects if they're not already present, this gives us cascading access
  1431. // from 'owner' => 'token-read-only'
  1432. for (project of tokenReadAndWrite) {
  1433. if (
  1434. projects.filter(p => p.id.toString() === project._id.toString())
  1435. .length === 0
  1436. ) {
  1437. projects.push(
  1438. ProjectController._buildProjectViewModel(
  1439. project,
  1440. 'readAndWrite',
  1441. Sources.TOKEN,
  1442. userId
  1443. )
  1444. )
  1445. }
  1446. }
  1447. for (project of tokenReadOnly) {
  1448. if (
  1449. projects.filter(p => p.id.toString() === project._id.toString())
  1450. .length === 0
  1451. ) {
  1452. projects.push(
  1453. ProjectController._buildProjectViewModel(
  1454. project,
  1455. 'readOnly',
  1456. Sources.TOKEN,
  1457. userId
  1458. )
  1459. )
  1460. }
  1461. }
  1462. return projects
  1463. },
  1464. _buildProjectViewModel(project, accessLevel, source, userId) {
  1465. const archived = ProjectHelper.isArchived(project, userId)
  1466. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  1467. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  1468. TokenAccessHandler.protectTokens(project, accessLevel)
  1469. const model = {
  1470. id: project._id,
  1471. name: project.name,
  1472. lastUpdated: project.lastUpdated,
  1473. lastUpdatedBy: project.lastUpdatedBy,
  1474. publicAccessLevel: project.publicAccesLevel,
  1475. accessLevel,
  1476. source,
  1477. archived,
  1478. trashed,
  1479. owner_ref: project.owner_ref,
  1480. isV1Project: false,
  1481. }
  1482. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  1483. model.owner_ref = null
  1484. model.lastUpdatedBy = null
  1485. }
  1486. return model
  1487. },
  1488. _injectProjectUsers(projects, callback) {
  1489. const users = {}
  1490. for (const project of projects) {
  1491. if (project.owner_ref != null) {
  1492. users[project.owner_ref.toString()] = true
  1493. }
  1494. if (project.lastUpdatedBy != null) {
  1495. users[project.lastUpdatedBy.toString()] = true
  1496. }
  1497. }
  1498. const userIds = Object.keys(users)
  1499. async.eachSeries(
  1500. userIds,
  1501. (userId, cb) => {
  1502. UserGetter.getUser(
  1503. userId,
  1504. { first_name: 1, last_name: 1, email: 1 },
  1505. (error, user) => {
  1506. if (error != null) {
  1507. return cb(error)
  1508. }
  1509. users[userId] = user
  1510. cb()
  1511. }
  1512. )
  1513. },
  1514. error => {
  1515. if (error != null) {
  1516. return callback(error)
  1517. }
  1518. for (const project of projects) {
  1519. if (project.owner_ref != null) {
  1520. project.owner = users[project.owner_ref.toString()]
  1521. }
  1522. if (project.lastUpdatedBy != null) {
  1523. project.lastUpdatedBy =
  1524. users[project.lastUpdatedBy.toString()] || null
  1525. }
  1526. }
  1527. callback(null, projects)
  1528. }
  1529. )
  1530. },
  1531. _buildPortalTemplatesList(affiliations) {
  1532. if (affiliations == null) {
  1533. affiliations = []
  1534. }
  1535. const portalTemplates = []
  1536. for (const aff of affiliations) {
  1537. if (
  1538. aff.portal &&
  1539. aff.portal.slug &&
  1540. aff.portal.templates_count &&
  1541. aff.portal.templates_count > 0
  1542. ) {
  1543. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  1544. portalTemplates.push({
  1545. name: aff.institution.name,
  1546. url: Settings.siteUrl + portalPath + aff.portal.slug,
  1547. })
  1548. }
  1549. }
  1550. return portalTemplates
  1551. },
  1552. }
  1553. const defaultSettingsForAnonymousUser = userId => ({
  1554. id: userId,
  1555. ace: {
  1556. mode: 'none',
  1557. theme: 'textmate',
  1558. fontSize: '12',
  1559. autoComplete: true,
  1560. spellCheckLanguage: '',
  1561. pdfViewer: '',
  1562. syntaxValidation: true,
  1563. },
  1564. subscription: {
  1565. freeTrial: {
  1566. allowed: true,
  1567. },
  1568. },
  1569. featureSwitches: {
  1570. github: false,
  1571. },
  1572. alphaProgram: false,
  1573. betaProgram: false,
  1574. })
  1575. const THEME_LIST = [
  1576. 'cobalt',
  1577. 'dracula',
  1578. 'eclipse',
  1579. 'monokai',
  1580. 'overleaf',
  1581. 'textmate',
  1582. ]
  1583. const LEGACY_THEME_LIST = [
  1584. 'ambiance',
  1585. 'chaos',
  1586. 'chrome',
  1587. 'clouds',
  1588. 'clouds_midnight',
  1589. 'crimson_editor',
  1590. 'dawn',
  1591. 'dreamweaver',
  1592. 'github',
  1593. 'gob',
  1594. 'gruvbox',
  1595. 'idle_fingers',
  1596. 'iplastic',
  1597. 'katzenmilch',
  1598. 'kr_theme',
  1599. 'kuroir',
  1600. 'merbivore',
  1601. 'merbivore_soft',
  1602. 'mono_industrial',
  1603. 'nord_dark',
  1604. 'pastel_on_dark',
  1605. 'solarized_dark',
  1606. 'solarized_light',
  1607. 'sqlserver',
  1608. 'terminal',
  1609. 'tomorrow',
  1610. 'tomorrow_night',
  1611. 'tomorrow_night_blue',
  1612. 'tomorrow_night_bright',
  1613. 'tomorrow_night_eighties',
  1614. 'twilight',
  1615. 'vibrant_ink',
  1616. 'xcode',
  1617. ]
  1618. module.exports = ProjectController