ExpressLocals.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. const logger = require('logger-sharelatex')
  2. const Settings = require('settings-sharelatex')
  3. const querystring = require('querystring')
  4. const _ = require('lodash')
  5. const Url = require('url')
  6. const Path = require('path')
  7. const moment = require('moment')
  8. const pug = require('pug-runtime')
  9. const IS_DEV_ENV = ['development', 'test'].includes(process.env.NODE_ENV)
  10. const Features = require('./Features')
  11. const AuthenticationController = require('../Features/Authentication/AuthenticationController')
  12. const PackageVersions = require('./PackageVersions')
  13. const Modules = require('./Modules')
  14. const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution')
  15. let webpackManifest
  16. if (!IS_DEV_ENV) {
  17. // Only load webpack manifest file in production. In dev, the web and webpack
  18. // containers can't coordinate, so there no guarantee that the manifest file
  19. // exists when the web server boots. We therefore ignore the manifest file in
  20. // dev reload
  21. webpackManifest = require(`../../../public/manifest.json`)
  22. }
  23. const I18N_HTML_INJECTIONS = new Set()
  24. module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
  25. webRouter.use(function(req, res, next) {
  26. res.locals.session = req.session
  27. next()
  28. })
  29. webRouter.use(function(req, res, next) {
  30. res.locals.isIE = /\b(msie|trident)\b/i.test(req.headers['user-agent'])
  31. next()
  32. })
  33. function addSetContentDisposition(req, res, next) {
  34. res.setContentDisposition = function(type, opts) {
  35. const directives = _.map(
  36. opts,
  37. (v, k) => `${k}="${encodeURIComponent(v)}"`
  38. )
  39. const contentDispositionValue = `${type}; ${directives.join('; ')}`
  40. res.setHeader('Content-Disposition', contentDispositionValue)
  41. }
  42. next()
  43. }
  44. webRouter.use(addSetContentDisposition)
  45. privateApiRouter.use(addSetContentDisposition)
  46. publicApiRouter.use(addSetContentDisposition)
  47. webRouter.use(function(req, res, next) {
  48. req.externalAuthenticationSystemUsed =
  49. Features.externalAuthenticationSystemUsed
  50. res.locals.externalAuthenticationSystemUsed =
  51. Features.externalAuthenticationSystemUsed
  52. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  53. next()
  54. })
  55. webRouter.use(function(req, res, next) {
  56. let staticFilesBase
  57. const cdnAvailable =
  58. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  59. const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked
  60. const userId = AuthenticationController.getLoggedInUserId(req)
  61. if (cdnBlocked && req.session.cdnBlocked == null) {
  62. logger.log(
  63. { user_id: userId, ip: req != null ? req.ip : undefined },
  64. 'cdnBlocked for user, not using it and turning it off for future requets'
  65. )
  66. req.session.cdnBlocked = true
  67. }
  68. const host = req.headers && req.headers.host
  69. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  70. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  71. staticFilesBase = Settings.cdn.web.host
  72. } else {
  73. staticFilesBase = ''
  74. }
  75. res.locals.buildBaseAssetPath = function() {
  76. // Return the base asset path (including the CDN url) so that webpack can
  77. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  78. return Url.resolve(staticFilesBase, '/')
  79. }
  80. res.locals.buildJsPath = function(jsFile) {
  81. let path
  82. if (IS_DEV_ENV) {
  83. // In dev: resolve path within JS asset directory
  84. // We are *not* guaranteed to have a manifest file when the server
  85. // starts up
  86. path = Path.join('/js', jsFile)
  87. } else {
  88. // In production: resolve path from webpack manifest file
  89. // We are guaranteed to have a manifest file since webpack compiles in
  90. // the build
  91. path = `/${webpackManifest[jsFile]}`
  92. }
  93. return Url.resolve(staticFilesBase, path)
  94. }
  95. // Temporary hack while jQuery/Angular dependencies are *not* bundled,
  96. // instead copied into output directory
  97. res.locals.buildCopiedJsAssetPath = function(jsFile) {
  98. let path
  99. if (IS_DEV_ENV) {
  100. // In dev: resolve path to root directory
  101. // We are *not* guaranteed to have a manifest file when the server
  102. // starts up
  103. path = Path.join('/', jsFile)
  104. } else {
  105. // In production: resolve path from webpack manifest file
  106. // We are guaranteed to have a manifest file since webpack compiles in
  107. // the build
  108. path = `/${webpackManifest[jsFile]}`
  109. }
  110. return Url.resolve(staticFilesBase, path)
  111. }
  112. res.locals.mathJaxPath = `/js/libs/mathjax/MathJax.js?${querystring.stringify(
  113. {
  114. config: 'TeX-AMS_HTML,Safe'
  115. }
  116. )}`
  117. res.locals.lib = PackageVersions.lib
  118. res.locals.moment = moment
  119. const IEEE_BRAND_ID = 15
  120. res.locals.isIEEE = brandVariation =>
  121. (brandVariation != null ? brandVariation.brand_id : undefined) ===
  122. IEEE_BRAND_ID
  123. res.locals.getCssThemeModifier = function(userSettings, brandVariation) {
  124. // Themes only exist in OL v2
  125. if (Settings.overleaf != null) {
  126. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  127. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  128. if (res.locals.isIEEE(brandVariation)) {
  129. return 'ieee-'
  130. } else if (userSettings && userSettings.overallTheme != null) {
  131. return userSettings.overallTheme
  132. }
  133. }
  134. }
  135. res.locals.buildCssPath = function(themeModifier = '') {
  136. const cssFileName = `${themeModifier}style.css`
  137. let path
  138. if (IS_DEV_ENV) {
  139. // In dev: resolve path within CSS asset directory
  140. // We are *not* guaranteed to have a manifest file when the server
  141. // starts up
  142. path = Path.join('/stylesheets/', cssFileName)
  143. } else {
  144. // In production: resolve path from webpack manifest file
  145. // We are guaranteed to have a manifest file since webpack compiles in
  146. // the build
  147. path = `/${webpackManifest[cssFileName]}`
  148. }
  149. return Url.resolve(staticFilesBase, path)
  150. }
  151. res.locals.buildImgPath = function(imgFile) {
  152. const path = Path.join('/img/', imgFile)
  153. return Url.resolve(staticFilesBase, path)
  154. }
  155. next()
  156. })
  157. webRouter.use(function(req, res, next) {
  158. res.locals.translate = function(key, vars, components) {
  159. vars = vars || {}
  160. if (Settings.i18n.checkForHTMLInVars) {
  161. Object.entries(vars).forEach(([field, value]) => {
  162. if (pug.escape(value) !== value) {
  163. const violationsKey = key + field
  164. // do not flood the logs, log one sample per pod + key + field
  165. if (!I18N_HTML_INJECTIONS.has(violationsKey)) {
  166. logger.warn(
  167. { key, field, value },
  168. 'html content in translations context vars'
  169. )
  170. I18N_HTML_INJECTIONS.add(violationsKey)
  171. }
  172. }
  173. })
  174. }
  175. vars.appName = Settings.appName
  176. const locale = req.i18n.translate(key, vars)
  177. if (components) {
  178. return SafeHTMLSubstitute.render(locale, components)
  179. } else {
  180. return locale
  181. }
  182. }
  183. // Don't include the query string parameters, otherwise Google
  184. // treats ?nocdn=true as the canonical version
  185. const parsedOriginalUrl = Url.parse(req.originalUrl)
  186. res.locals.currentUrl = parsedOriginalUrl.pathname
  187. res.locals.currentUrlWithQueryParams = parsedOriginalUrl.path
  188. res.locals.capitalize = function(string) {
  189. if (string.length === 0) {
  190. return ''
  191. }
  192. return string.charAt(0).toUpperCase() + string.slice(1)
  193. }
  194. next()
  195. })
  196. webRouter.use(function(req, res, next) {
  197. res.locals.getUserEmail = function() {
  198. const user = AuthenticationController.getSessionUser(req)
  199. const email = (user != null ? user.email : undefined) || ''
  200. return email
  201. }
  202. next()
  203. })
  204. webRouter.use(function(req, res, next) {
  205. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  206. next()
  207. })
  208. webRouter.use(function(req, res, next) {
  209. res.locals.buildReferalUrl = function(referalMedium) {
  210. let url = Settings.siteUrl
  211. const currentUser = AuthenticationController.getSessionUser(req)
  212. if (
  213. currentUser != null &&
  214. (currentUser != null ? currentUser.referal_id : undefined) != null
  215. ) {
  216. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  217. }
  218. return url
  219. }
  220. res.locals.getReferalId = function() {
  221. const currentUser = AuthenticationController.getSessionUser(req)
  222. if (
  223. currentUser != null &&
  224. (currentUser != null ? currentUser.referal_id : undefined) != null
  225. ) {
  226. return currentUser.referal_id
  227. }
  228. }
  229. next()
  230. })
  231. webRouter.use(function(req, res, next) {
  232. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  233. next()
  234. })
  235. webRouter.use(function(req, res, next) {
  236. res.locals.gaToken =
  237. Settings.analytics && Settings.analytics.ga && Settings.analytics.ga.token
  238. res.locals.gaOptimizeId = _.get(Settings, ['analytics', 'gaOptimize', 'id'])
  239. next()
  240. })
  241. webRouter.use(function(req, res, next) {
  242. res.locals.getReqQueryParam = field =>
  243. req.query != null ? req.query[field] : undefined
  244. next()
  245. })
  246. webRouter.use(function(req, res, next) {
  247. const currentUser = AuthenticationController.getSessionUser(req)
  248. if (currentUser != null) {
  249. res.locals.user = {
  250. email: currentUser.email,
  251. first_name: currentUser.first_name,
  252. last_name: currentUser.last_name
  253. }
  254. }
  255. next()
  256. })
  257. webRouter.use(function(req, res, next) {
  258. res.locals.getLoggedInUserId = () =>
  259. AuthenticationController.getLoggedInUserId(req)
  260. res.locals.getSessionUser = () =>
  261. AuthenticationController.getSessionUser(req)
  262. next()
  263. })
  264. webRouter.use(function(req, res, next) {
  265. // Clone the nav settings so they can be modified for each request
  266. res.locals.nav = {}
  267. for (let key in Settings.nav) {
  268. res.locals.nav[key] = _.clone(Settings.nav[key])
  269. }
  270. res.locals.templates = Settings.templateLinks
  271. next()
  272. })
  273. webRouter.use(function(req, res, next) {
  274. if (Settings.reloadModuleViewsOnEachRequest) {
  275. Modules.loadViewIncludes()
  276. }
  277. res.locals.moduleIncludes = Modules.moduleIncludes
  278. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  279. next()
  280. })
  281. webRouter.use(function(req, res, next) {
  282. res.locals.uiConfig = {
  283. defaultResizerSizeOpen: 7,
  284. defaultResizerSizeClosed: 7,
  285. eastResizerCursor: 'ew-resize',
  286. westResizerCursor: 'ew-resize',
  287. chatResizerSizeOpen: 7,
  288. chatResizerSizeClosed: 0,
  289. chatMessageBorderSaturation: '85%',
  290. chatMessageBorderLightness: '40%',
  291. chatMessageBgSaturation: '85%',
  292. chatMessageBgLightness: '40%'
  293. }
  294. next()
  295. })
  296. webRouter.use(function(req, res, next) {
  297. // TODO
  298. if (Settings.overleaf != null) {
  299. res.locals.overallThemes = [
  300. {
  301. name: 'Default',
  302. val: '',
  303. path: res.locals.buildCssPath()
  304. },
  305. {
  306. name: 'Light',
  307. val: 'light-',
  308. path: res.locals.buildCssPath('light-')
  309. }
  310. ]
  311. }
  312. next()
  313. })
  314. webRouter.use(function(req, res, next) {
  315. res.locals.settings = Settings
  316. next()
  317. })
  318. webRouter.use(function(req, res, next) {
  319. res.locals.ExposedSettings = {
  320. isOverleaf: Settings.overleaf != null,
  321. appName: Settings.appName,
  322. hasSamlBeta: req.session.samlBeta,
  323. hasSamlFeature: Features.hasFeature('saml'),
  324. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  325. siteUrl: Settings.siteUrl,
  326. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  327. recaptchaSiteKeyV3:
  328. Settings.recaptcha != null ? Settings.recaptcha.siteKeyV3 : undefined,
  329. recaptchaDisabled:
  330. Settings.recaptcha != null ? Settings.recaptcha.disabled : undefined,
  331. validRootDocExtensions: Settings.validRootDocExtensions,
  332. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  333. sentryDsn: Settings.sentry.publicDSN,
  334. sentryEnvironment: Settings.sentry.environment,
  335. sentryRelease: Settings.sentry.release,
  336. enableSubscriptions: Settings.enableSubscriptions
  337. }
  338. next()
  339. })
  340. }