ProjectController.js 48 KB

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