ProjectController.js 34 KB

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