ExpressLocals.js 12 KB

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