ExpressLocals.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 request = require('request')
  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. 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, { filename }) {
  92. res.setHeader(
  93. 'Content-Disposition',
  94. contentDisposition(filename, { type })
  95. )
  96. }
  97. next()
  98. }
  99. webRouter.use(addSetContentDisposition)
  100. privateApiRouter.use(addSetContentDisposition)
  101. publicApiRouter.use(addSetContentDisposition)
  102. webRouter.use(function (req, res, next) {
  103. req.externalAuthenticationSystemUsed =
  104. Features.externalAuthenticationSystemUsed
  105. res.locals.externalAuthenticationSystemUsed =
  106. Features.externalAuthenticationSystemUsed
  107. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  108. next()
  109. })
  110. webRouter.use(function (req, res, next) {
  111. let staticFilesBase
  112. const cdnAvailable =
  113. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  114. const cdnBlocked =
  115. req.query.nocdn === 'true' || req.session.cdnBlocked || false
  116. const userId = SessionManager.getLoggedInUserId(req.session)
  117. if (cdnBlocked && req.session.cdnBlocked == null) {
  118. logger.debug(
  119. { userId, ip: req != null ? req.ip : undefined },
  120. 'cdnBlocked for user, not using it and turning it off for future requets'
  121. )
  122. Metrics.inc('no_cdn', 1, {
  123. path: userId ? 'logged-in' : 'pre-login',
  124. method: 'true',
  125. })
  126. req.session.cdnBlocked = true
  127. }
  128. Metrics.inc('cdn_blocked', 1, {
  129. path: userId ? 'logged-in' : 'pre-login',
  130. method: String(cdnBlocked),
  131. })
  132. const host = req.headers && req.headers.host
  133. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  134. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  135. staticFilesBase = Settings.cdn.web.host
  136. } else {
  137. staticFilesBase = ''
  138. }
  139. res.locals.buildBaseAssetPath = function () {
  140. // Return the base asset path (including the CDN url) so that webpack can
  141. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  142. return staticFilesBase + '/'
  143. }
  144. res.locals.buildJsPath = function (jsFile) {
  145. return staticFilesBase + webpackManifest[jsFile]
  146. }
  147. res.locals.buildCopiedJsAssetPath = function (jsFile) {
  148. return staticFilesBase + (webpackManifest[jsFile] || '/' + jsFile)
  149. }
  150. let runtimeEmitted = false
  151. const runtimeChunk = webpackManifest['runtime.js']
  152. res.locals.entrypointScripts = function (entrypoint) {
  153. // Each "entrypoint" contains the runtime chunk as imports.
  154. // Loading the entrypoint twice results in broken execution.
  155. let chunks = getWebpackAssets(entrypoint, 'js')
  156. if (runtimeEmitted) {
  157. chunks = chunks.filter(chunk => chunk !== runtimeChunk)
  158. }
  159. runtimeEmitted = true
  160. return chunks.map(chunk => staticFilesBase + chunk)
  161. }
  162. res.locals.entrypointStyles = function (entrypoint) {
  163. const chunks = getWebpackAssets(entrypoint, 'css')
  164. return chunks.map(chunk => staticFilesBase + chunk)
  165. }
  166. res.locals.mathJaxPath = `/js/libs/mathjax-${PackageVersions.version.mathjax}/es5/tex-svg-full.js`
  167. res.locals.lib = PackageVersions.lib
  168. res.locals.moment = moment
  169. res.locals.isIEEE = brandVariation =>
  170. brandVariation?.brand_id === IEEE_BRAND_ID
  171. res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
  172. // Themes only exist in OL v2
  173. if (Settings.overleaf != null) {
  174. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  175. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  176. if (res.locals.isIEEE(brandVariation)) {
  177. return 'ieee-'
  178. } else if (userSettings && userSettings.overallTheme != null) {
  179. return userSettings.overallTheme
  180. }
  181. }
  182. return ''
  183. }
  184. res.locals.buildStylesheetPath = function (cssFileName) {
  185. return staticFilesBase + webpackManifest[cssFileName]
  186. }
  187. res.locals.buildCssPath = function (themeModifier = '') {
  188. // Pick which main stylesheet to use based on Bootstrap version
  189. const bootstrap5Modifier =
  190. res.locals.bootstrapVersion === 5 ? '-bootstrap-5' : ''
  191. return res.locals.buildStylesheetPath(
  192. `main-${themeModifier}style${bootstrap5Modifier}.css`
  193. )
  194. }
  195. res.locals.buildImgPath = function (imgFile) {
  196. const path = Path.join('/img/', imgFile)
  197. return staticFilesBase + path
  198. }
  199. next()
  200. })
  201. webRouter.use(function (req, res, next) {
  202. res.locals.translate = req.i18n.translate
  203. // Don't include the query string parameters, otherwise Google
  204. // treats ?nocdn=true as the canonical version
  205. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  206. res.locals.currentUrl = parsedOriginalUrl.pathname
  207. res.locals.currentUrlWithQueryParams =
  208. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  209. res.locals.capitalize = function (string) {
  210. if (string.length === 0) {
  211. return ''
  212. }
  213. return string.charAt(0).toUpperCase() + string.slice(1)
  214. }
  215. next()
  216. })
  217. webRouter.use(function (req, res, next) {
  218. res.locals.getUserEmail = function () {
  219. const user = SessionManager.getSessionUser(req.session)
  220. const email = (user != null ? user.email : undefined) || ''
  221. return email
  222. }
  223. next()
  224. })
  225. webRouter.use(function (req, res, next) {
  226. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  227. next()
  228. })
  229. webRouter.use(function (req, res, next) {
  230. res.locals.buildReferalUrl = function (referalMedium) {
  231. let url = Settings.siteUrl
  232. const currentUser = SessionManager.getSessionUser(req.session)
  233. if (
  234. currentUser != null &&
  235. (currentUser != null ? currentUser.referal_id : undefined) != null
  236. ) {
  237. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  238. }
  239. return url
  240. }
  241. res.locals.getReferalId = function () {
  242. const currentUser = SessionManager.getSessionUser(req.session)
  243. if (
  244. currentUser != null &&
  245. (currentUser != null ? currentUser.referal_id : undefined) != null
  246. ) {
  247. return currentUser.referal_id
  248. }
  249. }
  250. next()
  251. })
  252. webRouter.use(function (req, res, next) {
  253. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  254. next()
  255. })
  256. webRouter.use(function (req, res, next) {
  257. res.locals.getReqQueryParam = field =>
  258. req.query != null ? req.query[field] : undefined
  259. next()
  260. })
  261. webRouter.use(function (req, res, next) {
  262. const currentUser = SessionManager.getSessionUser(req.session)
  263. if (currentUser != null) {
  264. res.locals.user = {
  265. email: currentUser.email,
  266. first_name: currentUser.first_name,
  267. last_name: currentUser.last_name,
  268. }
  269. }
  270. next()
  271. })
  272. webRouter.use(function (req, res, next) {
  273. res.locals.getLoggedInUserId = () =>
  274. SessionManager.getLoggedInUserId(req.session)
  275. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  276. res.locals.canRedirectToAdminDomain = () =>
  277. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  278. res.locals.hasAdminAccess = () =>
  279. hasAdminAccess(SessionManager.getSessionUser(req.session))
  280. next()
  281. })
  282. webRouter.use(function (req, res, next) {
  283. // Clone the nav settings so they can be modified for each request
  284. res.locals.nav = {}
  285. for (const key in Settings.nav) {
  286. res.locals.nav[key] = _.clone(Settings.nav[key])
  287. }
  288. res.locals.templates = Settings.templateLinks
  289. next()
  290. })
  291. webRouter.use(function (req, res, next) {
  292. if (Settings.reloadModuleViewsOnEachRequest) {
  293. Modules.loadViewIncludes()
  294. }
  295. res.locals.moduleIncludes = Modules.moduleIncludes
  296. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  297. next()
  298. })
  299. webRouter.use(function (req, res, next) {
  300. // TODO
  301. if (Settings.overleaf != null) {
  302. res.locals.overallThemes = [
  303. {
  304. name: 'Default',
  305. val: '',
  306. path: res.locals.buildCssPath(),
  307. },
  308. {
  309. name: 'Light',
  310. val: 'light-',
  311. path: res.locals.buildCssPath('light-'),
  312. },
  313. ]
  314. }
  315. next()
  316. })
  317. webRouter.use(function (req, res, next) {
  318. res.locals.settings = Settings
  319. next()
  320. })
  321. webRouter.use(function (req, res, next) {
  322. res.locals.showThinFooter = !Features.hasFeature('saas')
  323. next()
  324. })
  325. webRouter.use(function (req, res, next) {
  326. // Set the Bootstrap version to 3 in all cases for now. This will come from
  327. // a split test/feature flag in future.
  328. res.locals.bootstrapVersion = 3
  329. next()
  330. })
  331. webRouter.use(function (req, res, next) {
  332. res.locals.ExposedSettings = {
  333. isOverleaf: Settings.overleaf != null,
  334. appName: Settings.appName,
  335. adminEmail: Settings.adminEmail,
  336. dropboxAppName:
  337. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  338. ieeeBrandId: IEEE_BRAND_ID,
  339. hasSamlBeta: req.session.samlBeta,
  340. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  341. hasSamlFeature: Features.hasFeature('saml'),
  342. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  343. hasLinkUrlFeature: Features.hasFeature('link-url'),
  344. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  345. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  346. 'linked-project-output-file'
  347. ),
  348. siteUrl: Settings.siteUrl,
  349. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  350. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  351. maxUploadSize: Settings.maxUploadSize,
  352. projectUploadTimeout: Settings.projectUploadTimeout,
  353. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  354. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  355. recaptchaDisabled: Settings.recaptcha?.disabled,
  356. textExtensions: Settings.textExtensions,
  357. editableFilenames: Settings.editableFilenames,
  358. validRootDocExtensions: Settings.validRootDocExtensions,
  359. fileIgnorePattern: Settings.fileIgnorePattern,
  360. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  361. sentryDsn: Settings.sentry.publicDSN,
  362. sentryEnvironment: Settings.sentry.environment,
  363. sentryRelease: Settings.sentry.release,
  364. enableSubscriptions: Settings.enableSubscriptions,
  365. gaToken:
  366. Settings.analytics &&
  367. Settings.analytics.ga &&
  368. Settings.analytics.ga.token,
  369. gaTokenV4:
  370. Settings.analytics &&
  371. Settings.analytics.ga &&
  372. Settings.analytics.ga.tokenV4,
  373. cookieDomain: Settings.cookieDomain,
  374. templateLinks: Settings.templateLinks,
  375. labsEnabled: Settings.labs && Settings.labs.enable,
  376. groupSSOEnabled: Settings.groupSSO?.enabled,
  377. wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
  378. templatesEnabled:
  379. Settings.overleaf != null || Settings.templates?.user_id != null,
  380. }
  381. next()
  382. })
  383. }