ProjectController.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 { ObjectId } = require('../../infrastructure/mongojs')
  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('metrics-sharelatex')
  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('settings-sharelatex')
  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 AuthenticationController = require('../Authentication/AuthenticationController')
  25. const PackageVersions = require('../../infrastructure/PackageVersions')
  26. const Sources = require('../Authorization/Sources')
  27. const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
  28. const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
  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 UserController = require('../User/UserController')
  38. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  39. if (!affiliation.institution) return false
  40. // institution.confirmed is for the domain being confirmed, not the email
  41. // Do not show SSO UI for unconfirmed domains
  42. if (!affiliation.institution.confirmed) return false
  43. // Could have multiple emails at the same institution, and if any are
  44. // linked to the institution then do not show notification for others
  45. if (
  46. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  47. ) {
  48. if (affiliation.institution.ssoEnabled) return true
  49. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  50. return false
  51. }
  52. return false
  53. }
  54. const ProjectController = {
  55. _isInPercentageRollout(rolloutName, objectId, percentage) {
  56. if (Settings.bypassPercentageRollouts === true) {
  57. return true
  58. }
  59. const data = `${rolloutName}:${objectId.toString()}`
  60. const md5hash = crypto
  61. .createHash('md5')
  62. .update(data)
  63. .digest('hex')
  64. const counter = parseInt(md5hash.slice(26, 32), 16)
  65. return counter % 100 < percentage
  66. },
  67. updateProjectSettings(req, res, next) {
  68. const projectId = req.params.Project_id
  69. const jobs = []
  70. if (req.body.compiler != null) {
  71. jobs.push(callback =>
  72. EditorController.setCompiler(projectId, req.body.compiler, callback)
  73. )
  74. }
  75. if (req.body.imageName != null) {
  76. jobs.push(callback =>
  77. EditorController.setImageName(projectId, req.body.imageName, callback)
  78. )
  79. }
  80. if (req.body.name != null) {
  81. jobs.push(callback =>
  82. EditorController.renameProject(projectId, req.body.name, callback)
  83. )
  84. }
  85. if (req.body.spellCheckLanguage != null) {
  86. jobs.push(callback =>
  87. EditorController.setSpellCheckLanguage(
  88. projectId,
  89. req.body.spellCheckLanguage,
  90. callback
  91. )
  92. )
  93. }
  94. if (req.body.rootDocId != null) {
  95. jobs.push(callback =>
  96. EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
  97. )
  98. }
  99. async.series(jobs, error => {
  100. if (error != null) {
  101. return next(error)
  102. }
  103. res.sendStatus(204)
  104. })
  105. },
  106. updateProjectAdminSettings(req, res, next) {
  107. const projectId = req.params.Project_id
  108. const jobs = []
  109. if (req.body.publicAccessLevel != null) {
  110. jobs.push(callback =>
  111. EditorController.setPublicAccessLevel(
  112. projectId,
  113. req.body.publicAccessLevel,
  114. callback
  115. )
  116. )
  117. }
  118. async.series(jobs, error => {
  119. if (error != null) {
  120. return next(error)
  121. }
  122. res.sendStatus(204)
  123. })
  124. },
  125. deleteProject(req, res) {
  126. const projectId = req.params.Project_id
  127. const user = AuthenticationController.getSessionUser(req)
  128. const cb = err => {
  129. if (err != null) {
  130. res.sendStatus(500)
  131. } else {
  132. res.sendStatus(200)
  133. }
  134. }
  135. ProjectDeleter.deleteProject(
  136. projectId,
  137. { deleterUser: user, ipAddress: req.ip },
  138. cb
  139. )
  140. },
  141. archiveProject(req, res, next) {
  142. const projectId = req.params.Project_id
  143. const userId = AuthenticationController.getLoggedInUserId(req)
  144. ProjectDeleter.archiveProject(projectId, userId, function(err) {
  145. if (err != null) {
  146. return next(err)
  147. } else {
  148. return res.sendStatus(200)
  149. }
  150. })
  151. },
  152. unarchiveProject(req, res, next) {
  153. const projectId = req.params.Project_id
  154. const userId = AuthenticationController.getLoggedInUserId(req)
  155. ProjectDeleter.unarchiveProject(projectId, userId, function(err) {
  156. if (err != null) {
  157. return next(err)
  158. } else {
  159. return res.sendStatus(200)
  160. }
  161. })
  162. },
  163. trashProject(req, res, next) {
  164. const projectId = req.params.project_id
  165. const userId = AuthenticationController.getLoggedInUserId(req)
  166. ProjectDeleter.trashProject(projectId, userId, function(err) {
  167. if (err != null) {
  168. return next(err)
  169. } else {
  170. return res.sendStatus(200)
  171. }
  172. })
  173. },
  174. untrashProject(req, res, next) {
  175. const projectId = req.params.project_id
  176. const userId = AuthenticationController.getLoggedInUserId(req)
  177. ProjectDeleter.untrashProject(projectId, userId, function(err) {
  178. if (err != null) {
  179. return next(err)
  180. } else {
  181. return res.sendStatus(200)
  182. }
  183. })
  184. },
  185. expireDeletedProjectsAfterDuration(req, res) {
  186. ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
  187. if (err != null) {
  188. res.sendStatus(500)
  189. } else {
  190. res.sendStatus(200)
  191. }
  192. })
  193. },
  194. expireDeletedProject(req, res, next) {
  195. const { projectId } = req.params
  196. ProjectDeleter.expireDeletedProject(projectId, err => {
  197. if (err != null) {
  198. next(err)
  199. } else {
  200. res.sendStatus(200)
  201. }
  202. })
  203. },
  204. restoreProject(req, res) {
  205. const projectId = req.params.Project_id
  206. ProjectDeleter.restoreProject(projectId, err => {
  207. if (err != null) {
  208. res.sendStatus(500)
  209. } else {
  210. res.sendStatus(200)
  211. }
  212. })
  213. },
  214. cloneProject(req, res, next) {
  215. res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
  216. metrics.inc('cloned-project')
  217. const projectId = req.params.Project_id
  218. const { projectName } = req.body
  219. logger.log({ projectId, projectName }, 'cloning project')
  220. if (!AuthenticationController.isUserLoggedIn(req)) {
  221. return res.send({ redir: '/register' })
  222. }
  223. const currentUser = AuthenticationController.getSessionUser(req)
  224. const { first_name: firstName, last_name: lastName, email } = currentUser
  225. ProjectDuplicator.duplicate(
  226. currentUser,
  227. projectId,
  228. projectName,
  229. (err, project) => {
  230. if (err != null) {
  231. logger.warn(
  232. { err, projectId, userId: currentUser._id },
  233. 'error cloning project'
  234. )
  235. return next(err)
  236. }
  237. res.send({
  238. name: project.name,
  239. project_id: project._id,
  240. owner_ref: project.owner_ref,
  241. owner: {
  242. first_name: firstName,
  243. last_name: lastName,
  244. email,
  245. _id: currentUser._id
  246. }
  247. })
  248. }
  249. )
  250. },
  251. newProject(req, res, next) {
  252. const userId = AuthenticationController.getLoggedInUserId(req)
  253. const projectName =
  254. req.body.projectName != null ? req.body.projectName.trim() : undefined
  255. const { template } = req.body
  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. 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. // _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
  294. projects = ProjectController._buildProjectList(projects, userId)
  295. .filter(p => !(p.archived || p.trashed))
  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. let institutionLinkingError
  331. async.parallel(
  332. {
  333. tags(cb) {
  334. TagsHandler.getAllTags(userId, cb)
  335. },
  336. notifications(cb) {
  337. NotificationsHandler.getUserNotifications(userId, cb)
  338. },
  339. projects(cb) {
  340. ProjectGetter.findAllUsersProjects(
  341. userId,
  342. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
  343. cb
  344. )
  345. },
  346. hasSubscription(cb) {
  347. LimitationsManager.hasPaidSubscription(
  348. currentUser,
  349. (error, hasPaidSubscription) => {
  350. if (error != null && error instanceof V1ConnectionError) {
  351. noV1Connection = true
  352. return cb(null, true)
  353. }
  354. cb(error, hasPaidSubscription)
  355. }
  356. )
  357. },
  358. user(cb) {
  359. User.findById(
  360. userId,
  361. 'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
  362. cb
  363. )
  364. },
  365. userAffiliations(cb) {
  366. if (!Features.hasFeature('affiliations')) {
  367. return cb(null, [])
  368. }
  369. getUserAffiliations(userId, (error, affiliations) => {
  370. if (error && error instanceof V1ConnectionError) {
  371. noV1Connection = true
  372. return cb(null, [])
  373. }
  374. cb(error, affiliations)
  375. })
  376. }
  377. },
  378. (err, results) => {
  379. if (err != null) {
  380. logger.warn({ err }, 'error getting data for project list page')
  381. return next(err)
  382. }
  383. const { notifications, user, userAffiliations } = results
  384. // Handle case of deleted user
  385. if (user == null) {
  386. UserController.logout(req, res, next)
  387. return
  388. }
  389. const tags = results.tags
  390. const notificationsInstitution = []
  391. for (const notification of notifications) {
  392. notification.html = req.i18n.translate(
  393. notification.templateKey,
  394. notification.messageOpts
  395. )
  396. }
  397. // Institution SSO Notifications
  398. if (Features.hasFeature('saml')) {
  399. const samlSession = req.session.saml
  400. // Notification: SSO Available
  401. const linkedInstitutionIds = []
  402. user.emails.forEach(email => {
  403. if (email.samlProviderId) {
  404. linkedInstitutionIds.push(email.samlProviderId)
  405. }
  406. })
  407. if (Array.isArray(userAffiliations)) {
  408. userAffiliations.forEach(affiliation => {
  409. if (
  410. _ssoAvailable(affiliation, req.session, linkedInstitutionIds)
  411. ) {
  412. notificationsInstitution.push({
  413. email: affiliation.email,
  414. institutionId: affiliation.institution.id,
  415. institutionName: affiliation.institution.name,
  416. templateKey: 'notification_institution_sso_available'
  417. })
  418. }
  419. })
  420. }
  421. if (samlSession) {
  422. // Notification: After SSO Linked
  423. if (samlSession.linked) {
  424. notificationsInstitution.push({
  425. email: samlSession.institutionEmail,
  426. institutionName: samlSession.linked.universityName,
  427. templateKey: 'notification_institution_sso_linked'
  428. })
  429. }
  430. // Notification: After SSO Linked or Logging in
  431. // The requested email does not match primary email returned from
  432. // the institution
  433. if (
  434. samlSession.requestedEmail &&
  435. samlSession.emailNonCanonical &&
  436. !samlSession.linkedToAnother
  437. ) {
  438. notificationsInstitution.push({
  439. institutionEmail: samlSession.emailNonCanonical,
  440. requestedEmail: samlSession.requestedEmail,
  441. templateKey: 'notification_institution_sso_non_canonical'
  442. })
  443. }
  444. // Notification: Tried to register, but account already existed
  445. // registerIntercept is set before the institution callback.
  446. // institutionEmail is set after institution callback.
  447. // Check for both in case SSO flow was abandoned
  448. if (
  449. samlSession.registerIntercept &&
  450. samlSession.institutionEmail &&
  451. !samlSession.linkedToAnother
  452. ) {
  453. notificationsInstitution.push({
  454. email: samlSession.institutionEmail,
  455. templateKey: 'notification_institution_sso_already_registered'
  456. })
  457. }
  458. // Notification: Already linked to another account
  459. if (samlSession.linkedToAnother) {
  460. notificationsInstitution.push({
  461. templateKey: 'notification_institution_sso_linked_by_another'
  462. })
  463. }
  464. // Notification: When there is a session error
  465. if (samlSession.error) {
  466. institutionLinkingError = samlSession.error
  467. notificationsInstitution.push({
  468. message: samlSession.error.message,
  469. templateKey: 'notification_institution_sso_error',
  470. tryAgain: samlSession.error.tryAgain
  471. })
  472. }
  473. }
  474. delete req.session.saml
  475. }
  476. const portalTemplates = ProjectController._buildPortalTemplatesList(
  477. userAffiliations
  478. )
  479. const projects = ProjectController._buildProjectList(
  480. results.projects,
  481. userId
  482. )
  483. const warnings = ProjectController._buildWarningsList(noV1Connection)
  484. // in v2 add notifications for matching university IPs
  485. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  486. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  487. }
  488. ProjectController._injectProjectUsers(projects, (error, projects) => {
  489. if (error != null) {
  490. return next(error)
  491. }
  492. const viewModel = {
  493. title: 'your_projects',
  494. priority_title: true,
  495. projects,
  496. tags,
  497. notifications: notifications || [],
  498. notificationsInstitution,
  499. portalTemplates,
  500. user,
  501. userAffiliations,
  502. hasSubscription: results.hasSubscription,
  503. institutionLinkingError,
  504. warnings,
  505. zipFileSizeLimit: Settings.maxUploadSize
  506. }
  507. if (
  508. Settings.algolia &&
  509. Settings.algolia.app_id &&
  510. Settings.algolia.read_only_api_key
  511. ) {
  512. viewModel.showUserDetailsArea = true
  513. viewModel.algolia_api_key = Settings.algolia.read_only_api_key
  514. viewModel.algolia_app_id = Settings.algolia.app_id
  515. } else {
  516. viewModel.showUserDetailsArea = false
  517. }
  518. const paidUser =
  519. (user.features != null ? user.features.github : undefined) &&
  520. (user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
  521. const freeUserProportion = 0.1
  522. const sampleFreeUser =
  523. parseInt(user._id.toString().slice(-2), 16) <
  524. freeUserProportion * 255
  525. const showFrontWidget = paidUser || sampleFreeUser
  526. if (showFrontWidget) {
  527. viewModel.frontChatWidgetRoomId =
  528. Settings.overleaf != null
  529. ? Settings.overleaf.front_chat_widget_room_id
  530. : undefined
  531. }
  532. res.render('project/list', viewModel)
  533. timer.done()
  534. })
  535. }
  536. )
  537. },
  538. loadEditor(req, res, next) {
  539. const timer = new metrics.Timer('load-editor')
  540. if (!Settings.editorIsOpen) {
  541. return res.render('general/closed', { title: 'updating_site' })
  542. }
  543. let anonymous, userId, sessionUser
  544. if (AuthenticationController.isUserLoggedIn(req)) {
  545. sessionUser = AuthenticationController.getSessionUser(req)
  546. userId = AuthenticationController.getLoggedInUserId(req)
  547. anonymous = false
  548. } else {
  549. sessionUser = null
  550. anonymous = true
  551. userId = null
  552. }
  553. const projectId = req.params.Project_id
  554. async.auto(
  555. {
  556. project(cb) {
  557. ProjectGetter.getProject(
  558. projectId,
  559. {
  560. name: 1,
  561. lastUpdated: 1,
  562. track_changes: 1,
  563. owner_ref: 1,
  564. brandVariationId: 1,
  565. overleaf: 1,
  566. tokens: 1
  567. },
  568. (err, project) => {
  569. if (err != null) {
  570. return cb(err)
  571. }
  572. cb(null, project)
  573. }
  574. )
  575. },
  576. user(cb) {
  577. if (userId == null) {
  578. cb(null, defaultSettingsForAnonymousUser(userId))
  579. } else {
  580. User.findById(userId, (err, user) => {
  581. // Handle case of deleted user
  582. if (user == null) {
  583. UserController.logout(req, res, next)
  584. return
  585. }
  586. logger.log({ projectId, userId }, 'got user')
  587. cb(err, user)
  588. })
  589. }
  590. },
  591. subscription(cb) {
  592. if (userId == null) {
  593. return cb()
  594. }
  595. SubscriptionLocator.getUsersSubscription(userId, cb)
  596. },
  597. activate(cb) {
  598. InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
  599. },
  600. markAsOpened(cb) {
  601. // don't need to wait for this to complete
  602. ProjectUpdateHandler.markAsOpened(projectId, () => {})
  603. cb()
  604. },
  605. isTokenMember(cb) {
  606. if (userId == null) {
  607. return cb()
  608. }
  609. CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
  610. },
  611. brandVariation: [
  612. 'project',
  613. (cb, results) => {
  614. if (
  615. (results.project != null
  616. ? results.project.brandVariationId
  617. : undefined) == null
  618. ) {
  619. return cb()
  620. }
  621. BrandVariationsHandler.getBrandVariationById(
  622. results.project.brandVariationId,
  623. (error, brandVariationDetails) => cb(error, brandVariationDetails)
  624. )
  625. }
  626. ],
  627. flushToTpds: cb => {
  628. TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
  629. }
  630. },
  631. (err, results) => {
  632. if (err != null) {
  633. logger.warn({ err }, 'error getting details for project page')
  634. return next(err)
  635. }
  636. const { project } = results
  637. const { user } = results
  638. const { subscription } = results
  639. const { brandVariation } = results
  640. const anonRequestToken = TokenAccessHandler.getRequestToken(
  641. req,
  642. projectId
  643. )
  644. const { isTokenMember } = results
  645. const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
  646. sessionUser
  647. )
  648. AuthorizationManager.getPrivilegeLevelForProject(
  649. userId,
  650. projectId,
  651. anonRequestToken,
  652. (error, privilegeLevel) => {
  653. let allowedFreeTrial
  654. if (error != null) {
  655. return next(error)
  656. }
  657. if (
  658. privilegeLevel == null ||
  659. privilegeLevel === PrivilegeLevels.NONE
  660. ) {
  661. return res.sendStatus(401)
  662. }
  663. if (
  664. subscription != null &&
  665. subscription.freeTrial != null &&
  666. subscription.freeTrial.expiresAt != null
  667. ) {
  668. allowedFreeTrial = !!subscription.freeTrial.allowed || true
  669. }
  670. let wsUrl = Settings.wsUrl
  671. let metricName = 'load-editor-ws'
  672. if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
  673. wsUrl = Settings.wsUrlBeta
  674. metricName += '-beta'
  675. } else if (
  676. Settings.wsUrlV2 &&
  677. Settings.wsUrlV2Percentage > 0 &&
  678. (ObjectId(projectId).getTimestamp() / 1000) %
  679. 100 <
  680. Settings.wsUrlV2Percentage
  681. ) {
  682. wsUrl = Settings.wsUrlV2
  683. metricName += '-v2'
  684. }
  685. if (req.query && req.query.ws === 'fallback') {
  686. // `?ws=fallback` will connect to the bare origin, and ignore
  687. // the custom wsUrl. Hence it must load the client side
  688. // javascript from there too.
  689. // Not resetting it here would possibly load a socket.io v2
  690. // client and connect to a v0 endpoint.
  691. wsUrl = undefined
  692. metricName += '-fallback'
  693. }
  694. metrics.inc(metricName)
  695. res.render('project/editor', {
  696. title: project.name,
  697. priority_title: true,
  698. bodyClasses: ['editor'],
  699. project_id: project._id,
  700. user: {
  701. id: userId,
  702. email: user.email,
  703. first_name: user.first_name,
  704. last_name: user.last_name,
  705. referal_id: user.referal_id,
  706. signUpDate: user.signUpDate,
  707. subscription: {
  708. freeTrial: { allowed: allowedFreeTrial }
  709. },
  710. featureSwitches: user.featureSwitches,
  711. features: user.features,
  712. refProviders: user.refProviders,
  713. alphaProgram: user.alphaProgram,
  714. betaProgram: user.betaProgram,
  715. isAdmin: user.isAdmin
  716. },
  717. userSettings: {
  718. mode: user.ace.mode,
  719. editorTheme: user.ace.theme,
  720. fontSize: user.ace.fontSize,
  721. autoComplete: user.ace.autoComplete,
  722. autoPairDelimiters: user.ace.autoPairDelimiters,
  723. pdfViewer: user.ace.pdfViewer,
  724. syntaxValidation: user.ace.syntaxValidation,
  725. fontFamily: user.ace.fontFamily || 'lucida',
  726. lineHeight: user.ace.lineHeight || 'normal',
  727. overallTheme: user.ace.overallTheme
  728. },
  729. trackChangesState: project.track_changes,
  730. privilegeLevel,
  731. chatUrl: Settings.apis.chat.url,
  732. anonymous,
  733. anonymousAccessToken: anonymous ? anonRequestToken : null,
  734. isTokenMember,
  735. isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
  736. userId,
  737. privilegeLevel,
  738. isTokenMember
  739. ),
  740. languages: Settings.languages,
  741. editorThemes: THEME_LIST,
  742. maxDocLength: Settings.max_doc_length,
  743. useV2History:
  744. project.overleaf &&
  745. project.overleaf.history &&
  746. Boolean(project.overleaf.history.display),
  747. brandVariation,
  748. allowedImageNames,
  749. gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
  750. wsUrl,
  751. showSupport: Features.hasFeature('support')
  752. })
  753. timer.done()
  754. }
  755. )
  756. }
  757. )
  758. },
  759. _buildProjectList(allProjects, userId) {
  760. let project
  761. const {
  762. owned,
  763. readAndWrite,
  764. readOnly,
  765. tokenReadAndWrite,
  766. tokenReadOnly
  767. } = allProjects
  768. const projects = []
  769. for (project of owned) {
  770. projects.push(
  771. ProjectController._buildProjectViewModel(
  772. project,
  773. 'owner',
  774. Sources.OWNER,
  775. userId
  776. )
  777. )
  778. }
  779. // Invite-access
  780. for (project of readAndWrite) {
  781. projects.push(
  782. ProjectController._buildProjectViewModel(
  783. project,
  784. 'readWrite',
  785. Sources.INVITE,
  786. userId
  787. )
  788. )
  789. }
  790. for (project of readOnly) {
  791. projects.push(
  792. ProjectController._buildProjectViewModel(
  793. project,
  794. 'readOnly',
  795. Sources.INVITE,
  796. userId
  797. )
  798. )
  799. }
  800. // Token-access
  801. // Only add these projects if they're not already present, this gives us cascading access
  802. // from 'owner' => 'token-read-only'
  803. for (project of tokenReadAndWrite) {
  804. if (
  805. projects.filter(p => p.id.toString() === project._id.toString())
  806. .length === 0
  807. ) {
  808. projects.push(
  809. ProjectController._buildProjectViewModel(
  810. project,
  811. 'readAndWrite',
  812. Sources.TOKEN,
  813. userId
  814. )
  815. )
  816. }
  817. }
  818. for (project of tokenReadOnly) {
  819. if (
  820. projects.filter(p => p.id.toString() === project._id.toString())
  821. .length === 0
  822. ) {
  823. projects.push(
  824. ProjectController._buildProjectViewModel(
  825. project,
  826. 'readOnly',
  827. Sources.TOKEN,
  828. userId
  829. )
  830. )
  831. }
  832. }
  833. return projects
  834. },
  835. _buildProjectViewModel(project, accessLevel, source, userId) {
  836. const archived = ProjectHelper.isArchived(project, userId)
  837. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  838. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  839. TokenAccessHandler.protectTokens(project, accessLevel)
  840. const model = {
  841. id: project._id,
  842. name: project.name,
  843. lastUpdated: project.lastUpdated,
  844. lastUpdatedBy: project.lastUpdatedBy,
  845. publicAccessLevel: project.publicAccesLevel,
  846. accessLevel,
  847. source,
  848. archived,
  849. trashed,
  850. owner_ref: project.owner_ref,
  851. isV1Project: false
  852. }
  853. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  854. model.owner_ref = null
  855. model.lastUpdatedBy = null
  856. }
  857. return model
  858. },
  859. _injectProjectUsers(projects, callback) {
  860. const users = {}
  861. for (const project of projects) {
  862. if (project.owner_ref != null) {
  863. users[project.owner_ref.toString()] = true
  864. }
  865. if (project.lastUpdatedBy != null) {
  866. users[project.lastUpdatedBy.toString()] = true
  867. }
  868. }
  869. const userIds = Object.keys(users)
  870. async.eachSeries(
  871. userIds,
  872. (userId, cb) => {
  873. UserGetter.getUser(
  874. userId,
  875. { first_name: 1, last_name: 1, email: 1 },
  876. (error, user) => {
  877. if (error != null) {
  878. return cb(error)
  879. }
  880. users[userId] = user
  881. cb()
  882. }
  883. )
  884. },
  885. error => {
  886. if (error != null) {
  887. return callback(error)
  888. }
  889. for (const project of projects) {
  890. if (project.owner_ref != null) {
  891. project.owner = users[project.owner_ref.toString()]
  892. }
  893. if (project.lastUpdatedBy != null) {
  894. project.lastUpdatedBy =
  895. users[project.lastUpdatedBy.toString()] || null
  896. }
  897. }
  898. callback(null, projects)
  899. }
  900. )
  901. },
  902. _buildWarningsList(noConnection) {
  903. return noConnection
  904. ? [
  905. 'Error accessing Overleaf V1. Some of your projects or features may be missing.'
  906. ]
  907. : []
  908. },
  909. _buildPortalTemplatesList(affiliations) {
  910. if (affiliations == null) {
  911. affiliations = []
  912. }
  913. const portalTemplates = []
  914. for (let aff of affiliations) {
  915. if (
  916. aff.portal &&
  917. aff.portal.slug &&
  918. aff.portal.templates_count &&
  919. aff.portal.templates_count > 0
  920. ) {
  921. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  922. portalTemplates.push({
  923. name: aff.institution.name,
  924. url: Settings.siteUrl + portalPath + aff.portal.slug
  925. })
  926. }
  927. }
  928. return portalTemplates
  929. }
  930. }
  931. var defaultSettingsForAnonymousUser = userId => ({
  932. id: userId,
  933. ace: {
  934. mode: 'none',
  935. theme: 'textmate',
  936. fontSize: '12',
  937. autoComplete: true,
  938. spellCheckLanguage: '',
  939. pdfViewer: '',
  940. syntaxValidation: true
  941. },
  942. subscription: {
  943. freeTrial: {
  944. allowed: true
  945. }
  946. },
  947. featureSwitches: {
  948. github: false
  949. }
  950. })
  951. var THEME_LIST = []
  952. function generateThemeList() {
  953. const files = fs.readdirSync(
  954. Path.join(
  955. __dirname,
  956. '/../../../../frontend/js/vendor/',
  957. PackageVersions.lib('ace')
  958. )
  959. )
  960. const result = []
  961. for (let file of files) {
  962. if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
  963. const cleanName = file.slice(0, -3).slice(6)
  964. result.push(THEME_LIST.push(cleanName))
  965. } else {
  966. result.push(undefined)
  967. }
  968. }
  969. }
  970. generateThemeList()
  971. module.exports = ProjectController