ExpressLocals.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  174. res.locals.capitalize = function(string) {
  175. if (string.length === 0) {
  176. return ''
  177. }
  178. return string.charAt(0).toUpperCase() + string.slice(1)
  179. }
  180. next()
  181. })
  182. webRouter.use(function(req, res, next) {
  183. const subdomain = _.find(
  184. Settings.i18n.subdomainLang,
  185. subdomain => subdomain.lngCode === req.showUserOtherLng && !subdomain.hide
  186. )
  187. res.locals.recomendSubdomain = subdomain
  188. res.locals.currentLngCode = req.lng
  189. next()
  190. })
  191. webRouter.use(function(req, res, next) {
  192. res.locals.getUserEmail = function() {
  193. const user = AuthenticationController.getSessionUser(req)
  194. const email = (user != null ? user.email : undefined) || ''
  195. return email
  196. }
  197. next()
  198. })
  199. webRouter.use(function(req, res, next) {
  200. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  201. next()
  202. })
  203. webRouter.use(function(req, res, next) {
  204. res.locals.buildReferalUrl = function(referalMedium) {
  205. let url = Settings.siteUrl
  206. const currentUser = AuthenticationController.getSessionUser(req)
  207. if (
  208. currentUser != null &&
  209. (currentUser != null ? currentUser.referal_id : undefined) != null
  210. ) {
  211. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  212. }
  213. return url
  214. }
  215. res.locals.getReferalId = function() {
  216. const currentUser = AuthenticationController.getSessionUser(req)
  217. if (
  218. currentUser != null &&
  219. (currentUser != null ? currentUser.referal_id : undefined) != null
  220. ) {
  221. return currentUser.referal_id
  222. }
  223. }
  224. next()
  225. })
  226. webRouter.use(function(req, res, next) {
  227. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  228. next()
  229. })
  230. webRouter.use(function(req, res, next) {
  231. res.locals.gaToken = Settings.analytics && Settings.analytics.ga.token
  232. res.locals.gaOptimizeId = _.get(Settings, ['analytics', 'gaOptimize', 'id'])
  233. next()
  234. })
  235. webRouter.use(function(req, res, next) {
  236. res.locals.getReqQueryParam = field =>
  237. req.query != null ? req.query[field] : undefined
  238. next()
  239. })
  240. webRouter.use(function(req, res, next) {
  241. const currentUser = AuthenticationController.getSessionUser(req)
  242. if (currentUser != null) {
  243. res.locals.user = {
  244. email: currentUser.email,
  245. first_name: currentUser.first_name,
  246. last_name: currentUser.last_name
  247. }
  248. }
  249. next()
  250. })
  251. webRouter.use(function(req, res, next) {
  252. res.locals.getLoggedInUserId = () =>
  253. AuthenticationController.getLoggedInUserId(req)
  254. res.locals.getSessionUser = () =>
  255. AuthenticationController.getSessionUser(req)
  256. next()
  257. })
  258. webRouter.use(function(req, res, next) {
  259. // Clone the nav settings so they can be modified for each request
  260. res.locals.nav = {}
  261. for (let key in Settings.nav) {
  262. res.locals.nav[key] = _.clone(Settings.nav[key])
  263. }
  264. res.locals.templates = Settings.templateLinks
  265. next()
  266. })
  267. webRouter.use(function(req, res, next) {
  268. if (Settings.reloadModuleViewsOnEachRequest) {
  269. Modules.loadViewIncludes()
  270. }
  271. res.locals.moduleIncludes = Modules.moduleIncludes
  272. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  273. next()
  274. })
  275. webRouter.use(function(req, res, next) {
  276. res.locals.uiConfig = {
  277. defaultResizerSizeOpen: 7,
  278. defaultResizerSizeClosed: 7,
  279. eastResizerCursor: 'ew-resize',
  280. westResizerCursor: 'ew-resize',
  281. chatResizerSizeOpen: 7,
  282. chatResizerSizeClosed: 0,
  283. chatMessageBorderSaturation: '85%',
  284. chatMessageBorderLightness: '40%',
  285. chatMessageBgSaturation: '85%',
  286. chatMessageBgLightness: '40%'
  287. }
  288. next()
  289. })
  290. webRouter.use(function(req, res, next) {
  291. // TODO
  292. if (Settings.overleaf != null) {
  293. res.locals.overallThemes = [
  294. {
  295. name: 'Default',
  296. val: '',
  297. path: res.locals.buildCssPath(null, { hashedPath: true })
  298. },
  299. {
  300. name: 'Light',
  301. val: 'light-',
  302. path: res.locals.buildCssPath('light-', { hashedPath: true })
  303. }
  304. ]
  305. }
  306. next()
  307. })
  308. webRouter.use(function(req, res, next) {
  309. res.locals.settings = Settings
  310. next()
  311. })
  312. webRouter.use(function(req, res, next) {
  313. res.locals.ExposedSettings = {
  314. isOverleaf: Settings.overleaf != null,
  315. appName: Settings.appName,
  316. hasSamlBeta: req.session.samlBeta,
  317. hasSamlFeature: Features.hasFeature('saml'),
  318. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  319. siteUrl: Settings.siteUrl,
  320. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  321. recaptchaSiteKeyV3:
  322. Settings.recaptcha != null ? Settings.recaptcha.siteKeyV3 : undefined,
  323. recaptchaDisabled:
  324. Settings.recaptcha != null ? Settings.recaptcha.disabled : undefined,
  325. validRootDocExtensions: Settings.validRootDocExtensions
  326. }
  327. next()
  328. })
  329. }