ProjectController.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. const Path = require('path')
  2. const fs = require('fs')
  3. const crypto = require('crypto')
  4. const async = require('async')
  5. const logger = require('logger-sharelatex')
  6. const ProjectDeleter = require('./ProjectDeleter')
  7. const ProjectDuplicator = require('./ProjectDuplicator')
  8. const ProjectCreationHandler = require('./ProjectCreationHandler')
  9. const EditorController = require('../Editor/EditorController')
  10. const ProjectHelper = require('./ProjectHelper')
  11. const metrics = require('metrics-sharelatex')
  12. const { User } = require('../../models/User')
  13. const TagsHandler = require('../Tags/TagsHandler')
  14. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  15. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  16. const LimitationsManager = require('../Subscription/LimitationsManager')
  17. const Settings = require('settings-sharelatex')
  18. const AuthorizationManager = require('../Authorization/AuthorizationManager')
  19. const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
  20. const ProjectUpdateHandler = require('./ProjectUpdateHandler')
  21. const ProjectGetter = require('./ProjectGetter')
  22. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  23. const AuthenticationController = require('../Authentication/AuthenticationController')
  24. const PackageVersions = require('../../infrastructure/PackageVersions')
  25. const Sources = require('../Authorization/Sources')
  26. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  27. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  28. const Modules = require('../../infrastructure/Modules')
  29. const ProjectEntityHandler = require('./ProjectEntityHandler')
  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 { getUserAffiliations } = require('../Institutions/InstitutionsAPI')
  36. const V1Handler = require('../V1/V1Handler')
  37. const { Project } = require('../../models/Project')
  38. const ProjectController = {
  39. _isInPercentageRollout(rolloutName, objectId, percentage) {
  40. if (Settings.bypassPercentageRollouts === true) {
  41. return true
  42. }
  43. const data = `${rolloutName}:${objectId.toString()}`
  44. const md5hash = crypto
  45. .createHash('md5')
  46. .update(data)
  47. .digest('hex')
  48. const counter = parseInt(md5hash.slice(26, 32), 16)
  49. return counter % 100 < percentage
  50. },
  51. updateProjectSettings(req, res, next) {
  52. const projectId = req.params.Project_id
  53. const jobs = []
  54. if (req.body.compiler != null) {
  55. jobs.push(callback =>
  56. EditorController.setCompiler(projectId, req.body.compiler, callback)
  57. )
  58. }
  59. if (req.body.imageName != null) {
  60. jobs.push(callback =>
  61. EditorController.setImageName(projectId, req.body.imageName, callback)
  62. )
  63. }
  64. if (req.body.name != null) {
  65. jobs.push(callback =>
  66. EditorController.renameProject(projectId, req.body.name, callback)
  67. )
  68. }
  69. if (req.body.spellCheckLanguage != null) {
  70. jobs.push(callback =>
  71. EditorController.setSpellCheckLanguage(
  72. projectId,
  73. req.body.spellCheckLanguage,
  74. callback
  75. )
  76. )
  77. }
  78. if (req.body.rootDocId != null) {
  79. jobs.push(callback =>
  80. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  81. )
  82. }
  83. async.series(jobs, error => {
  84. if (error != null) {
  85. return next(error)
  86. }
  87. res.sendStatus(204)
  88. })
  89. },
  90. updateProjectAdminSettings(req, res, next) {
  91. const projectId = req.params.Project_id
  92. const jobs = []
  93. if (req.body.publicAccessLevel != null) {
  94. jobs.push(callback =>
  95. EditorController.setPublicAccessLevel(
  96. projectId,
  97. req.body.publicAccessLevel,
  98. callback
  99. )
  100. )
  101. }
  102. async.series(jobs, error => {
  103. if (error != null) {
  104. return next(error)
  105. }
  106. res.sendStatus(204)
  107. })
  108. },
  109. deleteProject(req, res) {
  110. const projectId = req.params.Project_id
  111. const forever = (req.query != null ? req.query.forever : undefined) != null
  112. logger.log({ projectId, forever }, 'received request to archive project')
  113. const user = AuthenticationController.getSessionUser(req)
  114. const cb = err => {
  115. if (err != null) {
  116. res.sendStatus(500)
  117. } else {
  118. res.sendStatus(200)
  119. }
  120. }
  121. if (forever) {
  122. ProjectDeleter.deleteProject(
  123. projectId,
  124. { deleterUser: user, ipAddress: req.ip },
  125. cb
  126. )
  127. } else {
  128. ProjectDeleter.legacyArchiveProject(projectId, cb)
  129. }
  130. },
  131. archiveProject(req, res, next) {
  132. const projectId = req.params.Project_id
  133. logger.log({ projectId }, 'received request to archive project')
  134. const user = AuthenticationController.getSessionUser(req)
  135. ProjectDeleter.archiveProject(projectId, user._id, function(err) {
  136. if (err != null) {
  137. return next(err)
  138. } else {
  139. return res.sendStatus(200)
  140. }
  141. })
  142. },
  143. unarchiveProject(req, res, next) {
  144. const projectId = req.params.Project_id
  145. logger.log({ projectId }, 'received request to unarchive project')
  146. const user = AuthenticationController.getSessionUser(req)
  147. ProjectDeleter.unarchiveProject(projectId, user._id, function(err) {
  148. if (err != null) {
  149. return next(err)
  150. } else {
  151. return res.sendStatus(200)
  152. }
  153. })
  154. },
  155. expireDeletedProjectsAfterDuration(req, res) {
  156. logger.log(
  157. 'received request to look for old deleted projects and expire them'
  158. )
  159. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  160. if (err != null) {
  161. res.sendStatus(500)
  162. } else {
  163. res.sendStatus(200)
  164. }
  165. })
  166. },
  167. expireDeletedProject(req, res, next) {
  168. const { projectId } = req.params
  169. logger.log('received request to expire deleted project', { projectId })
  170. ProjectDeleter.expireDeletedProject(projectId, err => {
  171. if (err != null) {
  172. next(err)
  173. } else {
  174. res.sendStatus(200)
  175. }
  176. })
  177. },
  178. restoreProject(req, res) {
  179. const projectId = req.params.Project_id
  180. logger.log({ projectId }, 'received request to restore project')
  181. ProjectDeleter.restoreProject(projectId, err => {
  182. if (err != null) {
  183. res.sendStatus(500)
  184. } else {
  185. res.sendStatus(200)
  186. }
  187. })
  188. },
  189. trashProject(req, res, next) {
  190. const projectId = req.params.project_id
  191. const userId = AuthenticationController.getLoggedInUserId(req)
  192. Project.update(
  193. { _id: projectId },
  194. { $addToSet: { trashed: userId } },
  195. error => {
  196. if (error) {
  197. return next(error)
  198. }
  199. res.sendStatus(200)
  200. }
  201. )
  202. },
  203. untrashProject(req, res, next) {
  204. const projectId = req.params.project_id
  205. const userId = AuthenticationController.getLoggedInUserId(req)
  206. Project.update(
  207. { _id: projectId },
  208. { $pull: { trashed: userId } },
  209. error => {
  210. if (error) {
  211. return next(error)
  212. }
  213. res.sendStatus(200)
  214. }
  215. )
  216. },
  217. cloneProject(req, res, next) {
  218. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  219. metrics.inc('cloned-project')
  220. const projectId = req.params.Project_id
  221. const { projectName } = req.body
  222. logger.log({ projectId, projectName }, 'cloning project')
  223. if (!AuthenticationController.isUserLoggedIn(req)) {
  224. return res.send({ redir: '/register' })
  225. }
  226. const currentUser = AuthenticationController.getSessionUser(req)
  227. ProjectDuplicator.duplicate(
  228. currentUser,
  229. projectId,
  230. projectName,
  231. (err, project) => {
  232. if (err != null) {
  233. logger.warn(
  234. { err, projectId, userId: currentUser._id },
  235. 'error cloning project'
  236. )
  237. return next(err)
  238. }
  239. res.send({
  240. name: project.name,
  241. project_id: project._id,
  242. owner_ref: project.owner_ref
  243. })
  244. }
  245. )
  246. },
  247. newProject(req, res, next) {
  248. const userId = AuthenticationController.getLoggedInUserId(req)
  249. const projectName =
  250. req.body.projectName != null ? req.body.projectName.trim() : undefined
  251. const { template } = req.body
  252. logger.log(
  253. { user: userId, projectType: template, name: projectName },
  254. 'creating project'
  255. )
  256. async.waterfall(
  257. [
  258. cb => {
  259. if (template === 'example') {
  260. ProjectCreationHandler.createExampleProject(userId, projectName, cb)
  261. } else {
  262. ProjectCreationHandler.createBasicProject(userId, projectName, cb)
  263. }
  264. }
  265. ],
  266. (err, project) => {
  267. if (err != null) {
  268. return next(err)
  269. }
  270. logger.log(
  271. { project, userId, name: projectName, templateType: template },
  272. 'created project'
  273. )
  274. res.send({ project_id: project._id })
  275. }
  276. )
  277. },
  278. renameProject(req, res, next) {
  279. const projectId = req.params.Project_id
  280. const newName = req.body.newProjectName
  281. EditorController.renameProject(projectId, newName, err => {
  282. if (err != null) {
  283. return next(err)
  284. }
  285. res.sendStatus(200)
  286. })
  287. },
  288. userProjectsJson(req, res, next) {
  289. const userId = AuthenticationController.getLoggedInUserId(req)
  290. ProjectGetter.findAllUsersProjects(
  291. userId,
  292. 'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
  293. (err, projects) => {
  294. if (err != null) {
  295. return next(err)
  296. }
  297. projects = ProjectController._buildProjectList(projects, userId)
  298. .filter(p => !ProjectHelper.isArchivedOrTrashed(p, userId))
  299. .filter(p => !p.isV1Project)
  300. .map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
  301. res.json({ projects })
  302. }
  303. )
  304. },
  305. projectEntitiesJson(req, res, next) {
  306. const projectId = req.params.Project_id
  307. ProjectGetter.getProject(projectId, (err, project) => {
  308. if (err != null) {
  309. return next(err)
  310. }
  311. ProjectEntityHandler.getAllEntitiesFromProject(
  312. project,
  313. (err, docs, files) => {
  314. if (err != null) {
  315. return next(err)
  316. }
  317. const entities = docs
  318. .concat(files)
  319. .sort((a, b) => a.path > b.path) // Sort by path ascending
  320. .map(e => ({
  321. path: e.path,
  322. type: e.doc != null ? 'doc' : 'file'
  323. }))
  324. res.json({ project_id: projectId, entities })
  325. }
  326. )
  327. })
  328. },
  329. projectListPage(req, res, next) {
  330. const timer = new metrics.Timer('project-list')
  331. const userId = AuthenticationController.getLoggedInUserId(req)
  332. const currentUser = AuthenticationController.getSessionUser(req)
  333. let noV1Connection = false
  334. async.parallel(
  335. {
  336. tags(cb) {
  337. TagsHandler.getAllTags(userId, cb)
  338. },
  339. notifications(cb) {
  340. NotificationsHandler.getUserNotifications(userId, cb)
  341. },
  342. projects(cb) {
  343. ProjectGetter.findAllUsersProjects(
  344. userId,
  345. 'name lastUpdated lastUpdatedBy publicAccesLevel archived owner_ref tokens',
  346. cb
  347. )
  348. },
  349. v1Projects(cb) {
  350. if (!Features.hasFeature('overleaf-integration')) {
  351. return cb(null, null)
  352. }
  353. Modules.hooks.fire('findAllV1Projects', userId, (error, projects) => {
  354. if (projects == null) {
  355. projects = []
  356. }
  357. if (error != null && error instanceof V1ConnectionError) {
  358. noV1Connection = true
  359. return cb(null, null)
  360. }
  361. cb(error, projects[0])
  362. })
  363. }, // hooks.fire returns an array of results, only need first
  364. hasSubscription(cb) {
  365. LimitationsManager.hasPaidSubscription(
  366. currentUser,
  367. (error, hasPaidSubscription) => {
  368. if (error != null && error instanceof V1ConnectionError) {
  369. noV1Connection = true
  370. return cb(null, true)
  371. }
  372. cb(error, hasPaidSubscription)
  373. }
  374. )
  375. },
  376. user(cb) {
  377. User.findById(
  378. userId,
  379. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  380. cb
  381. )
  382. },
  383. userAffiliations(cb) {
  384. if (!Features.hasFeature('affiliations')) {
  385. return cb(null, null)
  386. }
  387. getUserAffiliations(userId, (error, affiliations) => {
  388. if (error && error instanceof V1ConnectionError) {
  389. noV1Connection = true
  390. return cb(null, [])
  391. }
  392. cb(error, affiliations)
  393. })
  394. }
  395. },
  396. (err, results) => {
  397. if (err != null) {
  398. logger.warn({ err }, 'error getting data for project list page')
  399. return next(err)
  400. }
  401. if (noV1Connection) {
  402. results.v1Projects = results.v1Projects || { projects: [], tags: [] }
  403. results.v1Projects.noConnection = true
  404. }
  405. const { notifications, user, userAffiliations } = results
  406. const v1Tags =
  407. (results.v1Projects != null ? results.v1Projects.tags : undefined) ||
  408. []
  409. const tags = results.tags.concat(v1Tags)
  410. const notificationsInstitution = []
  411. for (const notification of notifications) {
  412. notification.html = req.i18n.translate(
  413. notification.templateKey,
  414. notification.messageOpts
  415. )
  416. }
  417. // Institution SSO Notifications
  418. if (Features.hasFeature('saml') || req.session.samlBeta) {
  419. const samlSession = req.session.saml
  420. // Notification: SSO Available
  421. // Could have multiple emails at the same institution, and if any are
  422. // linked to the institution then do not show notification for others
  423. const linkedInstitutionIds = []
  424. const linkedInstitutionEmails = []
  425. user.emails.forEach(email => {
  426. if (email.samlProviderId) {
  427. linkedInstitutionEmails.push(email.email)
  428. linkedInstitutionIds.push(email.samlProviderId)
  429. }
  430. })
  431. if (Array.isArray(userAffiliations)) {
  432. userAffiliations.forEach(affiliation => {
  433. if (
  434. affiliation.institution &&
  435. affiliation.institution.ssoEnabled &&
  436. linkedInstitutionEmails.indexOf(affiliation.email) === -1 &&
  437. linkedInstitutionIds.indexOf(
  438. affiliation.institution.id.toString()
  439. ) === -1
  440. ) {
  441. notificationsInstitution.push({
  442. email: affiliation.email,
  443. institutionId: affiliation.institution.id,
  444. institutionName: affiliation.institution.name,
  445. templateKey: 'notification_institution_sso_available'
  446. })
  447. }
  448. })
  449. }
  450. if (samlSession) {
  451. // Notification: After SSO Linked
  452. if (samlSession.linked) {
  453. notificationsInstitution.push({
  454. email: samlSession.institutionEmail,
  455. institutionName: samlSession.linked.universityName,
  456. templateKey: 'notification_institution_sso_linked'
  457. })
  458. }
  459. // Notification: After SSO Linked or Logging in
  460. // The requested email does not match primary email returned from
  461. // the institution
  462. if (samlSession.emailNonCanonical) {
  463. notificationsInstitution.push({
  464. institutionEmail: samlSession.emailNonCanonical,
  465. requestedEmail: samlSession.requestedEmail,
  466. templateKey: 'notification_institution_sso_non_canonical'
  467. })
  468. }
  469. // Notification: Tried to register, but account already existed
  470. if (samlSession.registerIntercept) {
  471. notificationsInstitution.push({
  472. email: samlSession.institutionEmail,
  473. templateKey: 'notification_institution_sso_already_registered'
  474. })
  475. }
  476. }
  477. delete req.session.saml
  478. }
  479. const portalTemplates = ProjectController._buildPortalTemplatesList(
  480. userAffiliations
  481. )
  482. const projects = ProjectController._buildProjectList(
  483. results.projects,
  484. userId,
  485. results.v1Projects != null ? results.v1Projects.projects : undefined
  486. )
  487. const warnings = ProjectController._buildWarningsList(
  488. results.v1Projects
  489. )
  490. // in v2 add notifications for matching university IPs
  491. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  492. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  493. }
  494. ProjectController._injectProjectUsers(projects, (error, projects) => {
  495. if (error != null) {
  496. return next(error)
  497. }
  498. const viewModel = {
  499. title: 'your_projects',
  500. priority_title: true,
  501. projects,
  502. tags,
  503. notifications: notifications || [],
  504. notificationsInstitution,
  505. portalTemplates,
  506. user,
  507. userAffiliations,
  508. hasSubscription: results.hasSubscription,
  509. isShowingV1Projects: results.v1Projects != null,
  510. warnings,
  511. zipFileSizeLimit: Settings.maxUploadSize
  512. }
  513. if (
  514. Settings.algolia &&
  515. Settings.algolia.app_id &&
  516. Settings.algolia.read_only_api_key
  517. ) {
  518. viewModel.showUserDetailsArea = true
  519. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  520. viewModel.algolia_app_id = Settings.algolia.app_id
  521. } else {
  522. viewModel.showUserDetailsArea = false
  523. }
  524. const paidUser =
  525. (user.features != null ? user.features.github : undefined) &&
  526. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  527. const freeUserProportion = 0.1
  528. const sampleFreeUser =
  529. parseInt(user._id.toString().slice(-2), 16) <
  530. freeUserProportion * 255
  531. const showFrontWidget = paidUser || sampleFreeUser
  532. logger.log(
  533. { paidUser, sampleFreeUser, showFrontWidget },
  534. 'deciding whether to show front widget'
  535. )
  536. if (showFrontWidget) {
  537. viewModel.frontChatWidgetRoomId =
  538. Settings.overleaf != null
  539. ? Settings.overleaf.front_chat_widget_room_id
  540. : undefined
  541. }
  542. res.render('project/list', viewModel)
  543. timer.done()
  544. })
  545. }
  546. )
  547. },
  548. loadEditor(req, res, next) {
  549. let anonymous, userId
  550. const timer = new metrics.Timer('load-editor')
  551. if (!Settings.editorIsOpen) {
  552. return res.render('general/closed', { title: 'updating_site' })
  553. }
  554. if (AuthenticationController.isUserLoggedIn(req)) {
  555. userId = AuthenticationController.getLoggedInUserId(req)
  556. anonymous = false
  557. } else {
  558. anonymous = true
  559. userId = null
  560. }
  561. const projectId = req.params.Project_id
  562. logger.log({ projectId, anonymous, userId }, 'loading editor')
  563. // record failures to load the custom websocket
  564. if ((req.query != null ? req.query.ws : undefined) === 'fallback') {
  565. metrics.inc('load-editor-ws-fallback')
  566. }
  567. async.auto(
  568. {
  569. project(cb) {
  570. ProjectGetter.getProject(
  571. projectId,
  572. {
  573. name: 1,
  574. lastUpdated: 1,
  575. track_changes: 1,
  576. owner_ref: 1,
  577. brandVariationId: 1,
  578. overleaf: 1,
  579. tokens: 1
  580. },
  581. (err, project) => {
  582. if (err != null) {
  583. return cb(err)
  584. }
  585. if (
  586. (project.overleaf != null ? project.overleaf.id : undefined) ==
  587. null ||
  588. (project.tokens != null
  589. ? project.tokens.readAndWrite
  590. : undefined) == null ||
  591. Settings.projectImportingCheckMaxCreateDelta == null
  592. ) {
  593. return cb(null, project)
  594. }
  595. const createDelta =
  596. (new Date().getTime() -
  597. new Date(project._id.getTimestamp()).getTime()) /
  598. 1000
  599. if (
  600. !(createDelta < Settings.projectImportingCheckMaxCreateDelta)
  601. ) {
  602. return cb(null, project)
  603. }
  604. V1Handler.getDocExported(
  605. project.tokens.readAndWrite,
  606. (err, docExported) => {
  607. if (err != null) {
  608. return next(err)
  609. }
  610. project.exporting = docExported.exporting
  611. cb(null, project)
  612. }
  613. )
  614. }
  615. )
  616. },
  617. user(cb) {
  618. if (userId == null) {
  619. cb(null, defaultSettingsForAnonymousUser(userId))
  620. } else {
  621. User.findById(userId, (err, user) => {
  622. logger.log({ projectId, userId }, 'got user')
  623. cb(err, user)
  624. })
  625. }
  626. },
  627. subscription(cb) {
  628. if (userId == null) {
  629. return cb()
  630. }
  631. SubscriptionLocator.getUsersSubscription(userId, cb)
  632. },
  633. activate(cb) {
  634. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  635. },
  636. markAsOpened(cb) {
  637. // don't need to wait for this to complete
  638. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  639. cb()
  640. },
  641. isTokenMember(cb) {
  642. if (userId == null) {
  643. return cb()
  644. }
  645. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  646. },
  647. brandVariation: [
  648. 'project',
  649. (cb, results) => {
  650. if (
  651. (results.project != null
  652. ? results.project.brandVariationId
  653. : undefined) == null
  654. ) {
  655. return cb()
  656. }
  657. BrandVariationsHandler.getBrandVariationById(
  658. results.project.brandVariationId,
  659. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  660. )
  661. }
  662. ]
  663. },
  664. (err, results) => {
  665. if (err != null) {
  666. logger.warn({ err }, 'error getting details for project page')
  667. return next(err)
  668. }
  669. const { project } = results
  670. const { user } = results
  671. const { subscription } = results
  672. const { brandVariation } = results
  673. const daysSinceLastUpdated =
  674. (new Date() - project.lastUpdated) / 86400000
  675. logger.log(
  676. { projectId, daysSinceLastUpdated },
  677. 'got db results for loading editor'
  678. )
  679. const token = TokenAccessHandler.getRequestToken(req, projectId)
  680. const { isTokenMember } = results
  681. AuthorizationManager.getPrivilegeLevelForProject(
  682. userId,
  683. projectId,
  684. token,
  685. (error, privilegeLevel) => {
  686. let allowedFreeTrial
  687. if (error != null) {
  688. return next(error)
  689. }
  690. if (
  691. privilegeLevel == null ||
  692. privilegeLevel === PrivilegeLevels.NONE
  693. ) {
  694. return res.sendStatus(401)
  695. }
  696. if (project.exporting) {
  697. res.render('project/importing', { bodyClasses: ['editor'] })
  698. return
  699. }
  700. if (
  701. subscription != null &&
  702. subscription.freeTrial != null &&
  703. subscription.freeTrial.expiresAt != null
  704. ) {
  705. allowedFreeTrial = !!subscription.freeTrial.allowed || true
  706. }
  707. logger.log({ projectId }, 'rendering editor page')
  708. res.render('project/editor', {
  709. title: project.name,
  710. priority_title: true,
  711. bodyClasses: ['editor'],
  712. project_id: project._id,
  713. user: {
  714. id: userId,
  715. email: user.email,
  716. first_name: user.first_name,
  717. last_name: user.last_name,
  718. referal_id: user.referal_id,
  719. signUpDate: user.signUpDate,
  720. subscription: {
  721. freeTrial: { allowed: allowedFreeTrial }
  722. },
  723. featureSwitches: user.featureSwitches,
  724. features: user.features,
  725. refProviders: user.refProviders,
  726. betaProgram: user.betaProgram,
  727. isAdmin: user.isAdmin
  728. },
  729. userSettings: {
  730. mode: user.ace.mode,
  731. editorTheme: user.ace.theme,
  732. fontSize: user.ace.fontSize,
  733. autoComplete: user.ace.autoComplete,
  734. autoPairDelimiters: user.ace.autoPairDelimiters,
  735. pdfViewer: user.ace.pdfViewer,
  736. syntaxValidation: user.ace.syntaxValidation,
  737. fontFamily: user.ace.fontFamily,
  738. lineHeight: user.ace.lineHeight,
  739. overallTheme: user.ace.overallTheme
  740. },
  741. trackChangesState: project.track_changes,
  742. privilegeLevel,
  743. chatUrl: Settings.apis.chat.url,
  744. anonymous,
  745. anonymousAccessToken: req._anonymousAccessToken,
  746. isTokenMember,
  747. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  748. userId,
  749. privilegeLevel,
  750. isTokenMember
  751. ),
  752. languages: Settings.languages,
  753. editorThemes: THEME_LIST,
  754. maxDocLength: Settings.max_doc_length,
  755. useV2History:
  756. project.overleaf &&
  757. project.overleaf.history &&
  758. Boolean(project.overleaf.history.display),
  759. showTestControls:
  760. (req.query && req.query.tc === 'true') || user.isAdmin,
  761. brandVariation,
  762. allowedImageNames: Settings.allowedImageNames || [],
  763. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl
  764. })
  765. timer.done()
  766. }
  767. )
  768. }
  769. )
  770. },
  771. _buildProjectList(allProjects, userId, v1Projects) {
  772. let project
  773. if (v1Projects == null) {
  774. v1Projects = []
  775. }
  776. const {
  777. owned,
  778. readAndWrite,
  779. readOnly,
  780. tokenReadAndWrite,
  781. tokenReadOnly
  782. } = allProjects
  783. const projects = []
  784. for (project of owned) {
  785. projects.push(
  786. ProjectController._buildProjectViewModel(
  787. project,
  788. 'owner',
  789. Sources.OWNER,
  790. userId
  791. )
  792. )
  793. }
  794. // Invite-access
  795. for (project of readAndWrite) {
  796. projects.push(
  797. ProjectController._buildProjectViewModel(
  798. project,
  799. 'readWrite',
  800. Sources.INVITE,
  801. userId
  802. )
  803. )
  804. }
  805. for (project of readOnly) {
  806. projects.push(
  807. ProjectController._buildProjectViewModel(
  808. project,
  809. 'readOnly',
  810. Sources.INVITE,
  811. userId
  812. )
  813. )
  814. }
  815. for (project of v1Projects) {
  816. projects.push(ProjectController._buildV1ProjectViewModel(project))
  817. }
  818. // Token-access
  819. // Only add these projects if they're not already present, this gives us cascading access
  820. // from 'owner' => 'token-read-only'
  821. for (project of tokenReadAndWrite) {
  822. if (
  823. projects.filter(p => p.id.toString() === project._id.toString())
  824. .length === 0
  825. ) {
  826. projects.push(
  827. ProjectController._buildProjectViewModel(
  828. project,
  829. 'readAndWrite',
  830. Sources.TOKEN,
  831. userId
  832. )
  833. )
  834. }
  835. }
  836. for (project of tokenReadOnly) {
  837. if (
  838. projects.filter(p => p.id.toString() === project._id.toString())
  839. .length === 0
  840. ) {
  841. projects.push(
  842. ProjectController._buildProjectViewModel(
  843. project,
  844. 'readOnly',
  845. Sources.TOKEN,
  846. userId
  847. )
  848. )
  849. }
  850. }
  851. return projects
  852. },
  853. _buildProjectViewModel(project, accessLevel, source, userId) {
  854. TokenAccessHandler.protectTokens(project, accessLevel)
  855. const model = {
  856. id: project._id,
  857. name: project.name,
  858. lastUpdated: project.lastUpdated,
  859. lastUpdatedBy: project.lastUpdatedBy,
  860. publicAccessLevel: project.publicAccesLevel,
  861. accessLevel,
  862. source,
  863. archived: ProjectHelper.isArchived(project, userId),
  864. owner_ref: project.owner_ref,
  865. tokens: project.tokens,
  866. isV1Project: false
  867. }
  868. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  869. model.owner_ref = null
  870. model.lastUpdatedBy = null
  871. }
  872. return model
  873. },
  874. _buildV1ProjectViewModel(project) {
  875. const projectViewModel = {
  876. id: project.id,
  877. name: project.title,
  878. lastUpdated: new Date(project.updated_at * 1000), // Convert from epoch
  879. archived: project.removed || project.archived,
  880. isV1Project: true
  881. }
  882. if (
  883. (project.owner != null && project.owner.user_is_owner) ||
  884. (project.creator != null && project.creator.user_is_creator)
  885. ) {
  886. projectViewModel.accessLevel = 'owner'
  887. } else {
  888. projectViewModel.accessLevel = 'readOnly'
  889. }
  890. if (project.owner != null) {
  891. projectViewModel.owner = {
  892. first_name: project.owner.name
  893. }
  894. } else if (project.creator != null) {
  895. projectViewModel.owner = {
  896. first_name: project.creator.name
  897. }
  898. }
  899. return projectViewModel
  900. },
  901. _injectProjectUsers(projects, callback) {
  902. const users = {}
  903. for (const project of projects) {
  904. if (project.owner_ref != null) {
  905. users[project.owner_ref.toString()] = true
  906. }
  907. if (project.lastUpdatedBy != null) {
  908. users[project.lastUpdatedBy.toString()] = true
  909. }
  910. }
  911. const userIds = Object.keys(users)
  912. async.eachSeries(
  913. userIds,
  914. (userId, cb) => {
  915. UserGetter.getUser(
  916. userId,
  917. { first_name: 1, last_name: 1, email: 1 },
  918. (error, user) => {
  919. if (error != null) {
  920. return cb(error)
  921. }
  922. users[userId] = user
  923. cb()
  924. }
  925. )
  926. },
  927. error => {
  928. if (error != null) {
  929. return callback(error)
  930. }
  931. for (const project of projects) {
  932. if (project.owner_ref != null) {
  933. project.owner = users[project.owner_ref.toString()]
  934. }
  935. if (project.lastUpdatedBy != null) {
  936. project.lastUpdatedBy =
  937. users[project.lastUpdatedBy.toString()] || null
  938. }
  939. }
  940. callback(null, projects)
  941. }
  942. )
  943. },
  944. _buildWarningsList(v1ProjectData) {
  945. if (v1ProjectData == null) {
  946. v1ProjectData = {}
  947. }
  948. const warnings = []
  949. if (v1ProjectData.noConnection) {
  950. warnings.push(
  951. 'Error accessing Overleaf V1. Some of your projects or features may be missing.'
  952. )
  953. }
  954. if (v1ProjectData.hasHiddenV1Projects) {
  955. warnings.push(
  956. "Looks like you've got a lot of V1 projects! Some of them may be hidden on V2. To view them all, use the V1 dashboard."
  957. )
  958. }
  959. return warnings
  960. },
  961. _buildPortalTemplatesList(affiliations) {
  962. if (affiliations == null) {
  963. affiliations = []
  964. }
  965. const portalTemplates = []
  966. for (let aff of affiliations) {
  967. if (
  968. aff.portal &&
  969. aff.portal.slug &&
  970. aff.portal.templates_count &&
  971. aff.portal.templates_count > 0
  972. ) {
  973. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  974. portalTemplates.push({
  975. name: aff.institution.name,
  976. url: Settings.siteUrl + portalPath + aff.portal.slug
  977. })
  978. }
  979. }
  980. return portalTemplates
  981. }
  982. }
  983. var defaultSettingsForAnonymousUser = userId => ({
  984. id: userId,
  985. ace: {
  986. mode: 'none',
  987. theme: 'textmate',
  988. fontSize: '12',
  989. autoComplete: true,
  990. spellCheckLanguage: '',
  991. pdfViewer: '',
  992. syntaxValidation: true
  993. },
  994. subscription: {
  995. freeTrial: {
  996. allowed: true
  997. }
  998. },
  999. featureSwitches: {
  1000. github: false
  1001. }
  1002. })
  1003. var THEME_LIST = []
  1004. function generateThemeList() {
  1005. const files = fs.readdirSync(
  1006. Path.join(
  1007. __dirname,
  1008. '/../../../../public/src/vendor/',
  1009. PackageVersions.lib('ace')
  1010. )
  1011. )
  1012. const result = []
  1013. for (let file of files) {
  1014. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  1015. const cleanName = file.slice(0, -3).slice(6)
  1016. result.push(THEME_LIST.push(cleanName))
  1017. } else {
  1018. result.push(undefined)
  1019. }
  1020. }
  1021. }
  1022. generateThemeList()
  1023. module.exports = ProjectController