ProjectController.js 49 KB

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