ExpressLocals.js 13 KB

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