ExpressLocals.js 13 KB

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