ExpressLocals.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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('../util/promises')
  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. res.locals.entrypointScripts = function (entrypoint) {
  162. const chunks = getWebpackAssets(entrypoint, 'js')
  163. return chunks.map(chunk => staticFilesBase + chunk)
  164. }
  165. res.locals.entrypointStyles = function (entrypoint) {
  166. const chunks = getWebpackAssets(entrypoint, 'css')
  167. return chunks.map(chunk => staticFilesBase + chunk)
  168. }
  169. res.locals.mathJaxPath = `/js/libs/mathjax/MathJax.js?${querystring.stringify(
  170. {
  171. config: 'TeX-AMS_HTML,Safe',
  172. v: require('mathjax/package.json').version,
  173. }
  174. )}`
  175. res.locals.mathJax3Path = `/js/libs/mathjax3/es5/tex-svg-full.js?${querystring.stringify(
  176. {
  177. v: require('mathjax-3/package.json').version,
  178. }
  179. )}`
  180. res.locals.lib = PackageVersions.lib
  181. res.locals.moment = moment
  182. res.locals.isIEEE = brandVariation =>
  183. brandVariation?.brand_id === IEEE_BRAND_ID
  184. res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
  185. // Themes only exist in OL v2
  186. if (Settings.overleaf != null) {
  187. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  188. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  189. if (res.locals.isIEEE(brandVariation)) {
  190. return 'ieee-'
  191. } else if (userSettings && userSettings.overallTheme != null) {
  192. return userSettings.overallTheme
  193. }
  194. }
  195. }
  196. res.locals.buildStylesheetPath = function (cssFileName) {
  197. return staticFilesBase + webpackManifest[cssFileName]
  198. }
  199. res.locals.buildCssPath = function (themeModifier = '') {
  200. if (
  201. res.locals.splitTestVariants?.['design-system-updates'] === 'enabled'
  202. ) {
  203. themeModifier = `main-${themeModifier}`
  204. }
  205. return res.locals.buildStylesheetPath(`${themeModifier}style.css`)
  206. }
  207. res.locals.buildImgPath = function (imgFile) {
  208. const path = Path.join('/img/', imgFile)
  209. return staticFilesBase + path
  210. }
  211. next()
  212. })
  213. webRouter.use(function (req, res, next) {
  214. res.locals.translate = req.i18n.translate
  215. // Don't include the query string parameters, otherwise Google
  216. // treats ?nocdn=true as the canonical version
  217. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  218. res.locals.currentUrl = parsedOriginalUrl.pathname
  219. res.locals.currentUrlWithQueryParams =
  220. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  221. res.locals.capitalize = function (string) {
  222. if (string.length === 0) {
  223. return ''
  224. }
  225. return string.charAt(0).toUpperCase() + string.slice(1)
  226. }
  227. next()
  228. })
  229. webRouter.use(function (req, res, next) {
  230. res.locals.getUserEmail = function () {
  231. const user = SessionManager.getSessionUser(req.session)
  232. const email = (user != null ? user.email : undefined) || ''
  233. return email
  234. }
  235. next()
  236. })
  237. webRouter.use(function (req, res, next) {
  238. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  239. next()
  240. })
  241. webRouter.use(function (req, res, next) {
  242. res.locals.buildReferalUrl = function (referalMedium) {
  243. let url = Settings.siteUrl
  244. const currentUser = SessionManager.getSessionUser(req.session)
  245. if (
  246. currentUser != null &&
  247. (currentUser != null ? currentUser.referal_id : undefined) != null
  248. ) {
  249. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  250. }
  251. return url
  252. }
  253. res.locals.getReferalId = function () {
  254. const currentUser = SessionManager.getSessionUser(req.session)
  255. if (
  256. currentUser != null &&
  257. (currentUser != null ? currentUser.referal_id : undefined) != null
  258. ) {
  259. return currentUser.referal_id
  260. }
  261. }
  262. next()
  263. })
  264. webRouter.use(function (req, res, next) {
  265. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  266. next()
  267. })
  268. webRouter.use(function (req, res, next) {
  269. res.locals.getReqQueryParam = field =>
  270. req.query != null ? req.query[field] : undefined
  271. next()
  272. })
  273. webRouter.use(function (req, res, next) {
  274. const currentUser = SessionManager.getSessionUser(req.session)
  275. if (currentUser != null) {
  276. res.locals.user = {
  277. email: currentUser.email,
  278. first_name: currentUser.first_name,
  279. last_name: currentUser.last_name,
  280. }
  281. }
  282. next()
  283. })
  284. webRouter.use(function (req, res, next) {
  285. res.locals.getLoggedInUserId = () =>
  286. SessionManager.getLoggedInUserId(req.session)
  287. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  288. res.locals.canRedirectToAdminDomain = () =>
  289. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  290. res.locals.hasAdminAccess = () =>
  291. hasAdminAccess(SessionManager.getSessionUser(req.session))
  292. next()
  293. })
  294. webRouter.use(function (req, res, next) {
  295. // Clone the nav settings so they can be modified for each request
  296. res.locals.nav = {}
  297. for (const key in Settings.nav) {
  298. res.locals.nav[key] = _.clone(Settings.nav[key])
  299. }
  300. res.locals.templates = Settings.templateLinks
  301. next()
  302. })
  303. webRouter.use(function (req, res, next) {
  304. if (Settings.reloadModuleViewsOnEachRequest) {
  305. Modules.loadViewIncludes()
  306. }
  307. res.locals.moduleIncludes = Modules.moduleIncludes
  308. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  309. next()
  310. })
  311. webRouter.use(function (req, res, next) {
  312. // TODO
  313. if (Settings.overleaf != null) {
  314. res.locals.overallThemes = [
  315. {
  316. name: 'Default',
  317. val: '',
  318. path: res.locals.buildCssPath(),
  319. },
  320. {
  321. name: 'Light',
  322. val: 'light-',
  323. path: res.locals.buildCssPath('light-'),
  324. },
  325. ]
  326. }
  327. next()
  328. })
  329. webRouter.use(function (req, res, next) {
  330. res.locals.settings = Settings
  331. next()
  332. })
  333. webRouter.use(function (req, res, next) {
  334. res.locals.showThinFooter = !Features.hasFeature('saas')
  335. next()
  336. })
  337. webRouter.use(function (req, res, next) {
  338. res.locals.ExposedSettings = {
  339. isOverleaf: Settings.overleaf != null,
  340. appName: Settings.appName,
  341. adminEmail: Settings.adminEmail,
  342. dropboxAppName:
  343. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  344. hasSamlBeta: req.session.samlBeta,
  345. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  346. hasSamlFeature: Features.hasFeature('saml'),
  347. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  348. hasLinkUrlFeature: Features.hasFeature('link-url'),
  349. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  350. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  351. 'linked-project-output-file'
  352. ),
  353. siteUrl: Settings.siteUrl,
  354. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  355. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  356. maxUploadSize: Settings.maxUploadSize,
  357. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  358. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  359. recaptchaDisabled: Settings.recaptcha?.disabled,
  360. textExtensions: Settings.textExtensions,
  361. validRootDocExtensions: Settings.validRootDocExtensions,
  362. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  363. sentryDsn: Settings.sentry.publicDSN,
  364. sentryEnvironment: Settings.sentry.environment,
  365. sentryRelease: Settings.sentry.release,
  366. enableSubscriptions: Settings.enableSubscriptions,
  367. gaToken:
  368. Settings.analytics &&
  369. Settings.analytics.ga &&
  370. Settings.analytics.ga.token,
  371. gaTokenV4:
  372. Settings.analytics &&
  373. Settings.analytics.ga &&
  374. Settings.analytics.ga.tokenV4,
  375. cookieDomain: Settings.cookieDomain,
  376. templateLinks: Settings.templateLinks,
  377. labsEnabled: Settings.labs && Settings.labs.enable,
  378. }
  379. next()
  380. })
  381. }