ExpressLocals.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. const logger = require('@overleaf/logger')
  2. const Metrics = require('@overleaf/metrics')
  3. const Settings = require('@overleaf/settings')
  4. const querystring = require('querystring')
  5. const _ = require('lodash')
  6. const { URL } = require('url')
  7. const Path = require('path')
  8. const moment = require('moment')
  9. const request = require('request')
  10. const contentDisposition = require('content-disposition')
  11. const Features = require('./Features')
  12. const SessionManager = require('../Features/Authentication/SessionManager')
  13. const SplitTestMiddleware = require('../Features/SplitTests/SplitTestMiddleware')
  14. const PackageVersions = require('./PackageVersions')
  15. const Modules = require('./Modules')
  16. const {
  17. canRedirectToAdminDomain,
  18. hasAdminAccess,
  19. } = require('../Features/Helpers/AdminAuthorizationHelper')
  20. const {
  21. addOptionalCleanupHandlerAfterDrainingConnections,
  22. } = require('./GracefulShutdown')
  23. const { expressify } = require('@overleaf/promise-utils')
  24. const IEEE_BRAND_ID = Settings.ieeeBrandId
  25. let webpackManifest
  26. switch (process.env.NODE_ENV) {
  27. case 'production':
  28. // Only load webpack manifest file in production.
  29. webpackManifest = require('../../../public/manifest.json')
  30. break
  31. case 'development': {
  32. // In dev, fetch the manifest from the webpack container.
  33. loadManifestFromWebpackDevServer()
  34. const intervalHandle = setInterval(
  35. loadManifestFromWebpackDevServer,
  36. 10 * 1000
  37. )
  38. addOptionalCleanupHandlerAfterDrainingConnections(
  39. 'refresh webpack manifest',
  40. () => {
  41. clearInterval(intervalHandle)
  42. }
  43. )
  44. break
  45. }
  46. default:
  47. // In ci, all entries are undefined.
  48. webpackManifest = {}
  49. }
  50. function loadManifestFromWebpackDevServer(done = function () {}) {
  51. request(
  52. {
  53. uri: `${Settings.apis.webpack.url}/manifest.json`,
  54. headers: { Host: 'localhost' },
  55. json: true,
  56. },
  57. (err, res, body) => {
  58. if (!err && res.statusCode !== 200) {
  59. err = new Error(`webpack responded with statusCode: ${res.statusCode}`)
  60. }
  61. if (err) {
  62. logger.err({ err }, 'cannot fetch webpack manifest')
  63. return done(err)
  64. }
  65. webpackManifest = body
  66. done()
  67. }
  68. )
  69. }
  70. const IN_CI = process.env.NODE_ENV === 'test'
  71. function getWebpackAssets(entrypoint, section) {
  72. if (IN_CI) {
  73. // Emit an empty list of entries in CI.
  74. return []
  75. }
  76. return webpackManifest.entrypoints[entrypoint].assets[section] || []
  77. }
  78. module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
  79. webRouter.use(
  80. expressify(
  81. SplitTestMiddleware.loadAssignmentsInLocals([
  82. 'design-system-updates',
  83. 'features-page',
  84. ])
  85. )
  86. )
  87. if (process.env.NODE_ENV === 'development') {
  88. // In the dev-env, delay requests until we fetched the manifest once.
  89. webRouter.use(function (req, res, next) {
  90. if (!webpackManifest) {
  91. loadManifestFromWebpackDevServer(next)
  92. } else {
  93. next()
  94. }
  95. })
  96. }
  97. webRouter.use(function (req, res, next) {
  98. res.locals.session = req.session
  99. next()
  100. })
  101. function addSetContentDisposition(req, res, next) {
  102. res.setContentDisposition = function (type, { filename }) {
  103. res.setHeader(
  104. 'Content-Disposition',
  105. contentDisposition(filename, { type })
  106. )
  107. }
  108. next()
  109. }
  110. webRouter.use(addSetContentDisposition)
  111. privateApiRouter.use(addSetContentDisposition)
  112. publicApiRouter.use(addSetContentDisposition)
  113. webRouter.use(function (req, res, next) {
  114. req.externalAuthenticationSystemUsed =
  115. Features.externalAuthenticationSystemUsed
  116. res.locals.externalAuthenticationSystemUsed =
  117. Features.externalAuthenticationSystemUsed
  118. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  119. next()
  120. })
  121. webRouter.use(function (req, res, next) {
  122. let staticFilesBase
  123. const cdnAvailable =
  124. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  125. const cdnBlocked =
  126. req.query.nocdn === 'true' || req.session.cdnBlocked || false
  127. const userId = SessionManager.getLoggedInUserId(req.session)
  128. if (cdnBlocked && req.session.cdnBlocked == null) {
  129. logger.debug(
  130. { userId, ip: req != null ? req.ip : undefined },
  131. 'cdnBlocked for user, not using it and turning it off for future requets'
  132. )
  133. Metrics.inc('no_cdn', 1, {
  134. path: userId ? 'logged-in' : 'pre-login',
  135. method: 'true',
  136. })
  137. req.session.cdnBlocked = true
  138. }
  139. Metrics.inc('cdn_blocked', 1, {
  140. path: userId ? 'logged-in' : 'pre-login',
  141. method: String(cdnBlocked),
  142. })
  143. const host = req.headers && req.headers.host
  144. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  145. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  146. staticFilesBase = Settings.cdn.web.host
  147. } else {
  148. staticFilesBase = ''
  149. }
  150. res.locals.buildBaseAssetPath = function () {
  151. // Return the base asset path (including the CDN url) so that webpack can
  152. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  153. return staticFilesBase + '/'
  154. }
  155. res.locals.buildJsPath = function (jsFile) {
  156. return staticFilesBase + webpackManifest[jsFile]
  157. }
  158. res.locals.buildCopiedJsAssetPath = function (jsFile) {
  159. return staticFilesBase + (webpackManifest[jsFile] || '/' + jsFile)
  160. }
  161. let runtimeEmitted = false
  162. const runtimeChunk = webpackManifest['runtime.js']
  163. res.locals.entrypointScripts = function (entrypoint) {
  164. // Each "entrypoint" contains the runtime chunk as imports.
  165. // Loading the entrypoint twice results in broken execution.
  166. let chunks = getWebpackAssets(entrypoint, 'js')
  167. if (runtimeEmitted) {
  168. chunks = chunks.filter(chunk => chunk !== runtimeChunk)
  169. }
  170. runtimeEmitted = true
  171. return chunks.map(chunk => staticFilesBase + chunk)
  172. }
  173. res.locals.entrypointStyles = function (entrypoint) {
  174. const chunks = getWebpackAssets(entrypoint, 'css')
  175. return chunks.map(chunk => staticFilesBase + chunk)
  176. }
  177. res.locals.mathJaxPath = `/js/libs/mathjax/MathJax.js?${querystring.stringify(
  178. {
  179. config: 'TeX-AMS_HTML,Safe',
  180. v: PackageVersions.version.mathjax,
  181. }
  182. )}`
  183. res.locals.mathJax3Path = `/js/libs/mathjax3/es5/tex-svg-full.js?${querystring.stringify(
  184. {
  185. v: PackageVersions.version['mathjax-3'],
  186. }
  187. )}`
  188. res.locals.lib = PackageVersions.lib
  189. res.locals.moment = moment
  190. res.locals.isIEEE = brandVariation =>
  191. brandVariation?.brand_id === IEEE_BRAND_ID
  192. res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
  193. // Themes only exist in OL v2
  194. if (Settings.overleaf != null) {
  195. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  196. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  197. if (res.locals.isIEEE(brandVariation)) {
  198. return 'ieee-'
  199. } else if (userSettings && userSettings.overallTheme != null) {
  200. return userSettings.overallTheme
  201. }
  202. }
  203. return ''
  204. }
  205. res.locals.buildStylesheetPath = function (cssFileName) {
  206. return staticFilesBase + webpackManifest[cssFileName]
  207. }
  208. res.locals.buildCssPath = function (themeModifier = '') {
  209. if (
  210. res.locals.splitTestVariants?.['design-system-updates'] === 'enabled'
  211. ) {
  212. themeModifier = `main-${themeModifier}`
  213. }
  214. return res.locals.buildStylesheetPath(`${themeModifier}style.css`)
  215. }
  216. res.locals.buildImgPath = function (imgFile) {
  217. const path = Path.join('/img/', imgFile)
  218. return staticFilesBase + path
  219. }
  220. next()
  221. })
  222. webRouter.use(function (req, res, next) {
  223. res.locals.translate = req.i18n.translate
  224. // Don't include the query string parameters, otherwise Google
  225. // treats ?nocdn=true as the canonical version
  226. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  227. res.locals.currentUrl = parsedOriginalUrl.pathname
  228. res.locals.currentUrlWithQueryParams =
  229. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  230. res.locals.capitalize = function (string) {
  231. if (string.length === 0) {
  232. return ''
  233. }
  234. return string.charAt(0).toUpperCase() + string.slice(1)
  235. }
  236. next()
  237. })
  238. webRouter.use(function (req, res, next) {
  239. res.locals.getUserEmail = function () {
  240. const user = SessionManager.getSessionUser(req.session)
  241. const email = (user != null ? user.email : undefined) || ''
  242. return email
  243. }
  244. next()
  245. })
  246. webRouter.use(function (req, res, next) {
  247. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  248. next()
  249. })
  250. webRouter.use(function (req, res, next) {
  251. res.locals.buildReferalUrl = function (referalMedium) {
  252. let url = Settings.siteUrl
  253. const currentUser = SessionManager.getSessionUser(req.session)
  254. if (
  255. currentUser != null &&
  256. (currentUser != null ? currentUser.referal_id : undefined) != null
  257. ) {
  258. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  259. }
  260. return url
  261. }
  262. res.locals.getReferalId = function () {
  263. const currentUser = SessionManager.getSessionUser(req.session)
  264. if (
  265. currentUser != null &&
  266. (currentUser != null ? currentUser.referal_id : undefined) != null
  267. ) {
  268. return currentUser.referal_id
  269. }
  270. }
  271. next()
  272. })
  273. webRouter.use(function (req, res, next) {
  274. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  275. next()
  276. })
  277. webRouter.use(function (req, res, next) {
  278. res.locals.getReqQueryParam = field =>
  279. req.query != null ? req.query[field] : undefined
  280. next()
  281. })
  282. webRouter.use(function (req, res, next) {
  283. const currentUser = SessionManager.getSessionUser(req.session)
  284. if (currentUser != null) {
  285. res.locals.user = {
  286. email: currentUser.email,
  287. first_name: currentUser.first_name,
  288. last_name: currentUser.last_name,
  289. }
  290. }
  291. next()
  292. })
  293. webRouter.use(function (req, res, next) {
  294. res.locals.getLoggedInUserId = () =>
  295. SessionManager.getLoggedInUserId(req.session)
  296. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  297. res.locals.canRedirectToAdminDomain = () =>
  298. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  299. res.locals.hasAdminAccess = () =>
  300. hasAdminAccess(SessionManager.getSessionUser(req.session))
  301. next()
  302. })
  303. webRouter.use(function (req, res, next) {
  304. // Clone the nav settings so they can be modified for each request
  305. res.locals.nav = {}
  306. for (const key in Settings.nav) {
  307. res.locals.nav[key] = _.clone(Settings.nav[key])
  308. }
  309. res.locals.templates = Settings.templateLinks
  310. next()
  311. })
  312. webRouter.use(function (req, res, next) {
  313. if (Settings.reloadModuleViewsOnEachRequest) {
  314. Modules.loadViewIncludes()
  315. }
  316. res.locals.moduleIncludes = Modules.moduleIncludes
  317. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  318. next()
  319. })
  320. webRouter.use(function (req, res, next) {
  321. // TODO
  322. if (Settings.overleaf != null) {
  323. res.locals.overallThemes = [
  324. {
  325. name: 'Default',
  326. val: '',
  327. path: res.locals.buildCssPath(),
  328. },
  329. {
  330. name: 'Light',
  331. val: 'light-',
  332. path: res.locals.buildCssPath('light-'),
  333. },
  334. ]
  335. }
  336. next()
  337. })
  338. webRouter.use(function (req, res, next) {
  339. res.locals.settings = Settings
  340. next()
  341. })
  342. webRouter.use(function (req, res, next) {
  343. res.locals.showThinFooter = !Features.hasFeature('saas')
  344. next()
  345. })
  346. webRouter.use(function (req, res, next) {
  347. res.locals.ExposedSettings = {
  348. isOverleaf: Settings.overleaf != null,
  349. appName: Settings.appName,
  350. adminEmail: Settings.adminEmail,
  351. dropboxAppName:
  352. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  353. hasSamlBeta: req.session.samlBeta,
  354. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  355. hasSamlFeature: Features.hasFeature('saml'),
  356. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  357. hasLinkUrlFeature: Features.hasFeature('link-url'),
  358. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  359. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  360. 'linked-project-output-file'
  361. ),
  362. siteUrl: Settings.siteUrl,
  363. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  364. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  365. maxUploadSize: Settings.maxUploadSize,
  366. projectUploadTimeout: Settings.projectUploadTimeout,
  367. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  368. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  369. recaptchaDisabled: Settings.recaptcha?.disabled,
  370. textExtensions: Settings.textExtensions,
  371. editableFilenames: Settings.editableFilenames,
  372. validRootDocExtensions: Settings.validRootDocExtensions,
  373. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  374. sentryDsn: Settings.sentry.publicDSN,
  375. sentryEnvironment: Settings.sentry.environment,
  376. sentryRelease: Settings.sentry.release,
  377. enableSubscriptions: Settings.enableSubscriptions,
  378. gaToken:
  379. Settings.analytics &&
  380. Settings.analytics.ga &&
  381. Settings.analytics.ga.token,
  382. gaTokenV4:
  383. Settings.analytics &&
  384. Settings.analytics.ga &&
  385. Settings.analytics.ga.tokenV4,
  386. cookieDomain: Settings.cookieDomain,
  387. templateLinks: Settings.templateLinks,
  388. labsEnabled: Settings.labs && Settings.labs.enable,
  389. }
  390. next()
  391. })
  392. }