ProjectController.js 48 KB

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