ExpressLocals.js 12 KB

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